1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License..

//! Get the metadata of the current enclave.
//!
//! This mod has clear interface and is easy to understand. Currently we don't
//! have time for its documents.

use sgx_types::metadata::*;
use sgx_types::*;

pub const LAYOUT_ENTRY_NUM: usize = 42;

#[link(name = "sgx_trts")]
extern "C" {
    static g_global_data: global_data_t;
    static g_cpu_feature_indicator: uint64_t;
    static g_cpu_core_num: uint32_t;
    static EDMM_supported: c_int;
    pub fn get_thread_data() -> *const c_void;
    pub fn get_enclave_base() -> *const c_void;
    pub fn get_heap_base() -> *const c_void;
    pub fn get_heap_size() -> size_t;
    pub fn get_rsrv_base() -> *const c_void;
    pub fn get_rsrv_size() -> size_t;
}

#[repr(C)]
pub struct global_data_t {
    pub sdk_version: usize,
    pub enclave_size: usize,
    pub heap_offset: usize,
    pub heap_size: usize,
    pub rsrv_offset: usize,
    pub rsrv_size: usize,
    pub rsrv_executable: usize,
    pub thread_policy: usize,
    pub tcs_max_num: usize,
    pub td_template: thread_data_t,
    pub tcs_template: [u8; TCS_TEMPLATE_SIZE],
    pub layout_entry_num: u32,
    pub reserved: u32,
    pub layout_table: [layout_t; LAYOUT_ENTRY_NUM],
}

#[repr(C)]
pub struct thread_data_t {
    pub self_addr: usize,
    pub last_sp: usize,
    pub stack_base_addr: usize,
    pub stack_limit_addr: usize,
    pub first_ssa_gpr: usize,
    pub stack_guard: usize,
    pub flags: usize,
    pub xsave_size: usize,
    pub last_error: usize,
    pub m_next: usize,
    pub tls_addr: usize,
    pub tls_array: usize,
    pub exception_flag: usize,
    pub cxx_thread_info: [usize; 6],
    pub stack_commit_addr: usize,
}

#[derive(Copy, Clone)]
pub struct SgxGlobalData {
    enclave_base: usize,
    enclave_size: usize,
    heap_base: usize,
    heap_offset: usize,
    heap_size: usize,
    rsrv_base: usize,
    rsrv_offset: usize,
    rsrv_size: usize,
    thread_policy: SgxThreadPolicy,
    static_tcs_num: u32, // minpool thread + utility thread
    eremove_tcs_num: u32,
    dyn_tcs_num: u32,
    max_tcs_num: u32,
}

impl Default for SgxGlobalData {
    fn default() -> Self {
        Self::new()
    }
}

impl SgxGlobalData {
    ///
    /// get global_data.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn new() -> Self {
        let (static_num, eremove_num, dyn_num) = rsgx_get_tcs_num();
        SgxGlobalData {
            enclave_base: rsgx_get_enclave_base() as usize,
            enclave_size: rsgx_get_enclave_size(),
            heap_base: rsgx_get_heap_base() as usize,
            heap_offset: rsgx_get_heap_offset(),
            heap_size: rsgx_get_heap_size(),
            rsrv_base: rsgx_get_rsrv_base() as usize,
            rsrv_offset: rsgx_get_rsrv_offset(),
            rsrv_size: rsgx_get_rsrv_size(),
            thread_policy: rsgx_get_thread_policy(),
            static_tcs_num: static_num,
            eremove_tcs_num: eremove_num,
            dyn_tcs_num: dyn_num,
            max_tcs_num: rsgx_get_tcs_max_num(),
        }
    }

    ///
    /// enclave_base is to get enclave map base address.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn enclave_base(&self) -> usize {
        self.enclave_base
    }
    ///
    /// enclave_size is to get enclave map size.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn enclave_size(&self) -> usize {
        self.enclave_size
    }
    ///
    /// heap_base is to get heap base address.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn heap_base(&self) -> usize {
        self.heap_base
    }
    ///
    /// heap_offset is to get heap offset.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn heap_offset(&self) -> usize {
        self.heap_offset
    }
    ///
    /// heap_size is to get heap size.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn heap_size(&self) -> usize {
        self.heap_size
    }
    ///
    /// rsrv_base is to get rsrv base address.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn rsrv_base(&self) -> usize {
        self.rsrv_base
    }
    ///
    /// rsrv_offset is to get heap offset.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn rsrv_offset(&self) -> usize {
        self.rsrv_offset
    }
    ///
    /// rsrv_size is to get heap size.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn rsrv_size(&self) -> usize {
        self.rsrv_size
    }
    ///
    /// thread_policy is to get TCS policy.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn thread_policy(&self) -> SgxThreadPolicy {
        self.thread_policy
    }

    pub fn get_static_tcs_num(&self) -> u32 {
        self.static_tcs_num
    }

    pub fn get_eremove_tcs_num(&self) -> u32 {
        self.eremove_tcs_num
    }

    pub fn get_dyn_tcs_num(&self) -> u32 {
        self.dyn_tcs_num
    }

    pub fn get_tcs_max_num(&self) -> u32 {
        self.max_tcs_num
        //if rsgx_is_supported_EDMM() {
        //    if self.dyn_tcs_num != 0 {
        //        self.static_tcs_num + self.dyn_tcs_num - 1 // - 1 is utility thread
        //    } else {
        //        self.static_tcs_num
        //    }
        //} else {
        //    self.static_tcs_num + self.eremove_tcs_num
        //}
    }
}

#[allow(dead_code)]
#[derive(Copy, Clone, Default)]
pub struct SgxThreadData {
    td_addr: usize,
    last_sp: usize,
    stack_base_addr: usize,
    stack_limit_addr: usize,
    first_ssa_gpr: usize,
    stack_guard: usize,
    xsave_size: usize,
    last_error: usize,
    tls_addr: usize,
    tls_array: usize,
    exception_flag: usize,
    cxx_thread_info: [usize; 6],
}

impl SgxThreadData {
    ///
    /// get thread_data per thread.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    #[allow(clippy::cast_ptr_alignment)]
    pub fn current() -> Self {
        let td = unsafe {
            let p = rsgx_get_thread_data();
            &*p
        };
        SgxThreadData {
            td_addr: td.self_addr,
            last_sp: td.last_sp,
            stack_base_addr: td.stack_base_addr,
            stack_limit_addr: td.stack_limit_addr,
            first_ssa_gpr: td.first_ssa_gpr,
            stack_guard: td.stack_guard,
            xsave_size: td.xsave_size,
            last_error: td.last_error,
            tls_addr: td.tls_addr,
            tls_array: td.tls_array,
            exception_flag: td.exception_flag,
            cxx_thread_info: td.cxx_thread_info,
        }
    }

    pub unsafe fn from_raw(raw: sgx_thread_t) -> Self {
        let p = raw as *const thread_data_t;
        let td = &*p;
        SgxThreadData {
            td_addr: td.self_addr,
            last_sp: td.last_sp,
            stack_base_addr: td.stack_base_addr,
            stack_limit_addr: td.stack_limit_addr,
            first_ssa_gpr: td.first_ssa_gpr,
            stack_guard: td.stack_guard,
            xsave_size: td.xsave_size,
            last_error: td.last_error,
            tls_addr: td.tls_addr,
            tls_array: td.tls_array,
            exception_flag: td.exception_flag,
            cxx_thread_info: td.cxx_thread_info,
        }
    }

    ///
    /// td_base is to get TD base address per thread.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn td_base(&self) -> usize {
        self.td_addr
    }
    ///
    /// stack_base is to get stack base address per thread.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn stack_base(&self) -> usize {
        self.stack_base_addr
    }
    ///
    /// stack_limit is to get stack limit per thread.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn stack_limit(&self) -> usize {
        self.stack_limit_addr
    }
    ///
    /// tls_base is to get tls base address per thread.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn tls_base(&self) -> usize {
        self.tls_addr
    }
    ///
    /// last_error is to get last error per thread.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn last_error(&self) -> usize {
        self.last_error
    }
    ///
    /// exception_flag is to get exception flag per thread.
    ///
    /// **Note**
    ///
    /// This API is only an experimental funtion.
    ///
    pub fn exception_flag(&self) -> usize {
        self.exception_flag
    }

    pub fn get_tcs(&self) -> usize {
        self.stack_base() + STATIC_STACK_SIZE + SE_GUARD_PAGE_SIZE
    }
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum SgxThreadPolicy {
    Bound,
    Unbound,
}

///
/// rsgx_get_thread_data is to get TD base address per thread.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_thread_data() -> *const thread_data_t {
    unsafe { get_thread_data() as *const thread_data_t }
}

///
/// rsgx_get_enclave_base is to get enclave image base address.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_enclave_base() -> *const u8 {
    unsafe { get_enclave_base() as *const u8 }
}

///
/// rsgx_get_enclave_size is to get enclave image size.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_enclave_size() -> usize {
    unsafe { g_global_data.enclave_size }
}

///
/// rsgx_get_heap_base is to get enclave heap base address.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_heap_base() -> *const u8 {
    unsafe { get_heap_base() as *const u8 }
}

///
/// rsgx_get_heap_offset is to get enclave heap offset.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_heap_offset() -> usize {
    unsafe { g_global_data.heap_offset }
}

///
/// rsgx_get_heap_size is to get enclave heap size.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_heap_size() -> usize {
    unsafe { get_heap_size() }
}

///
/// rsgx_get_rsrv_base is to get enclave rsrv base address.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_rsrv_base() -> *const u8 {
    unsafe { get_rsrv_base() as *const u8 }
}

///
/// rsgx_get_rsrv_offset is to get enclave rsrv offset.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_rsrv_offset() -> usize {
    unsafe { g_global_data.rsrv_offset }
}

///
/// rsgx_get_rsrv_size is to get enclave rsrv size.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_rsrv_size() -> usize {
    unsafe { get_rsrv_size() }
}

///
/// rsgx_get_thread_policy is to get TCS management policy.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_thread_policy() -> SgxThreadPolicy {
    unsafe {
        if g_global_data.thread_policy != 0 {
            SgxThreadPolicy::Unbound
        } else {
            SgxThreadPolicy::Bound
        }
    }
}

///
/// rsgx_get_global_data is to get global_data base address.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_global_data() -> *const global_data_t {
    unsafe { &g_global_data as *const global_data_t }
}

///
/// rsgx_get_tcs_max_num is to get max tcs number.
///
/// **Note**
///
/// This API is only an experimental funtion.
///
#[inline]
pub fn rsgx_get_tcs_max_num() -> u32 {
    unsafe { g_global_data.tcs_max_num as u32 }
}

pub fn rsgx_get_tcs_num() -> (u32, u32, u32) {
    let gd = unsafe {
        let p = rsgx_get_global_data();
        &*p
    };

    let mut static_tcs_num: u32 = 0;
    let mut eremove_tcs_num: u32 = 0;
    let mut dyn_tcs_num: u32 = 0;
    let layout_table = &gd.layout_table[0..gd.layout_entry_num as usize];
    unsafe {
        traversal_layout(
            &mut static_tcs_num,
            &mut dyn_tcs_num,
            &mut eremove_tcs_num,layout_table,
        );
    }

    unsafe fn traversal_layout(
        static_num: &mut u32,
        dyn_num: &mut u32,
        eremove_num: &mut u32,
        layout_table: &[layout_t],
    ) {
        for (i, layout) in layout_table.iter().enumerate() {
            if !is_group_id!(layout.group.id as u32) {
                if (layout.entry.attributes & PAGE_ATTR_EADD) != 0 {
                    if (layout.entry.content_offset != 0) && (layout.entry.si_flags == SI_FLAGS_TCS) {
                        if (layout.entry.attributes & PAGE_ATTR_EREMOVE) == 0 {
                            *static_num += 1;
                        } else {
                            *eremove_num += 1;
                        }
                    }
                }
                if (layout.entry.attributes & PAGE_ATTR_POST_ADD) != 0 {
                    if layout.entry.id == LAYOUT_ID_TCS_DYN as u16 {
                        *dyn_num += 1;
                    }
                }
            } else {
                for _ in 0..layout.group.load_times {
                    traversal_layout(static_num, dyn_num, eremove_num, &layout_table[i-layout.group.entry_count as usize..i])
                }
            }
        }
    }
    (static_tcs_num, eremove_tcs_num, dyn_tcs_num)
}

#[inline]
pub fn rsgx_is_supported_EDMM() -> bool {
    // cpu support
    // sgx driver support
    // sgx sdk support ( uRTS and enclave metadata)
    // hw mode
    unsafe { EDMM_supported != 0 }
}

#[inline]
pub fn rsgx_get_cpu_feature() -> u64 {
    unsafe { g_cpu_feature_indicator }
}

#[inline]
pub fn rsgx_get_cpu_core_num() -> u32 {
    unsafe { g_cpu_core_num }
}