You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@teaclave.apache.org by di...@apache.org on 2020/04/18 23:32:42 UTC

[incubator-teaclave-sgx-sdk] branch v1.1.2-testing created (now 2692d25)

This is an automated email from the ASF dual-hosted git repository.

dingyu pushed a change to branch v1.1.2-testing
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave-sgx-sdk.git.


      at 2692d25  v1.1.2 initial commit

This branch includes the following new commits:

     new 2692d25  v1.1.2 initial commit

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org


[incubator-teaclave-sgx-sdk] 01/01: v1.1.2 initial commit

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dingyu pushed a commit to branch v1.1.2-testing
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave-sgx-sdk.git

commit 2692d251154518e10b8138a8cfb4d45c38c878df
Author: Yu Ding <di...@gmail.com>
AuthorDate: Sat Apr 18 16:31:42 2020 -0700

    v1.1.2 initial commit
---
 samplecode/backtrace/enclave/Xargo.toml            |    5 +-
 samplecode/backtrace/enclave/src/lib.rs            |   23 +-
 samplecode/crypto/enclave/Xargo.toml               |    4 +
 samplecode/db-proxy/db-proxy/enclave/Xargo.toml    |    4 +
 samplecode/file/enclave/Xargo.toml                 |    4 +
 samplecode/hello-regex/enclave/Xargo.toml          |    4 +
 .../hello-rust-vscode-debug/enclave/Xargo.toml     |    4 +
 samplecode/hello-rust/enclave/Xargo.toml           |    4 +
 samplecode/helloworld/enclave/Xargo.toml           |    4 +
 samplecode/http_req/enclave/Xargo.toml             |    4 +
 samplecode/hugemem/enclave/Xargo.toml              |    4 +
 samplecode/kvdb-memdb/enclave/Xargo.toml           |    4 +
 samplecode/localattestation/attestation/Xargo.toml |    4 +
 samplecode/localattestation/enclave1/Xargo.toml    |    5 +-
 samplecode/localattestation/enclave2/Xargo.toml    |    5 +-
 samplecode/localattestation/enclave3/Xargo.toml    |    5 +-
 samplecode/logger/enclave/Xargo.toml               |    5 +-
 samplecode/machine-learning/enclave/Xargo.toml     |    5 +-
 samplecode/mio/client/enclave/Xargo.toml           |    5 +-
 samplecode/mio/server/enclave/Xargo.toml           |    5 +-
 samplecode/mutual-ra/enclave/Xargo.toml            |    5 +-
 samplecode/net2/enclave/Xargo.toml                 |    5 +-
 samplecode/pcl/encrypted-hello/enclave/Xargo.toml  |    5 +-
 samplecode/pcl/pcl-seal/enclave/Xargo.toml         |    5 +-
 samplecode/prost-protobuf/enclave/Xargo.toml       |    4 +
 samplecode/protobuf/enclave/Xargo.toml             |    5 +-
 samplecode/psi/SMCServer/enclave/Xargo.toml        |    5 +-
 .../Application/enclave/Xargo.toml                 |    5 +-
 samplecode/sealeddata/enclave/Xargo.toml           |    5 +-
 samplecode/secretsharing/enclave/Xargo.toml        |    5 +-
 samplecode/serialize/enclave/Xargo.toml            |    5 +-
 samplecode/sgx-cov/enclave/Xargo.toml              |    4 +
 .../static-data-distribution/enclave/Xargo.toml    |    5 +-
 samplecode/switchless/enclave/Xargo.toml           |    5 +-
 samplecode/tcmalloc/enclave/Xargo.toml             |    5 +-
 samplecode/thread/enclave/Xargo.toml               |    5 +-
 samplecode/tls/tlsclient/enclave/Xargo.toml        |    5 +-
 samplecode/tls/tlsserver/enclave/Xargo.toml        |    5 +-
 samplecode/tr-mpc/tr-mpc-server/enclave/Xargo.toml |    5 +-
 samplecode/ue-ra/ue-ra-server/enclave/Xargo.toml   |    5 +-
 samplecode/unit-test/enclave/Cargo.toml            |    7 +-
 samplecode/unit-test/enclave/Enclave.edl           |    2 +
 samplecode/unit-test/enclave/Xargo.toml            |    6 +-
 samplecode/unit-test/enclave/src/lib.rs            |   17 +-
 samplecode/unit-test/enclave/src/test_exception.rs |   81 ++
 samplecode/unit-test/enclave/src/test_rand.rs      |   14 +-
 samplecode/unit-test/enclave/src/test_rts.rs       |   20 +-
 samplecode/unit-test/enclave/src/test_signal.rs    |  128 ++
 samplecode/wasmi/enclave/Xargo.toml                |    5 +-
 .../zlib-lazy-static-sample/enclave/Xargo.toml     |    5 +-
 sgx_align_struct_attribute/Cargo.toml              |    2 +-
 sgx_align_struct_attribute/src/align.rs            |   41 +-
 sgx_align_struct_attribute/src/layout.rs           |    2 +-
 sgx_alloc/Cargo.toml                               |    2 +-
 sgx_alloc/src/alignalloc.rs                        |   12 +-
 sgx_alloc/src/alignbox.rs                          |   28 +-
 sgx_alloc/src/lib.rs                               |    1 +
 sgx_alloc/src/rsrvmem.rs                           |    2 +-
 sgx_alloc/src/system.rs                            |  131 +-
 sgx_backtrace/Cargo.toml                           |    9 +-
 sgx_backtrace/src/backtrace/libunwind.rs           |  101 +-
 sgx_backtrace/src/backtrace/mod.rs                 |    2 +-
 sgx_backtrace/src/capture.rs                       |   81 +-
 sgx_backtrace/src/lib.rs                           |   19 +-
 sgx_backtrace/src/print.rs                         |  254 ++++
 sgx_backtrace/src/symbolize/libbacktrace.rs        |  102 +-
 sgx_backtrace/src/symbolize/mod.rs                 |   24 +-
 sgx_backtrace/src/types.rs                         |    2 -
 sgx_backtrace_sys/Cargo.toml                       |    2 +-
 sgx_backtrace_sys/src/lib.rs                       |   60 +-
 sgx_build_helper/lib.rs                            |   45 +-
 sgx_cov/Cargo.toml                                 |    2 +-
 sgx_crypto_helper/Cargo.toml                       |   43 +-
 sgx_demangle/Cargo.toml                            |    2 +-
 sgx_libc/Cargo.toml                                |    2 +-
 sgx_libc/src/linux/x86_64/mod.rs                   |  166 ++-
 sgx_libc/src/linux/x86_64/ocall.rs                 |  117 +-
 sgx_libc/src/macros.rs                             |    1 -
 sgx_no_tstd/Cargo.toml                             |    2 +-
 sgx_no_tstd/build.rs                               |   26 +-
 sgx_no_tstd/src/lib.rs                             |    6 +-
 sgx_panic_abort/lib.rs                             |   21 +-
 sgx_panic_unwind/dwarf/eh.rs                       |   50 +-
 sgx_panic_unwind/dwarf/mod.rs                      |    2 +-
 sgx_panic_unwind/gcc.rs                            |   90 +-
 sgx_panic_unwind/lib.rs                            |   58 +-
 sgx_rand/Cargo.toml                                |    2 +-
 sgx_rand/src/chacha.rs                             |    8 +-
 sgx_rand/src/lib.rs                                |    2 +-
 sgx_rand/src/read.rs                               |    6 +-
 sgx_rand_derive/Cargo.toml                         |    2 +-
 sgx_serialize/Cargo.toml                           |    2 +-
 sgx_serialize/src/leb128.rs                        |    6 +-
 sgx_serialize/src/lib.rs                           |    2 +-
 sgx_serialize/src/serialize.rs                     |  356 ++++--
 sgx_serialize_derive/Cargo.toml                    |    2 +-
 sgx_serialize_derive_internals/Cargo.toml          |    2 +-
 {sgx_rand => sgx_signal}/Cargo.toml                |   10 +-
 sgx_signal/src/exception.rs                        |  260 ++++
 {sgx_serialize => sgx_signal}/src/lib.rs           |   24 +-
 sgx_signal/src/manager.rs                          |  320 +++++
 sgx_signal/src/signal.rs                           |  366 ++++++
 sgx_tcrypto/Cargo.toml                             |    2 +-
 sgx_tcrypto/src/crypto.rs                          | 1322 +++++++++++---------
 sgx_tcrypto_helper/Cargo.toml                      |    2 +-
 sgx_tdh/Cargo.toml                                 |    2 +-
 sgx_tdh/src/dh.rs                                  |   61 +-
 sgx_tdh/src/ecp.rs                                 |    9 +-
 sgx_tdh/src/lib.rs                                 |    2 -
 sgx_tkey_exchange/Cargo.toml                       |    2 +-
 sgx_tkey_exchange/src/lib.rs                       |   19 +-
 sgx_tprotected_fs/Cargo.toml                       |    2 +-
 sgx_tprotected_fs/src/fs.rs                        |    1 -
 sgx_trts/Cargo.toml                                |    2 +-
 sgx_trts/src/ascii.rs                              |    4 +-
 sgx_trts/src/c_str.rs                              |  177 ++-
 sgx_trts/src/enclave.rs                            |   63 +-
 sgx_trts/src/lib.rs                                |    6 +-
 sgx_trts/src/memchr.rs                             |   16 +-
 sgx_trts/src/memeq.rs                              |   32 +-
 sgx_trts/src/oom.rs                                |   21 +-
 sgx_tse/Cargo.toml                                 |    2 +-
 sgx_tse/src/se.rs                                  |   19 +-
 sgx_tseal/Cargo.toml                               |    2 +-
 sgx_tseal/src/aad.rs                               |   58 +-
 sgx_tseal/src/internal.rs                          |  156 +--
 sgx_tseal/src/seal.rs                              |   66 +-
 sgx_tstd/Cargo.toml                                |    9 +-
 sgx_tstd/hashbrown/Cargo.toml                      |   18 +-
 sgx_tstd/src/alloc.rs                              |   41 +-
 sgx_tstd/src/backtrace.rs                          |  364 +++++-
 sgx_tstd/src/collections/hash/map.rs               |  180 +--
 sgx_tstd/src/collections/hash/mod.rs               |   17 +
 sgx_tstd/src/collections/hash/set.rs               |  106 +-
 sgx_tstd/src/collections/mod.rs                    |  404 +++++-
 sgx_tstd/src/env.rs                                |  238 +++-
 sgx_tstd/src/error.rs                              |  200 +--
 sgx_tstd/src/f32.rs                                |  123 +-
 sgx_tstd/src/f64.rs                                |   70 +-
 sgx_tstd/src/ffi/c_str.rs                          |   14 +-
 sgx_tstd/src/ffi/mod.rs                            |  149 ++-
 sgx_tstd/src/ffi/os_str.rs                         |  177 ++-
 sgx_tstd/src/fs.rs                                 |  367 ++++--
 sgx_tstd/src/future.rs                             |   80 +-
 sgx_tstd/src/io/buffered.rs                        |  226 +++-
 sgx_tstd/src/io/cursor.rs                          |   89 +-
 sgx_tstd/src/io/error.rs                           |   66 +-
 sgx_tstd/src/io/impls.rs                           |   63 +-
 sgx_tstd/src/io/lazy.rs                            |    6 +-
 sgx_tstd/src/io/mod.rs                             |  318 +++--
 sgx_tstd/src/io/prelude.rs                         |   10 +-
 sgx_tstd/src/io/stdio.rs                           |   83 +-
 sgx_tstd/src/io/util.rs                            |   46 +-
 sgx_tstd/src/lib.rs                                |  120 +-
 sgx_tstd/src/macros.rs                             |   29 +-
 sgx_tstd/src/memchr.rs                             |    5 +-
 sgx_tstd/src/net/addr.rs                           |  121 +-
 sgx_tstd/src/net/ip.rs                             |  317 +++--
 sgx_tstd/src/net/mod.rs                            |   27 +-
 sgx_tstd/src/net/parser.rs                         |  119 +-
 sgx_tstd/src/net/tcp.rs                            |   69 +-
 sgx_tstd/src/net/udp.rs                            |   55 +-
 sgx_tstd/src/num.rs                                |    8 +-
 sgx_tstd/src/os/fs.rs                              |   17 +-
 sgx_tstd/src/os/raw.rs                             |    2 +
 sgx_tstd/src/panic.rs                              |   72 +-
 sgx_tstd/src/panicking.rs                          |  314 +++--
 sgx_tstd/src/path.rs                               |  227 ++--
 sgx_tstd/src/prelude/mod.rs                        |   14 +
 sgx_tstd/src/prelude/v1.rs                         |   64 +-
 sgx_tstd/src/sgxfs.rs                              |    2 +-
 sgx_tstd/src/sync/barrier.rs                       |   20 +-
 sgx_tstd/src/sync/condvar.rs                       |  219 ++--
 sgx_tstd/src/sync/mod.rs                           |    2 +-
 sgx_tstd/src/sync/mpsc/blocking.rs                 |   16 +-
 sgx_tstd/src/sync/mpsc/cache_aligned.rs            |   14 +-
 sgx_tstd/src/sync/mpsc/mod.rs                      |  274 ++--
 sgx_tstd/src/sync/mpsc/mpsc_queue.rs               |   16 +-
 sgx_tstd/src/sync/mpsc/oneshot.rs                  |   54 +-
 sgx_tstd/src/sync/mpsc/shared.rs                   |   57 +-
 sgx_tstd/src/sync/mpsc/spsc_queue.rs               |   33 +-
 sgx_tstd/src/sync/mpsc/stream.rs                   |  115 +-
 sgx_tstd/src/sync/mpsc/sync.rs                     |  131 +-
 sgx_tstd/src/sync/mutex.rs                         |  101 +-
 sgx_tstd/src/sync/once.rs                          |  259 ++--
 sgx_tstd/src/sync/remutex.rs                       |   27 +-
 sgx_tstd/src/sync/rwlock.rs                        |  129 +-
 sgx_tstd/src/sync/spinlock.rs                      |   11 +-
 sgx_tstd/src/sys/backtrace/mod.rs                  |   38 +-
 sgx_tstd/src/sys/backtrace/printing/mod.rs         |  194 ++-
 sgx_tstd/src/sys/backtrace/tracing/gcc_s.rs        |  146 +--
 sgx_tstd/src/sys/backtrace/tracing/mod.rs          |   64 +-
 sgx_tstd/src/sys/cmath.rs                          |    4 +-
 sgx_tstd/src/sys/condvar.rs                        |   21 +-
 sgx_tstd/src/sys/env.rs                            |   14 +-
 sgx_tstd/src/sys/ext/fs.rs                         |  131 +-
 sgx_tstd/src/sys/ext/io.rs                         |   24 +-
 sgx_tstd/src/sys/ext/mod.rs                        |   14 +-
 sgx_tstd/src/sys/ext/net.rs                        |   98 +-
 .../sys/{backtrace/printing/mod.rs => ext/raw.rs}  |   12 +-
 sgx_tstd/src/sys/ext/thread.rs                     |   49 +
 sgx_tstd/src/sys/fast_thread_local.rs              |    2 +-
 sgx_tstd/src/sys/fd.rs                             |  104 +-
 sgx_tstd/src/sys/fs.rs                             |  212 ++--
 sgx_tstd/src/sys/io.rs                             |   44 +-
 sgx_tstd/src/sys/mod.rs                            |   21 +-
 sgx_tstd/src/sys/mutex.rs                          |   99 +-
 sgx_tstd/src/sys/net.rs                            |  142 +--
 sgx_tstd/src/sys/os.rs                             |   46 +-
 sgx_tstd/src/sys/path.rs                           |    2 +-
 sgx_tstd/src/sys/pipe.rs                           |   24 +-
 sgx_tstd/src/sys/rand.rs                           |    5 +-
 sgx_tstd/src/sys/rwlock.rs                         |    3 +-
 sgx_tstd/src/sys/sgxfs.rs                          |   21 +-
 sgx_tstd/src/sys/stdio.rs                          |   12 +-
 sgx_tstd/src/sys/thread.rs                         |   25 +-
 sgx_tstd/src/sys/thread_local.rs                   |    2 +-
 sgx_tstd/src/sys/time.rs                           |   62 +-
 sgx_tstd/src/sys_common/at_exit_imp.rs             |    5 +-
 sgx_tstd/src/sys_common/backtrace.rs               |  339 ++---
 sgx_tstd/src/sys_common/fs.rs                      |    8 +-
 sgx_tstd/src/sys_common/gnu/libbacktrace.rs        |  396 ++++--
 sgx_tstd/src/sys_common/gnu/mod.rs                 |  244 +++-
 sgx_tstd/src/sys_common/io.rs                      |    1 -
 sgx_tstd/src/sys_common/mod.rs                     |   26 +-
 sgx_tstd/src/sys_common/net.rs                     |  172 ++-
 sgx_tstd/src/sys_common/os_str_bytes.rs            |   75 +-
 sgx_tstd/src/sys_common/poison.rs                  |   45 +-
 sgx_tstd/src/sys_common/thread.rs                  |    5 -
 sgx_tstd/src/sys_common/thread_info.rs             |   27 +-
 sgx_tstd/src/sys_common/thread_local.rs            |   36 +-
 sgx_tstd/src/sys_common/util.rs                    |    9 +-
 sgx_tstd/src/sys_common/wtf8.rs                    |  209 ++--
 sgx_tstd/src/thread/local.rs                       |  175 ++-
 sgx_tstd/src/thread/mod.rs                         |  352 ++++--
 sgx_tstd/src/time.rs                               |   51 +-
 sgx_tstd/src/untrusted/time.rs                     |   18 +-
 sgx_tunittest/Cargo.toml                           |    2 +-
 sgx_tunittest/src/lib.rs                           |   66 +-
 sgx_types/Cargo.toml                               |    2 +-
 sgx_types/src/error.rs                             |  202 +--
 sgx_types/src/function.rs                          |   73 +-
 sgx_types/src/macros.rs                            |   64 +-
 sgx_types/src/metadata.rs                          |   18 +-
 sgx_types/src/types.rs                             |  154 ++-
 sgx_ucrypto/Cargo.toml                             |    2 +-
 sgx_ucrypto/src/crypto.rs                          | 1240 ++++++++++--------
 sgx_ucrypto/src/util.rs                            |   23 +-
 sgx_unwind/build.rs                                |   57 +-
 sgx_unwind/lib.rs                                  |   42 +-
 sgx_unwind/libunwind.rs                            |  229 +---
 sgx_unwind/libunwind/autogen-linux.sh              |    4 +-
 sgx_unwind/macros.rs                               |   56 +-
 sgx_urts/Cargo.toml                                |    2 +-
 sgx_urts/src/asyncio.rs                            |   24 +-
 sgx_urts/src/enclave.rs                            |  314 ++---
 sgx_urts/src/env.rs                                |   24 +-
 sgx_urts/src/event.rs                              |   81 +-
 sgx_urts/src/fd.rs                                 |  126 +-
 sgx_urts/src/file.rs                               |  195 +--
 sgx_urts/src/lib.rs                                |    3 +-
 sgx_urts/src/mem.rs                                |   46 +-
 sgx_urts/src/net.rs                                |   14 +-
 sgx_urts/src/pipe.rs                               |   16 +-
 .../gnu/mod.rs => sgx_urts/src/process.rs          |   10 +-
 sgx_urts/src/signal.rs                             |  270 ++++
 sgx_urts/src/socket.rs                             |  208 +--
 sgx_urts/src/sys.rs                                |   36 +-
 sgx_urts/src/thread.rs                             |    8 +-
 sgx_urts/src/time.rs                               |   10 +-
 sgx_ustdc/Makefile                                 |    7 +-
 sgx_ustdc/inc/inline-hashtab.h                     |  300 +++++
 .../sys_common/gnu/mod.rs => sgx_ustdc/process.c   |   15 +-
 sgx_ustdc/signal.c                                 |  271 ++++
 xargo/sgx_tstd/Cargo.toml                          |    8 +-
 275 files changed, 13224 insertions(+), 6768 deletions(-)

diff --git a/samplecode/backtrace/enclave/Xargo.toml b/samplecode/backtrace/enclave/Xargo.toml
index 4b6f280..abb29c4 100644
--- a/samplecode/backtrace/enclave/Xargo.toml
+++ b/samplecode/backtrace/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/backtrace/enclave/src/lib.rs b/samplecode/backtrace/enclave/src/lib.rs
index 1fce2c0..b65a7bc 100644
--- a/samplecode/backtrace/enclave/src/lib.rs
+++ b/samplecode/backtrace/enclave/src/lib.rs
@@ -87,14 +87,18 @@ pub extern "C" fn say_something(some_string: *const u8, some_len: usize) -> sgx_
         })
     }).ok();
 
+    let _ = backtrace::enable_backtrace("enclave.signed.so", PrintFormat::Full);
     panic::catch_unwind(||{
         test_backtrace_2()
     }).ok();
 
-    println!("\nsgx_backtrace sample code");
+    println!("\nsgx_backtrace sample code:");
     let _  = sgx_backtrace::set_enclave_path("enclave.signed.so");
     foo();
 
+    println!("\nstd::backtrace sample code:");
+    foo_1();
+
     sgx_status_t::SGX_SUCCESS
 }
 
@@ -134,6 +138,23 @@ fn raw() {
     print()
 }
 
+#[inline(never)]
+fn foo_1() {
+    bar_1()
+}
+
+#[inline(never)]
+fn bar_1() {
+    baz_1()
+}
+
+#[inline(never)]
+fn baz_1() {
+    let bt = std::backtrace::Backtrace::capture();
+    println!("{:#?}", bt);
+    println!("{:#}", bt);
+}
+
 #[cfg(target_pointer_width = "32")]
 const HEX_WIDTH: usize = 10;
 #[cfg(target_pointer_width = "64")]
diff --git a/samplecode/crypto/enclave/Xargo.toml b/samplecode/crypto/enclave/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/crypto/enclave/Xargo.toml
+++ b/samplecode/crypto/enclave/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/db-proxy/db-proxy/enclave/Xargo.toml b/samplecode/db-proxy/db-proxy/enclave/Xargo.toml
index 2fe0af4..e9f9dbc 100644
--- a/samplecode/db-proxy/db-proxy/enclave/Xargo.toml
+++ b/samplecode/db-proxy/db-proxy/enclave/Xargo.toml
@@ -84,3 +84,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/file/enclave/Xargo.toml b/samplecode/file/enclave/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/file/enclave/Xargo.toml
+++ b/samplecode/file/enclave/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/hello-regex/enclave/Xargo.toml b/samplecode/hello-regex/enclave/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/hello-regex/enclave/Xargo.toml
+++ b/samplecode/hello-regex/enclave/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/hello-rust-vscode-debug/enclave/Xargo.toml b/samplecode/hello-rust-vscode-debug/enclave/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/hello-rust-vscode-debug/enclave/Xargo.toml
+++ b/samplecode/hello-rust-vscode-debug/enclave/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/hello-rust/enclave/Xargo.toml b/samplecode/hello-rust/enclave/Xargo.toml
index 66af891..ffb4272 100644
--- a/samplecode/hello-rust/enclave/Xargo.toml
+++ b/samplecode/hello-rust/enclave/Xargo.toml
@@ -89,3 +89,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/helloworld/enclave/Xargo.toml b/samplecode/helloworld/enclave/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/helloworld/enclave/Xargo.toml
+++ b/samplecode/helloworld/enclave/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/http_req/enclave/Xargo.toml b/samplecode/http_req/enclave/Xargo.toml
index 07d26e8..26fd2ce 100644
--- a/samplecode/http_req/enclave/Xargo.toml
+++ b/samplecode/http_req/enclave/Xargo.toml
@@ -89,3 +89,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/hugemem/enclave/Xargo.toml b/samplecode/hugemem/enclave/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/hugemem/enclave/Xargo.toml
+++ b/samplecode/hugemem/enclave/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/kvdb-memdb/enclave/Xargo.toml b/samplecode/kvdb-memdb/enclave/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/kvdb-memdb/enclave/Xargo.toml
+++ b/samplecode/kvdb-memdb/enclave/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/localattestation/attestation/Xargo.toml b/samplecode/localattestation/attestation/Xargo.toml
index 6189cbf..cd02285 100644
--- a/samplecode/localattestation/attestation/Xargo.toml
+++ b/samplecode/localattestation/attestation/Xargo.toml
@@ -88,3 +88,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/localattestation/enclave1/Xargo.toml b/samplecode/localattestation/enclave1/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/localattestation/enclave1/Xargo.toml
+++ b/samplecode/localattestation/enclave1/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/localattestation/enclave2/Xargo.toml b/samplecode/localattestation/enclave2/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/localattestation/enclave2/Xargo.toml
+++ b/samplecode/localattestation/enclave2/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/localattestation/enclave3/Xargo.toml b/samplecode/localattestation/enclave3/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/localattestation/enclave3/Xargo.toml
+++ b/samplecode/localattestation/enclave3/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/logger/enclave/Xargo.toml b/samplecode/logger/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/logger/enclave/Xargo.toml
+++ b/samplecode/logger/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/machine-learning/enclave/Xargo.toml b/samplecode/machine-learning/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/machine-learning/enclave/Xargo.toml
+++ b/samplecode/machine-learning/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/mio/client/enclave/Xargo.toml b/samplecode/mio/client/enclave/Xargo.toml
index 30186d7..989d796 100644
--- a/samplecode/mio/client/enclave/Xargo.toml
+++ b/samplecode/mio/client/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/mio/server/enclave/Xargo.toml b/samplecode/mio/server/enclave/Xargo.toml
index 30186d7..989d796 100644
--- a/samplecode/mio/server/enclave/Xargo.toml
+++ b/samplecode/mio/server/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/mutual-ra/enclave/Xargo.toml b/samplecode/mutual-ra/enclave/Xargo.toml
index e01bc02..333a007 100644
--- a/samplecode/mutual-ra/enclave/Xargo.toml
+++ b/samplecode/mutual-ra/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/net2/enclave/Xargo.toml b/samplecode/net2/enclave/Xargo.toml
index ed0c076..80745aa 100644
--- a/samplecode/net2/enclave/Xargo.toml
+++ b/samplecode/net2/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/pcl/encrypted-hello/enclave/Xargo.toml b/samplecode/pcl/encrypted-hello/enclave/Xargo.toml
index da6e4a0..29ccfac 100644
--- a/samplecode/pcl/encrypted-hello/enclave/Xargo.toml
+++ b/samplecode/pcl/encrypted-hello/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/pcl/pcl-seal/enclave/Xargo.toml b/samplecode/pcl/pcl-seal/enclave/Xargo.toml
index 30186d7..989d796 100644
--- a/samplecode/pcl/pcl-seal/enclave/Xargo.toml
+++ b/samplecode/pcl/pcl-seal/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/prost-protobuf/enclave/Xargo.toml b/samplecode/prost-protobuf/enclave/Xargo.toml
index 66af891..ffb4272 100644
--- a/samplecode/prost-protobuf/enclave/Xargo.toml
+++ b/samplecode/prost-protobuf/enclave/Xargo.toml
@@ -89,3 +89,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/protobuf/enclave/Xargo.toml b/samplecode/protobuf/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/protobuf/enclave/Xargo.toml
+++ b/samplecode/protobuf/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/psi/SMCServer/enclave/Xargo.toml b/samplecode/psi/SMCServer/enclave/Xargo.toml
index da6e4a0..29ccfac 100644
--- a/samplecode/psi/SMCServer/enclave/Xargo.toml
+++ b/samplecode/psi/SMCServer/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/remoteattestation/Application/enclave/Xargo.toml b/samplecode/remoteattestation/Application/enclave/Xargo.toml
index da6e4a0..29ccfac 100644
--- a/samplecode/remoteattestation/Application/enclave/Xargo.toml
+++ b/samplecode/remoteattestation/Application/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/sealeddata/enclave/Xargo.toml b/samplecode/sealeddata/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/sealeddata/enclave/Xargo.toml
+++ b/samplecode/sealeddata/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/secretsharing/enclave/Xargo.toml b/samplecode/secretsharing/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/secretsharing/enclave/Xargo.toml
+++ b/samplecode/secretsharing/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/serialize/enclave/Xargo.toml b/samplecode/serialize/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/serialize/enclave/Xargo.toml
+++ b/samplecode/serialize/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/sgx-cov/enclave/Xargo.toml b/samplecode/sgx-cov/enclave/Xargo.toml
index abc6f28..981737d 100644
--- a/samplecode/sgx-cov/enclave/Xargo.toml
+++ b/samplecode/sgx-cov/enclave/Xargo.toml
@@ -93,3 +93,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/static-data-distribution/enclave/Xargo.toml b/samplecode/static-data-distribution/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/static-data-distribution/enclave/Xargo.toml
+++ b/samplecode/static-data-distribution/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/switchless/enclave/Xargo.toml b/samplecode/switchless/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/switchless/enclave/Xargo.toml
+++ b/samplecode/switchless/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/tcmalloc/enclave/Xargo.toml b/samplecode/tcmalloc/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/tcmalloc/enclave/Xargo.toml
+++ b/samplecode/tcmalloc/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/thread/enclave/Xargo.toml b/samplecode/thread/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/thread/enclave/Xargo.toml
+++ b/samplecode/thread/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/tls/tlsclient/enclave/Xargo.toml b/samplecode/tls/tlsclient/enclave/Xargo.toml
index 30186d7..989d796 100644
--- a/samplecode/tls/tlsclient/enclave/Xargo.toml
+++ b/samplecode/tls/tlsclient/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/tls/tlsserver/enclave/Xargo.toml b/samplecode/tls/tlsserver/enclave/Xargo.toml
index 30186d7..989d796 100644
--- a/samplecode/tls/tlsserver/enclave/Xargo.toml
+++ b/samplecode/tls/tlsserver/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/tr-mpc/tr-mpc-server/enclave/Xargo.toml b/samplecode/tr-mpc/tr-mpc-server/enclave/Xargo.toml
index 30186d7..989d796 100644
--- a/samplecode/tr-mpc/tr-mpc-server/enclave/Xargo.toml
+++ b/samplecode/tr-mpc/tr-mpc-server/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/ue-ra/ue-ra-server/enclave/Xargo.toml b/samplecode/ue-ra/ue-ra-server/enclave/Xargo.toml
index 30186d7..989d796 100644
--- a/samplecode/ue-ra/ue-ra-server/enclave/Xargo.toml
+++ b/samplecode/ue-ra/ue-ra-server/enclave/Xargo.toml
@@ -88,4 +88,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../../sgx_signal"
+stage = 7
diff --git a/samplecode/unit-test/enclave/Cargo.toml b/samplecode/unit-test/enclave/Cargo.toml
index 0eddbb4..59964d3 100644
--- a/samplecode/unit-test/enclave/Cargo.toml
+++ b/samplecode/unit-test/enclave/Cargo.toml
@@ -12,7 +12,7 @@ default = []
 
 [target.'cfg(not(target_env = "sgx"))'.dependencies]
 sgx_types = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
-sgx_tstd = { git = "https://github.com/apache/teaclave-sgx-sdk.git", features = ["untrusted_fs", "thread"] }
+sgx_tstd = { git = "https://github.com/apache/teaclave-sgx-sdk.git", features = ["untrusted_fs", "thread", "backtrace"] }
 sgx_tcrypto = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 sgx_tunittest = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 sgx_trts = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
@@ -20,6 +20,8 @@ sgx_rand = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 sgx_tseal = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 sgx_serialize = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 sgx_alloc = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
+sgx_libc = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
+sgx_signal = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 
 [dependencies]
 sgx_serialize_derive = { git = "https://github.com/apache/teaclave-sgx-sdk.git" }
@@ -54,6 +56,7 @@ sgx_tseal = { path = "../../../sgx_tseal" }
 sgx_tstd = { path = "../../../sgx_tstd" }
 sgx_tunittest = { path = "../../../sgx_tunittest" }
 sgx_types = { path = "../../../sgx_types" }
-#sgx_ucrypto = { path = "../../../sgx_ucrypto" }
 sgx_unwind = { path = "../../../sgx_unwind" }
+sgx_signal = { path = "../../../sgx_signal" }
+#sgx_ucrypto = { path = "../../../sgx_ucrypto" }
 #sgx_urts = { path = "../../../sgx_urts" }
\ No newline at end of file
diff --git a/samplecode/unit-test/enclave/Enclave.edl b/samplecode/unit-test/enclave/Enclave.edl
index f56338a..59eff09 100644
--- a/samplecode/unit-test/enclave/Enclave.edl
+++ b/samplecode/unit-test/enclave/Enclave.edl
@@ -25,6 +25,8 @@ enclave {
     from "sgx_thread.edl" import *;
     from "sgx_sys.edl" import *;
     from "sgx_backtrace.edl" import *;
+    from "sgx_signal.edl" import*;
+    from "sgx_process.edl" import*;
     trusted {
         /* define ECALLs here. */
 
diff --git a/samplecode/unit-test/enclave/Xargo.toml b/samplecode/unit-test/enclave/Xargo.toml
index 681554e..61e97a9 100644
--- a/samplecode/unit-test/enclave/Xargo.toml
+++ b/samplecode/unit-test/enclave/Xargo.toml
@@ -63,7 +63,7 @@ stage = 4
 
 [dependencies.std]
 path = "../../../xargo/sgx_tstd"
-features = ["untrusted_fs", "thread"]
+features = ["untrusted_fs", "thread", "backtrace"]
 stage = 5
 
 [dependencies.sgx_no_tstd]
@@ -89,3 +89,7 @@ stage = 7
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
 stage = 7
+
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
\ No newline at end of file
diff --git a/samplecode/unit-test/enclave/src/lib.rs b/samplecode/unit-test/enclave/src/lib.rs
index 50ca3d4..b9ea49b 100644
--- a/samplecode/unit-test/enclave/src/lib.rs
+++ b/samplecode/unit-test/enclave/src/lib.rs
@@ -19,7 +19,7 @@
 #![crate_type = "staticlib"]
 
 #![feature(box_syntax)]
-
+#![feature(core_intrinsics)]
 #![cfg_attr(not(target_env = "sgx"), no_std)]
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
 
@@ -45,6 +45,8 @@ extern crate sgx_serialize;
 pub use sgx_serialize::*;
 #[macro_use]
 extern crate sgx_serialize_derive;
+extern crate sgx_signal;
+extern crate sgx_libc;
 
 pub use sgx_serialize::*;
 use sgx_types::*;
@@ -103,6 +105,11 @@ use test_alignbox::*;
 mod test_alignstruct;
 
 
+mod test_signal;
+use test_signal::*;
+
+mod test_exception;
+use test_exception::*;
 #[no_mangle]
 pub extern "C"
 fn test_main_entrance() -> size_t {
@@ -331,6 +338,14 @@ fn test_main_entrance() -> size_t {
                     test_alignbox_clone,
                     test_alignbox_clonefrom,
                     test_alignbox_clonefrom_no_eq_size,
+                    //test signal
+                    test_signal_forbidden,
+                    test_signal_without_pid,
+                    test_signal_with_pid,
+                    test_signal_register_unregister,
+                    test_signal_register_unregister1,
+                    //test exception
+                    test_exception_handler,
                     )
 }
 
diff --git a/samplecode/unit-test/enclave/src/test_exception.rs b/samplecode/unit-test/enclave/src/test_exception.rs
new file mode 100644
index 0000000..36d9819
--- /dev/null
+++ b/samplecode/unit-test/enclave/src/test_exception.rs
@@ -0,0 +1,81 @@
+// 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..
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::thread;
+use std::time::Duration;
+use std::backtrace::{self, PrintFormat};
+use std::panic;
+use sgx_signal::ContinueType;
+use sgx_signal::exception::{register_exception, unregister};
+use sgx_types::sgx_exception_info_t;
+use sgx_trts::enclave;
+
+#[no_mangle]
+#[inline(never)]
+fn test_abort() -> ! {
+    let td = enclave::SgxThreadData::current();
+    println!("test_abort stack: {:x}-{:x}", td.stack_base(), td.stack_limit());
+
+    unsafe{ std::intrinsics::abort() }
+}
+
+pub fn test_exception_handler() {
+    let _ = backtrace::enable_backtrace("enclave.signed.so", PrintFormat::Full);
+
+    let status = Arc::new(AtomicUsize::new(2));
+    let handler1 = {
+        let status = Arc::clone(&status);
+        move |_info: &mut sgx_exception_info_t| {
+            status.fetch_add(2, Ordering::Relaxed);
+            ContinueType::Search
+        }
+    };
+
+    let handler2 = {
+        let status = Arc::clone(&status);
+        move |_info: &mut sgx_exception_info_t| {
+            status.store(1, Ordering::Relaxed);
+            ContinueType::Search
+        }
+    };
+
+    let r1 = register_exception(false, handler1);
+    let r2 = register_exception(true, handler2);
+
+    panic::catch_unwind(||{
+        test_abort()
+    }).ok();
+
+    for _ in 0..10 {
+        thread::sleep(Duration::from_millis(100));
+        let current = status.load(Ordering::Relaxed);
+        match current {
+            // Not yet
+            0 => continue,
+            // Good, we are done with the correct result
+            _ if current == 3 => return,
+            _ => panic!("Wrong result value {}", current),
+        }
+    }
+
+    unregister(r1.unwrap());
+    unregister(r2.unwrap());
+    panic!("Timed out waiting for the exception");
+}
+
diff --git a/samplecode/unit-test/enclave/src/test_rand.rs b/samplecode/unit-test/enclave/src/test_rand.rs
index 51d27c9..65bd268 100644
--- a/samplecode/unit-test/enclave/src/test_rand.rs
+++ b/samplecode/unit-test/enclave/src/test_rand.rs
@@ -21,8 +21,8 @@ use sgx_rand::*;
 // pub use os::SgxRng
 pub fn test_rand_os_sgxrng(){
     let mut os_rng = os::SgxRng::new().unwrap();
-    let mut checksum_u32 : u32 = 0;
-    let mut checksum_u64 : u64 = 0;
+    let mut checksum_u32: u32 = 0;
+    let mut checksum_u64: u64 = 0;
     let testcount = 1000;
     for _ in 0..testcount {
         checksum_u32 |= os_rng.next_u32();
@@ -31,10 +31,10 @@ pub fn test_rand_os_sgxrng(){
     assert_ne!(checksum_u32, 0);
     assert_ne!(checksum_u64, 0);
 
-    let mut rand_arr = [0;1000];
+    let mut rand_arr = [0; 1000];
     os_rng.fill_bytes(&mut rand_arr[..]);
-    let x = rand_arr.iter().fold(0, |sum, &x| sum + x);
-    assert_ne!(x, 0);
+    let cmp = [0; 1000].iter().zip(rand_arr.iter()).all(|(x, y)| x == y);
+    assert_ne!(cmp, true);
 }
 
 // pub mod distribution
@@ -45,8 +45,8 @@ pub fn test_rand_distributions () {
     use sgx_rand::*;
 
     // From rust-src/librand/distributions/rand.rs
-    should_panic!(Range::new(10,10));
-    should_panic!(Range::new(10,5));
+    should_panic!(Range::new(10, 10));
+    should_panic!(Range::new(10, 5));
     let mut rng = thread_rng();
     macro_rules! t {
         ($($ty:ident),*) => {{
diff --git a/samplecode/unit-test/enclave/src/test_rts.rs b/samplecode/unit-test/enclave/src/test_rts.rs
index 5fb37fa..25d6047 100644
--- a/samplecode/unit-test/enclave/src/test_rts.rs
+++ b/samplecode/unit-test/enclave/src/test_rts.rs
@@ -88,20 +88,20 @@ pub fn test_register_multiple_exception_handler() {
 pub fn test_read_rand(){
     let mut rand_arr = [0; 100];
     assert_eq!(rsgx_read_rand(&mut rand_arr[..]), Ok(()));
-    let x = rand_arr.iter().fold(0, |sum, &x| sum + x);
     // Cannot all be zero
-    assert_ne!(x, 0);
+    let cmp = [0; 100].iter().zip(rand_arr.iter()).all(|(x, y)| x == y);
+    assert_ne!(cmp, true);
 }
 
 pub fn test_data_is_within_enclave() {
     #[derive(Clone, Copy)]
     struct SampleDs{
-        x : i32,
-        y : i32,
-        z : [i32;100],
+        x: i32,
+        y: i32,
+        z: [i32; 100],
     };
     unsafe impl marker::ContiguousMemory for SampleDs{};
-    let mut sample_object : SampleDs = SampleDs{ x : 0, y : 0, z : [0;100]};
+    let mut sample_object : SampleDs = SampleDs{ x: 0, y: 0, z: [0; 100]};
     sample_object.x = 100;
     sample_object.y = 100;
     sample_object.z[0] = 100;
@@ -140,12 +140,12 @@ pub fn test_raw_is_within_enclave(){
 pub fn test_data_is_outside_enclave() {
     #[derive(Clone, Copy)]
     struct SampleDs{
-        x : i32,
-        y : i32,
-        z : [i32;100],
+        x: i32,
+        y: i32,
+        z: [i32; 100],
     };
     unsafe impl marker::ContiguousMemory for SampleDs{};
-    let mut sample_object : SampleDs = SampleDs{ x : 0, y : 0, z : [0;100]};
+    let mut sample_object : SampleDs = SampleDs{ x: 0, y: 0, z: [0; 100]};
     sample_object.x = 100;
     sample_object.y = 100;
     sample_object.z[0] = 100;
diff --git a/samplecode/unit-test/enclave/src/test_signal.rs b/samplecode/unit-test/enclave/src/test_signal.rs
new file mode 100644
index 0000000..c944e14
--- /dev/null
+++ b/samplecode/unit-test/enclave/src/test_signal.rs
@@ -0,0 +1,128 @@
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::thread;
+use std::time::Duration;
+use sgx_libc::{siginfo_t, c_int, pid_t, SIGUSR1, SIGUSR2, SIGILL, SIGTERM,SIGINT};
+use sgx_libc::ocall::getpid;
+use sgx_signal::signal::{register, register_sigaction, unregister, unregister_signal, raise_signal};
+
+pub fn test_signal_forbidden() {
+   let ret = register(SIGILL, || ());
+   assert_eq!(ret.is_ok(), false);
+}
+
+pub fn test_signal_without_pid() {
+   let status = Arc::new(AtomicUsize::new(0));
+   let action = {
+      let status = Arc::clone(&status);
+      move || {
+         status.store(1, Ordering::Relaxed);
+      }
+   };
+
+   register(SIGUSR2, action).unwrap();
+   raise_signal(SIGUSR2);
+
+   for _ in 0..10 {
+      thread::sleep(Duration::from_millis(100));
+      let current = status.load(Ordering::Relaxed);
+      match current {
+         // Not yet
+         0 => continue,
+         // Good, we are done with the correct result
+         _ if current == 1 => return,
+         _ => panic!("Wrong result value {}", current),
+      }
+   }
+   panic!("Timed out waiting for the signal");
+}
+
+pub fn test_signal_with_pid() {
+   let status = Arc::new(AtomicUsize::new(0));
+   let action = {
+      let status = Arc::clone(&status);
+      move |siginfo: &siginfo_t| {
+         // Hack: currently, libc exposes only the first 3 fields of siginfo_t. The pid
+         // comes somewhat later on. Therefore, we do a Really Ugly Hack and define our
+         // own structure (and hope it is correct on all platforms). But hey, this is
+         // only the tests, so we are going to get away with this.
+         #[repr(C)]
+         struct SigInfo {
+            _fields: [c_int; 3],
+            #[cfg(all(target_pointer_width = "64", target_os = "linux"))]
+            _pad: c_int,
+            pid: pid_t,
+         }
+         let info: &SigInfo = unsafe {
+            (siginfo as *const _ as *const SigInfo)
+               .as_ref()
+               .unwrap()
+         };
+
+         status.store(info.pid as usize, Ordering::Relaxed);
+      }
+   };
+
+   let pid = unsafe { getpid() };
+   register_sigaction(SIGUSR2, action).unwrap();
+   raise_signal(SIGUSR2);
+
+   for _ in 0..10 {
+      thread::sleep(Duration::from_millis(100));
+      let current = status.load(Ordering::Relaxed);
+      match current {
+         // Not yet (PID == 0 doesn't happen)
+         0 => continue,
+         // Good, we are done with the correct result
+         _ if current == pid as usize => return,
+         _ => panic!("Wrong status value {}", current),
+      }
+   }
+   panic!("Timed out waiting for the signal");
+}
+
+// Check that registration works as expected and that unregister tells if it did or not.
+pub fn test_signal_register_unregister() {
+   let signal = register(SIGUSR1, || ()).unwrap();
+   // It was there now, so we can unregister
+   assert!(unregister(signal));
+   // The next time unregistering does nothing and tells us so.
+   assert!(!unregister(signal));
+}
+
+pub fn test_signal_register_unregister1() {
+   let called = Arc::new(AtomicUsize::new(0));
+   let action = {
+      let called = Arc::clone(&called);
+      move || {
+         called.fetch_add(1, Ordering::Relaxed);
+      }
+   };
+
+   register(SIGTERM, action.clone()).unwrap();
+   register(SIGTERM, action.clone()).unwrap();
+   register(SIGINT, action.clone()).unwrap();
+
+   raise_signal(SIGTERM);
+   // The closure is run twice.
+   assert_eq!(2, called.load(Ordering::Relaxed));
+
+   assert!(unregister_signal(SIGTERM));
+
+   raise_signal(SIGTERM);
+   // Second one unregisters nothing.
+   assert!(!unregister_signal(SIGTERM));
+
+   // After unregistering (both), it is no longer run at all.
+   assert_eq!(2, called.load(Ordering::Relaxed));
+
+   // The SIGINT one is not disturbed.
+   raise_signal(SIGINT);
+   assert_eq!(3, called.load(Ordering::Relaxed));
+
+   // But it's possible to register it again just fine.
+   register(SIGTERM, action).unwrap();
+
+   raise_signal(SIGTERM);
+   assert_eq!(4, called.load(Ordering::Relaxed));
+}
diff --git a/samplecode/wasmi/enclave/Xargo.toml b/samplecode/wasmi/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/wasmi/enclave/Xargo.toml
+++ b/samplecode/wasmi/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/samplecode/zlib-lazy-static-sample/enclave/Xargo.toml b/samplecode/zlib-lazy-static-sample/enclave/Xargo.toml
index b51ceef..31fb7d4 100644
--- a/samplecode/zlib-lazy-static-sample/enclave/Xargo.toml
+++ b/samplecode/zlib-lazy-static-sample/enclave/Xargo.toml
@@ -87,4 +87,7 @@ stage = 7
 
 [dependencies.sgx_cov]
 path = "../../../sgx_cov"
-stage = 7
\ No newline at end of file
+stage = 7
+[dependencies.sgx_signal]
+path = "../../../sgx_signal"
+stage = 7
diff --git a/sgx_align_struct_attribute/Cargo.toml b/sgx_align_struct_attribute/Cargo.toml
index e423af5..d32d457 100644
--- a/sgx_align_struct_attribute/Cargo.toml
+++ b/sgx_align_struct_attribute/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_align_struct_attribute"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_align_struct_attribute/src/align.rs b/sgx_align_struct_attribute/src/align.rs
index 0c832b2..7e5ac1b 100644
--- a/sgx_align_struct_attribute/src/align.rs
+++ b/sgx_align_struct_attribute/src/align.rs
@@ -56,16 +56,26 @@ impl AlignArgs {
         let align: usize = if let Some(align_value) = align_iter {
             self.parse_align(&align_value.value)?
         } else {
-            return Err(Error::new(Span::call_site(), "Invalid type of align attribute parsing"));
+            return Err(Error::new(
+                Span::call_site(),
+                "Invalid type of align attribute parsing",
+            ));
         };
 
         let size_iter = self.vars.iter().filter(|v| v.ident.to_string() == "size").next();
         let size: usize = if let Some(size_value) = size_iter {
             self.parse_size(&size_value.value)?
         } else {
-            return Err(Error::new(Span::call_site(), "Invalid type of size attribute parsing"));
+            return Err(Error::new(
+                Span::call_site(),
+                "Invalid type of size attribute parsing",
+            ));
         };
-        Layout::from_size_align(size, align).map_err(|_e| Error::new(Span::call_site(), "Layout illegal"))
+        Layout::from_size_align(size, align)
+            .map_err(|_e| Error::new(
+                Span::call_site(),
+                "Layout illegal",
+            ))
     }
 
     fn parse_align(&self, align_expr: &Expr) -> Result<usize> {
@@ -74,10 +84,16 @@ impl AlignArgs {
                 let align = lit.base10_parse::<u32>()?;
                 Ok(align as usize)
             } else {
-                Err(Error::new(Span::call_site(), "Invalid align attribute parsing"))
+                Err(Error::new(
+                    Span::call_site(),
+                    "Invalid align attribute parsing",
+                ))
             }
         } else {
-            Err(Error::new(Span::call_site(), "Invalid align attribute parsing"))
+            Err(Error::new(
+                Span::call_site(),
+                "Invalid align attribute parsing",
+            ))
         }
     }
 
@@ -87,10 +103,16 @@ impl AlignArgs {
                 let size = lit.base10_parse::<u32>()?;
                 Ok(size as usize)
             } else {
-                Err(Error::new(Span::call_site(), "Invalid size attribute parsing"))
+                Err(Error::new(
+                    Span::call_site(),
+                    "Invalid size attribute parsing",
+                ))
             }
         } else {
-            Err(Error::new(Span::call_site(), "Invalid size attribute parsing"))
+            Err(Error::new(
+                Span::call_site(),
+                "Invalid size attribute parsing",
+            ))
         }
     }
 }
@@ -175,7 +197,8 @@ impl AlignStruct {
                             }    
                             find
                         })
-                        .next().is_some();
+                        .next()
+                        .is_some();
                     }
                 }
             }
@@ -229,4 +252,4 @@ impl AlignStruct {
             #name: #ty
         }
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_align_struct_attribute/src/layout.rs b/sgx_align_struct_attribute/src/layout.rs
index 80b7c0e..ec9b5ca 100644
--- a/sgx_align_struct_attribute/src/layout.rs
+++ b/sgx_align_struct_attribute/src/layout.rs
@@ -192,7 +192,7 @@ fn make_bitmap(align_req: &[AlignReq]) -> i64 {
 
 mod libc {
     use std::ffi::c_void;
-    extern {
+    extern "C" {
         pub fn malloc(size: usize) -> *mut c_void;
         pub fn free(p: *mut c_void);
     }
diff --git a/sgx_alloc/Cargo.toml b/sgx_alloc/Cargo.toml
index 87c00bf..27051f7 100644
--- a/sgx_alloc/Cargo.toml
+++ b/sgx_alloc/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_alloc"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_alloc/src/alignalloc.rs b/sgx_alloc/src/alignalloc.rs
index e20d85a..0b1e16e 100644
--- a/sgx_alloc/src/alignalloc.rs
+++ b/sgx_alloc/src/alignalloc.rs
@@ -38,8 +38,7 @@ impl AlignAlloc {
     }
 
     #[inline]
-    pub unsafe fn alloc_zeroed(&mut self, layout: Layout)
-        -> Result<NonNull<u8>, AlighAllocErr> {
+    pub unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AlighAllocErr> {
         NonNull::new(platform::alloc_zeroed(layout)).ok_or(AlighAllocErr)
     }
 
@@ -49,8 +48,7 @@ impl AlignAlloc {
     }
 
     #[inline]
-    pub unsafe fn alloc_with_req_zeroed(&mut self, layout: Layout, align_req: &[AlignReq])
-        -> Result<NonNull<u8>, AlighAllocErr> {
+    pub unsafe fn alloc_with_req_zeroed(&mut self, layout: Layout, align_req: &[AlignReq]) -> Result<NonNull<u8>, AlighAllocErr> {
         NonNull::new(platform::alloc_with_req_zeroed(layout, align_req)).ok_or(AlighAllocErr)
     }
 
@@ -60,8 +58,7 @@ impl AlignAlloc {
     }
 
     #[inline]
-    pub unsafe fn alloc_with_pad_align_zeroed(&mut self, layout: Layout, align_layout: Layout)
-        -> Result<NonNull<u8>, AlighAllocErr> {
+    pub unsafe fn alloc_with_pad_align_zeroed(&mut self, layout: Layout, align_layout: Layout) -> Result<NonNull<u8>, AlighAllocErr> {
         NonNull::new(platform::alloc_with_pad_align_zeroed(layout, align_layout)).ok_or(AlighAllocErr)
     }
 
@@ -349,9 +346,10 @@ mod platform {
     mod libc {
         use core::ffi::c_void;
         type size_t = usize;
-        extern {
+        extern "C" {
             pub fn malloc(size: size_t) -> *mut c_void;
             pub fn free(p: *mut c_void);
         }
     }
 }
+
diff --git a/sgx_alloc/src/alignbox.rs b/sgx_alloc/src/alignbox.rs
index 0af1472..dede7d6 100644
--- a/sgx_alloc/src/alignbox.rs
+++ b/sgx_alloc/src/alignbox.rs
@@ -159,8 +159,7 @@ unsafe impl<#[may_dangle] T> Drop for AlignBox<T> {
 }
 
 impl<T> AlignBox<T> {
-
-    fn new_with_req_in(align: usize, align_req: &[AlignReq]) -> Option<Self> {
+    fn new_with_req_in(align: usize, align_req: &[AlignReq]) -> Option<AlignBox<T>> {
         if align_req.len() == 0 {
             AlignBox::new_in()
         } else {
@@ -168,17 +167,17 @@ impl<T> AlignBox<T> {
         }
     }
 
-    fn new_with_align_in(align: usize) -> Option<Self> {
+    fn new_with_align_in(align: usize) -> Option<AlignBox<T>> {
         let v: [AlignReq; 1] = [AlignReq{ offset:0, len:mem::size_of::<T>() }];
         AlignBox::allocate_in(true, align, &v)
     }
 
-    fn new_in() -> Option<Self> {
+    fn new_in() -> Option<AlignBox<T>> {
         let v: [AlignReq; 1] = [AlignReq{ offset: 0, len:mem::size_of::<T>() }];
         AlignBox::allocate_in(true, mem::align_of::<T>(), &v)
     }
 
-    fn allocate_in(zeroed: bool, align: usize, align_req: &[AlignReq]) -> Option<Self> {
+    fn allocate_in(zeroed: bool, align: usize, align_req: &[AlignReq]) -> Option<AlignBox<T>> {
         if mem::size_of::<T>() == 0 {
             return None;
         }
@@ -205,27 +204,27 @@ impl<T> AlignBox<T> {
         };
 
         Some(AlignBox{
-                ptr: ptr.into(),
-                align_layout: align_layout,
-                origin_layout: layout,
+            ptr: ptr.into(),
+            align_layout: align_layout,
+            origin_layout: layout,
         })
     }
 }
 
 impl<T> AlignBox<T> {
-    pub fn new() -> Option<Self> {
+    pub fn new() -> Option<AlignBox<T>> {
         Self::new_in()
     }
-     pub fn new_with_align(align: usize) -> Option<Self> {
+     pub fn new_with_align(align: usize) -> Option<AlignBox<T>> {
         Self::new_with_align_in(align)
     }
-    pub fn new_with_req(align: usize, align_req: &[AlignReq]) -> Option<Self> {
+    pub fn new_with_req(align: usize, align_req: &[AlignReq]) -> Option<AlignBox<T>> {
         Self::new_with_req_in(align, align_req)
     }
 }
 
 impl<T> AlignBox<T> {
-    pub fn heap_init<F>(initialize: F) -> Option<Self>
+    pub fn heap_init<F>(initialize: F) -> Option<AlignBox<T>>
     where
         F: Fn(&mut T),
     {
@@ -238,7 +237,7 @@ impl<T> AlignBox<T> {
             t
         }
     }
-    pub fn heap_init_with_align<F>(initialize: F, align: usize) -> Option<Self>
+    pub fn heap_init_with_align<F>(initialize: F, align: usize) -> Option<AlignBox<T>>
     where
         F: Fn(&mut T),
     {
@@ -251,7 +250,7 @@ impl<T> AlignBox<T> {
             t
         }
     }
-    pub fn heap_init_with_req<F>(initialize: F, align: usize, data: &[AlignReq]) -> Option<Self>
+    pub fn heap_init_with_req<F>(initialize: F, align: usize, data: &[AlignReq]) -> Option<AlignBox<T>>
     where
         F: Fn(&mut T),
     {
@@ -265,3 +264,4 @@ impl<T> AlignBox<T> {
         }
     }
 }
+
diff --git a/sgx_alloc/src/lib.rs b/sgx_alloc/src/lib.rs
index f07af9c..ddf8fb6 100644
--- a/sgx_alloc/src/lib.rs
+++ b/sgx_alloc/src/lib.rs
@@ -32,6 +32,7 @@
 #![feature(ptr_internals)]
 #![feature(dropck_eyepatch)]
 #![feature(allocator_api)]
+#![feature(core_intrinsics)]
 
 extern crate alloc;
 
diff --git a/sgx_alloc/src/rsrvmem.rs b/sgx_alloc/src/rsrvmem.rs
index 3d54e42..15e9f7b 100644
--- a/sgx_alloc/src/rsrvmem.rs
+++ b/sgx_alloc/src/rsrvmem.rs
@@ -117,7 +117,7 @@ mod platform {
     type int32_t = i32;
     type sgx_status_t = u32;
 
-    extern {
+    extern "C" {
         pub fn sgx_alloc_rsrv_mem(length: size_t) -> *mut c_void;
         pub fn sgx_free_rsrv_mem(addr: *const c_void, length: size_t) -> int32_t;
         pub fn sgx_tprotect_rsrv_mem(addr: *const c_void, length: size_t, prot: i32) -> sgx_status_t;  
diff --git a/sgx_alloc/src/system.rs b/sgx_alloc/src/system.rs
index 3b29cdb..771fe72 100644
--- a/sgx_alloc/src/system.rs
+++ b/sgx_alloc/src/system.rs
@@ -22,7 +22,16 @@
 //! It is essential, because we depends on Intel SGX's SDK.
 //! 2018-06-22 Add liballoc components here
 
-use core::alloc::{GlobalAlloc, AllocRef, AllocErr, Layout};
+use core::alloc::{
+    AllocInit,
+    AllocRef,
+    AllocErr,
+    GlobalAlloc,
+    Layout,
+    MemoryBlock,
+    ReallocPlacement
+};
+use core::intrinsics;
 use core::ptr::NonNull;
 
 // The minimum alignment guaranteed by the architecture. This value is used to
@@ -40,56 +49,96 @@ pub struct System;
 
 unsafe impl AllocRef for System {
     #[inline]
-    fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
-        if layout.size() == 0 {
-            Ok((layout.dangling(), 0))
-        } else {
-            unsafe {
-                NonNull::new(GlobalAlloc::alloc(self, layout))
-                    .ok_or(AllocErr)
-                    .map(|p| (p, layout.size()))
+    fn alloc(&mut self, layout: Layout, init: AllocInit) -> Result<MemoryBlock, AllocErr> {
+        unsafe {
+            let size = layout.size();
+            if size == 0 {
+                Ok(MemoryBlock { ptr: layout.dangling(), size: 0 })
+            } else {
+                let raw_ptr = match init {
+                    AllocInit::Uninitialized => GlobalAlloc::alloc(self, layout),
+                    AllocInit::Zeroed => GlobalAlloc::alloc_zeroed(self, layout),
+                };
+                let ptr = NonNull::new(raw_ptr).ok_or(AllocErr)?;
+                Ok(MemoryBlock { ptr, size })
             }
         }
     }
 
     #[inline]
-    fn alloc_zeroed(&mut self, layout: Layout)
-        -> Result<(NonNull<u8>, usize), AllocErr>
-    {
-        if layout.size() == 0 {
-            Ok((layout.dangling(), 0))
-        } else {
-            unsafe {
-                NonNull::new(GlobalAlloc::alloc_zeroed(self, layout))
-                    .ok_or(AllocErr)
-                    .map(|p| (p, layout.size()))
-            }
+    unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
+        if layout.size() != 0 {
+            GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
         }
     }
 
     #[inline]
-    unsafe fn dealloc(&mut self, ptr: core::ptr::NonNull<u8>, layout: Layout) {
-        if layout.size() != 0 {
-            GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
+    unsafe fn grow(
+        &mut self,
+        ptr: NonNull<u8>,
+        layout: Layout,
+        new_size: usize,
+        placement: ReallocPlacement,
+        init: AllocInit,
+    ) -> Result<MemoryBlock, AllocErr> {
+        let size = layout.size();
+        debug_assert!(
+            new_size >= size,
+            "`new_size` must be greater than or equal to `memory.size()`"
+        );
+
+        if size == new_size {
+            return Ok(MemoryBlock { ptr, size });
+        }
+
+        match placement {
+            ReallocPlacement::InPlace => Err(AllocErr),
+            ReallocPlacement::MayMove if layout.size() == 0 => {
+                let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
+                self.alloc(new_layout, init)
+            }
+            ReallocPlacement::MayMove => {
+                // `realloc` probably checks for `new_size > size` or something similar.
+                intrinsics::assume(new_size > size);
+                let ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size);
+                let memory =
+                    MemoryBlock { ptr: NonNull::new(ptr).ok_or(AllocErr)?, size: new_size };
+                init.init_offset(memory, size);
+                Ok(memory)
+            }
         }
     }
 
     #[inline]
-    unsafe fn realloc(&mut self,
-                      ptr: core::ptr::NonNull<u8>,
-                      layout: Layout,
-                      new_size: usize) -> Result<(NonNull<u8>, usize), AllocErr> {
-        //NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
-        match (layout.size(), new_size) {
-            (0, 0) => Ok((layout.dangling(), 0)),
-            (0, _) => self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())),
-            (_, 0) => {
+    unsafe fn shrink(
+        &mut self,
+        ptr: NonNull<u8>,
+        layout: Layout,
+        new_size: usize,
+        placement: ReallocPlacement,
+    ) -> Result<MemoryBlock, AllocErr> {
+        let size = layout.size();
+        debug_assert!(
+            new_size <= size,
+            "`new_size` must be smaller than or equal to `memory.size()`"
+        );
+
+        if size == new_size {
+            return Ok(MemoryBlock { ptr, size });
+        }
+
+        match placement {
+            ReallocPlacement::InPlace => Err(AllocErr),
+            ReallocPlacement::MayMove if new_size == 0 => {
                 self.dealloc(ptr, layout);
-                Ok((layout.dangling(), 0))
+                Ok(MemoryBlock { ptr: layout.dangling(), size: 0 })
+            }
+            ReallocPlacement::MayMove => {
+                // `realloc` probably checks for `new_size < size` or something similar.
+                intrinsics::assume(new_size < size);
+                let ptr = GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size);
+                Ok(MemoryBlock { ptr: NonNull::new(ptr).ok_or(AllocErr)?, size: new_size })
             }
-            (_, _) => NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size))
-                .ok_or(AllocErr)
-                .map(|p| (p, new_size)),
         }
     }
 }
@@ -100,8 +149,12 @@ mod realloc_fallback {
     use core::ptr;
 
     impl super::System {
-        pub(crate) unsafe fn realloc_fallback(&self, ptr: *mut u8, old_layout: Layout,
-                                              new_size: usize) -> *mut u8 {
+        pub(crate) unsafe fn realloc_fallback(
+            &self,
+            ptr: *mut u8,
+            old_layout: Layout,
+            new_size: usize,
+        ) -> *mut u8 {
             // Docs for GlobalAlloc::realloc require this to be valid:
             let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align());
 
@@ -175,7 +228,7 @@ mod platform {
 mod libc {
     use core::ffi::c_void;
     type size_t = usize;
-    extern {
+    extern "C" {
         pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void;
         pub fn malloc(size: size_t) -> *mut c_void;
         pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void;
diff --git a/sgx_backtrace/Cargo.toml b/sgx_backtrace/Cargo.toml
index fa6f50c..d6224c2 100644
--- a/sgx_backtrace/Cargo.toml
+++ b/sgx_backtrace/Cargo.toml
@@ -1,7 +1,7 @@
 
 [package]
 name = "sgx_backtrace"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
@@ -13,10 +13,10 @@ edition = "2018"
 sgx_demangle = { path = "../sgx_demangle" }
 sgx_backtrace_sys = { path = "../sgx_backtrace_sys" }
 sgx_libc = { path = "../sgx_libc" }
-sgx_unwind = { path = "../sgx_unwind" }
 sgx_types = { path = "../sgx_types" }
 sgx_trts = { path = "../sgx_trts" }
-sgx_tstd = { path = "../sgx_tstd" }
+sgx_tstd = { path = "../sgx_tstd", optional = true }
+sgx_unwind = { path = "../sgx_unwind", optional = true }
 sgx_serialize = { path = "../sgx_serialize", optional = true }
 
 [dependencies]
@@ -24,5 +24,6 @@ sgx_serialize_derive = { path = "../sgx_serialize_derive" }
 
 [features]
 default = ["std"]
-std = []
+std = ["sgx_tstd"]
+nostd = ["sgx_unwind"]
 serialize = ["sgx_serialize"]
diff --git a/sgx_backtrace/src/backtrace/libunwind.rs b/sgx_backtrace/src/backtrace/libunwind.rs
index 98ad368..045ba65 100644
--- a/sgx_backtrace/src/backtrace/libunwind.rs
+++ b/sgx_backtrace/src/backtrace/libunwind.rs
@@ -32,7 +32,7 @@
 //!
 //! This is the default unwinding API for all non-Windows platforms currently.
 
-use sgx_libc::c_void;
+use core::ffi::c_void;
 
 pub enum Frame {
     Raw(*mut uw::_Unwind_Context),
@@ -55,9 +55,7 @@ impl Frame {
             Frame::Raw(ctx) => ctx,
             Frame::Cloned { ip, .. } => return ip,
         };
-        unsafe {
-            uw::_Unwind_GetIP(ctx) as *mut c_void
-        }
+        unsafe { uw::_Unwind_GetIP(ctx) as *mut c_void }
     }
 
     pub fn symbol_address(&self) -> *mut c_void {
@@ -94,8 +92,10 @@ impl Clone for Frame {
 pub unsafe fn trace(mut cb: &mut dyn FnMut(&super::Frame) -> bool) {
     uw::_Unwind_Backtrace(trace_fn, &mut cb as *mut _ as *mut _);
 
-    extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
-                       arg: *mut c_void) -> uw::_Unwind_Reason_Code {
+    extern "C" fn trace_fn(
+        ctx: *mut uw::_Unwind_Context,
+        arg: *mut c_void,
+    ) -> uw::_Unwind_Reason_Code {
         let cb = unsafe { &mut *(arg as *mut &mut dyn FnMut(&super::Frame) -> bool) };
         let cx = super::Frame {
             inner: Frame::Raw(ctx),
@@ -124,7 +124,7 @@ pub unsafe fn trace(mut cb: &mut dyn FnMut(&super::Frame) -> bool) {
 mod uw {
     pub use self::_Unwind_Reason_Code::*;
 
-    use sgx_libc::{c_void, uintptr_t};
+    use core::ffi::c_void;
 
     #[repr(C)]
     pub enum _Unwind_Reason_Code {
@@ -143,37 +143,41 @@ mod uw {
     pub enum _Unwind_Context {}
 
     pub type _Unwind_Trace_Fn =
-            extern fn(ctx: *mut _Unwind_Context,
-                      arg: *mut c_void) -> _Unwind_Reason_Code;
+        extern "C" fn(ctx: *mut _Unwind_Context, arg: *mut c_void) -> _Unwind_Reason_Code;
 
-    extern {
+    extern "C" {
         // No native _Unwind_Backtrace on iOS
         #[cfg(not(all(target_os = "ios", target_arch = "arm")))]
-        pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
-                                 trace_argument: *mut c_void)
-                    -> _Unwind_Reason_Code;
+        pub fn _Unwind_Backtrace(
+            trace: _Unwind_Trace_Fn,
+            trace_argument: *mut c_void,
+        ) -> _Unwind_Reason_Code;
 
         // available since GCC 4.2.0, should be fine for our purpose
-        #[cfg(all(not(all(target_os = "android", target_arch = "arm")),
-                  not(all(target_os = "freebsd", target_arch = "arm")),
-                  not(all(target_os = "linux", target_arch = "arm"))))]
-        pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context)
-                    -> uintptr_t;
-
-        #[cfg(all(not(target_os = "android"),
-                  not(all(target_os = "freebsd", target_arch = "arm")),
-                  not(all(target_os = "linux", target_arch = "arm"))))]
-        pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void)
-            -> *mut c_void;
+        #[cfg(all(
+            not(all(target_os = "android", target_arch = "arm")),
+            not(all(target_os = "freebsd", target_arch = "arm")),
+            not(all(target_os = "linux", target_arch = "arm"))
+        ))]
+        pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> sgx_libc::uintptr_t;
+
+        #[cfg(all(
+            not(target_os = "android"),
+            not(all(target_os = "freebsd", target_arch = "arm")),
+            not(all(target_os = "linux", target_arch = "arm"))
+        ))]
+        pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void;
     }
 
     // On android, the function _Unwind_GetIP is a macro, and this is the
     // expansion of the macro. This is all copy/pasted directly from the
     // header file with the definition of _Unwind_GetIP.
-    #[cfg(any(all(target_os = "android", target_arch = "arm"),
-              all(target_os = "freebsd", target_arch = "arm"),
-              all(target_os = "linux", target_arch = "arm")))]
-    pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> uintptr_t {
+    #[cfg(any(
+        all(target_os = "android", target_arch = "arm"),
+        all(target_os = "freebsd", target_arch = "arm"),
+        all(target_os = "linux", target_arch = "arm")
+    ))]
+    pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> sgx_libc::uintptr_t {
         #[repr(C)]
         enum _Unwind_VRS_Result {
             _UVRSR_OK = 0,
@@ -198,32 +202,37 @@ mod uw {
             _UVRSD_DOUBLE = 5,
         }
 
-        type _Unwind_Word = sgx_libc::c_uint;
-        extern {
-            fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context,
-                               klass: _Unwind_VRS_RegClass,
-                               word: _Unwind_Word,
-                               repr: _Unwind_VRS_DataRepresentation,
-                               data: *mut c_void)
-                -> _Unwind_VRS_Result;
+        type _Unwind_Word = libc::c_uint;
+        extern "C" {
+            fn _Unwind_VRS_Get(
+                ctx: *mut _Unwind_Context,
+                klass: _Unwind_VRS_RegClass,
+                word: _Unwind_Word,
+                repr: _Unwind_VRS_DataRepresentation,
+                data: *mut c_void,
+            ) -> _Unwind_VRS_Result;
         }
 
         let mut val: _Unwind_Word = 0;
         let ptr = &mut val as *mut _Unwind_Word;
-        let _ = _Unwind_VRS_Get(ctx, _Unwind_VRS_RegClass::_UVRSC_CORE, 15,
-                                _Unwind_VRS_DataRepresentation::_UVRSD_UINT32,
-                                ptr as *mut c_void);
-        (val & !1) as uintptr_t
+        let _ = _Unwind_VRS_Get(
+            ctx,
+            _Unwind_VRS_RegClass::_UVRSC_CORE,
+            15,
+            _Unwind_VRS_DataRepresentation::_UVRSD_UINT32,
+            ptr as *mut c_void,
+        );
+        (val & !1) as libc::uintptr_t
     }
 
     // This function also doesn't exist on Android or ARM/Linux, so make it
     // a no-op
-    #[cfg(any(target_os = "android",
-              all(target_os = "freebsd", target_arch = "arm"),
-              all(target_os = "linux", target_arch = "arm")))]
-    pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void)
-        -> *mut c_void
-    {
+    #[cfg(any(
+        target_os = "android",
+        all(target_os = "freebsd", target_arch = "arm"),
+        all(target_os = "linux", target_arch = "arm")
+    ))]
+    pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void {
         pc
     }
 }
diff --git a/sgx_backtrace/src/backtrace/mod.rs b/sgx_backtrace/src/backtrace/mod.rs
index 8161a97..4be0e0a 100644
--- a/sgx_backtrace/src/backtrace/mod.rs
+++ b/sgx_backtrace/src/backtrace/mod.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use core::ffi::c_void;
 use core::fmt;
-use sgx_libc::c_void;
 
 /// Inspects the current call-stack, passing all active frames into the closure
 /// provided to calculate a stack trace.
diff --git a/sgx_backtrace/src/capture.rs b/sgx_backtrace/src/capture.rs
index 5241329..f55af29 100644
--- a/sgx_backtrace/src/capture.rs
+++ b/sgx_backtrace/src/capture.rs
@@ -15,11 +15,12 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use crate::{resolve, resolve_frame, trace, Symbol, SymbolName};
-use std::fmt;
+use crate::PrintFmt;
+use crate::{resolve, resolve_frame, trace, BacktraceFmt, Symbol, SymbolName};
 use std::path::{Path, PathBuf};
 use std::prelude::v1::*;
-use sgx_libc::c_void;
+use core::ffi::c_void;
+use core::fmt;
 
 /// Representation of an owned and self-contained backtrace.
 ///
@@ -136,7 +137,6 @@ impl Backtrace {
     /// enabled, and the `std` feature is enabled by default.
     #[inline(never)] // want to make sure there's a frame here to remove
     pub fn new() -> Backtrace {
-        let _guard = lock_and_platform_init();
         let mut bt = Self::create(Self::new as usize);
         bt.resolve();
         bt
@@ -167,7 +167,6 @@ impl Backtrace {
     /// enabled, and the `std` feature is enabled by default.
     #[inline(never)] // want to make sure there's a frame here to remove
     pub fn new_unresolved() -> Backtrace {
-        let _guard = lock_and_platform_init();
         Self::create(Self::new_unresolved as usize)
     }
 
@@ -217,7 +216,6 @@ impl Backtrace {
     /// This function requires the `std` feature of the `backtrace` crate to be
     /// enabled, and the `std` feature is enabled by default.
     pub fn resolve(&mut self) {
-        let _guard = lock_and_platform_init();
         for frame in self.frames.iter_mut().filter(|f| f.symbols.is_none()) {
             let mut symbols = Vec::new();
             {
@@ -340,55 +338,36 @@ impl BacktraceSymbol {
 
 impl fmt::Debug for Backtrace {
     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
-        write!(fmt, "stack backtrace:")?;
-
-        let iter = if fmt.alternate() {
-            self.frames.iter()
+        let full = fmt.alternate();
+        let (frames, style) = if full {
+            (&self.frames[..], PrintFmt::Full)
         } else {
-            self.frames[self.actual_start_index..].iter()
+            (&self.frames[self.actual_start_index..], PrintFmt::Short)
         };
 
-        for (idx, frame) in iter.enumerate() {
-            // To reduce TCB size in Sgx enclave, we do not want to implement symbol resolution functionality.
-            // Rather, we can print the offset of the address here, which could be later mapped to
-            // correct function.
-            let ip: *mut c_void = frame.ip();
-
-            write!(fmt, "\n{:4}: ", idx)?;
-
-            let symbols = match frame.symbols {
-                Some(ref s) => s,
-                None => {
-                    write!(fmt, "<unresolved> ({:?})", ip)?;
-                    continue;
-                }
-            };
-            if symbols.len() == 0 {
-                write!(fmt, "<no info> ({:?})", ip)?;
-                continue;
-            }
-
-            for (idx, symbol) in symbols.iter().enumerate() {
-                if idx != 0 {
-                    write!(fmt, "\n      ")?;
-                }
-
-                if let Some(name) = symbol.name() {
-                    write!(fmt, "{}", name)?;
-                } else {
-                    write!(fmt, "<unknown>")?;
-                }
-
-                if idx == 0 {
-                    write!(fmt, " ({:?})", ip)?;
-                }
+        // When printing paths we try to strip the cwd if it exists, otherwise
+        // we just print the path as-is. Note that we also only do this for the
+        // short format, because if it's full we presumably want to print
+        // everything.
+        // let cwd = std::env::current_dir();
+        let mut print_path = move |fmt: &mut fmt::Formatter, path: crate::BytesOrWideString| {
+            let path = path.into_path_buf();
+            // if !full {
+            //     if let Ok(cwd) = &cwd {
+            //         if let Ok(suffix) = path.strip_prefix(cwd) {
+            //             return fmt::Display::fmt(&suffix.display(), fmt);
+            //         }
+            //     }
+            // }
+            fmt::Display::fmt(&path.display(), fmt)
+        };
 
-                if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) {
-                    write!(fmt, "\n             at {}:{}", file.display(), line)?;
-                }
-            }
+        let mut f = BacktraceFmt::new(fmt, style, &mut print_path);
+        f.add_context()?;
+        for frame in frames {
+            f.frame().backtrace_frame(frame)?;
         }
-
+        f.finish()?;
         Ok(())
     }
 }
@@ -419,8 +398,6 @@ impl fmt::Debug for BacktraceSymbol {
     }
 }
 
-fn lock_and_platform_init() {}
-
 #[cfg(feature = "serialize")]
 mod sgx_serialize_impls {
     use super::*;
diff --git a/sgx_backtrace/src/lib.rs b/sgx_backtrace/src/lib.rs
index 555ae0f..32cdf2c 100644
--- a/sgx_backtrace/src/lib.rs
+++ b/sgx_backtrace/src/lib.rs
@@ -48,7 +48,7 @@
 //!
 //! ```toml
 //! [dependencies]
-//! sgx_backtrace = "1.0.8"
+//! sgx_backtrace = "1.1.2"
 //! ```
 //!
 //! Next:
@@ -80,8 +80,9 @@
 //! # }
 //! ```
 #![no_std]
-#![feature(panic_unwind)]
-#![cfg_attr(all(target_env = "sgx", feature = "std"), feature(rustc_private))]
+
+#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock", feature = "std"), feature(rustc_private))]
+#![cfg_attr(feature = "nostd", feature(panic_unwind))]
 
 #[cfg(all(not(target_env = "sgx"), feature = "std"))]
 #[macro_use]
@@ -90,9 +91,13 @@ extern crate sgx_tstd as std;
 #[macro_use]
 extern crate std;
 
+extern crate alloc;
 extern crate sgx_backtrace_sys as bt;
+
+#[cfg(feature = "nostd")]
 #[allow(unused_extern_crates)]
 extern crate sgx_unwind;
+
 #[macro_use]
 extern crate sgx_types;
 extern crate sgx_trts;
@@ -119,14 +124,14 @@ mod types;
 #[cfg(feature = "std")]
 pub use crate::symbolize::clear_symbol_cache;
 
+mod print;
+pub use print::{BacktraceFmt, BacktraceFrameFmt, PrintFmt};
 cfg_if! {
     if #[cfg(feature = "std")] {
         pub use crate::backtrace::trace;
         pub use crate::symbolize::{resolve, resolve_frame};
         pub use crate::capture::{Backtrace, BacktraceFrame, BacktraceSymbol};
         mod capture;
-    } else {
-
     }
 }
 
@@ -149,12 +154,12 @@ impl Drop for Bomb {
 mod lock {
     use std::boxed::Box;
     use std::cell::Cell;
-    use std::sync::{SgxMutex, SgxMutexGuard, Once, ONCE_INIT};
+    use std::sync::{SgxMutex, SgxMutexGuard, Once};
 
     pub struct LockGuard(Option<SgxMutexGuard<'static, ()>>);
 
     static mut LOCK: *mut SgxMutex<()> = 0 as *mut _;
-    static INIT: Once = ONCE_INIT;
+    static INIT: Once = Once::new();
     thread_local!(static LOCK_HELD: Cell<bool> = Cell::new(false));
 
     impl Drop for LockGuard {
diff --git a/sgx_backtrace/src/print.rs b/sgx_backtrace/src/print.rs
new file mode 100644
index 0000000..ad47eb9
--- /dev/null
+++ b/sgx_backtrace/src/print.rs
@@ -0,0 +1,254 @@
+// 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..
+
+use crate::BytesOrWideString;
+use core::ffi::c_void;
+use core::fmt;
+
+const HEX_WIDTH: usize = 2 + 2 * core::mem::size_of::<usize>();
+
+/// A formatter for backtraces.
+///
+/// This type can be used to print a backtrace regardless of where the backtrace
+/// itself comes from. If you have a `Backtrace` type then its `Debug`
+/// implementation already uses this printing format.
+pub struct BacktraceFmt<'a, 'b> {
+    fmt: &'a mut fmt::Formatter<'b>,
+    frame_index: usize,
+    format: PrintFmt,
+    print_path: &'a mut (dyn FnMut(&mut fmt::Formatter, BytesOrWideString) -> fmt::Result + 'b),
+}
+
+/// The styles of printing that we can print
+#[derive(Copy, Clone, Eq, PartialEq)]
+pub enum PrintFmt {
+    /// Prints a terser backtrace which ideally only contains relevant information
+    Short,
+    /// Prints a backtrace that contains all possible information
+    Full,
+    #[doc(hidden)]
+    __Nonexhaustive,
+}
+
+impl<'a, 'b> BacktraceFmt<'a, 'b> {
+    /// Create a new `BacktraceFmt` which will write output to the provided
+    /// `fmt`.
+    ///
+    /// The `format` argument will control the style in which the backtrace is
+    /// printed, and the `print_path` argument will be used to print the
+    /// `BytesOrWideString` instances of filenames. This type itself doesn't do
+    /// any printing of filenames, but this callback is required to do so.
+    pub fn new(
+        fmt: &'a mut fmt::Formatter<'b>,
+        format: PrintFmt,
+        print_path: &'a mut (dyn FnMut(&mut fmt::Formatter, BytesOrWideString) -> fmt::Result + 'b),
+    ) -> Self {
+        BacktraceFmt {
+            fmt,
+            frame_index: 0,
+            format,
+            print_path,
+        }
+    }
+
+    /// Prints a preamble for the backtrace about to be printed.
+    ///
+    /// This is required on some platforms for backtraces to be fully
+    /// sumbolicated later, and otherwise this should just be the first method
+    /// you call after creating a `BacktraceFmt`.
+    pub fn add_context(&mut self) -> fmt::Result {
+        Ok(())
+    }
+
+    /// Adds a frame to the backtrace output.
+    ///
+    /// This commit returns an RAII instance of a `BacktraceFrameFmt` which can be used
+    /// to actually print a frame, and on destruction it will increment the
+    /// frame counter.
+    pub fn frame(&mut self) -> BacktraceFrameFmt<'_, 'a, 'b> {
+        BacktraceFrameFmt {
+            fmt: self,
+            symbol_index: 0,
+        }
+    }
+
+    /// Completes the backtrace output.
+    ///
+    /// This is currently a no-op but is added for future compatibility with
+    /// backtrace formats.
+    pub fn finish(&mut self) -> fmt::Result {
+        // Currently a no-op-- including this hook to allow for future additions.
+        Ok(())
+    }
+}
+
+/// A formatter for just one frame of a backtrace.
+///
+/// This type is created by the `BacktraceFmt::frame` function.
+pub struct BacktraceFrameFmt<'fmt, 'a, 'b> {
+    fmt: &'fmt mut BacktraceFmt<'a, 'b>,
+    symbol_index: usize,
+}
+
+impl BacktraceFrameFmt<'_, '_, '_> {
+    /// Prints a `BacktraceFrame` with this frame formatter.
+    ///
+    /// This will recusrively print all `BacktraceSymbol` instances within the
+    /// `BacktraceFrame`.
+    ///
+    /// # Required features
+    ///
+    /// This function requires the `std` feature of the `backtrace` crate to be
+    /// enabled, and the `std` feature is enabled by default.
+    #[cfg(feature = "std")]
+    pub fn backtrace_frame(&mut self, frame: &crate::BacktraceFrame) -> fmt::Result {
+        let symbols = frame.symbols();
+        for symbol in symbols {
+            self.backtrace_symbol(frame, symbol)?;
+        }
+        if symbols.is_empty() {
+            self.print_raw(frame.ip(), None, None, None)?;
+        }
+        Ok(())
+    }
+
+    /// Prints a `BacktraceSymbol` within a `BacktraceFrame`.
+    ///
+    /// # Required features
+    ///
+    /// This function requires the `std` feature of the `backtrace` crate to be
+    /// enabled, and the `std` feature is enabled by default.
+    #[cfg(feature = "std")]
+    pub fn backtrace_symbol(
+        &mut self,
+        frame: &crate::BacktraceFrame,
+        symbol: &crate::BacktraceSymbol,
+    ) -> fmt::Result {
+        self.print_raw(
+            frame.ip(),
+            symbol.name(),
+            // TODO: this isn't great that we don't end up printing anything
+            // with non-utf8 filenames. Thankfully almost everything is utf8 so
+            // this shouldn't be too too bad.
+            symbol
+                .filename()
+                .and_then(|p| Some(BytesOrWideString::Bytes(p.to_str()?.as_bytes()))),
+            symbol.lineno(),
+        )?;
+        Ok(())
+    }
+
+    /// Prints a raw traced `Frame` and `Symbol`, typically from within the raw
+    /// callbacks of this crate.
+    pub fn symbol(&mut self, frame: &crate::Frame, symbol: &crate::Symbol) -> fmt::Result {
+        self.print_raw(
+            frame.ip(),
+            symbol.name(),
+            symbol.filename_raw(),
+            symbol.lineno(),
+        )?;
+        Ok(())
+    }
+
+    /// Adds a raw frame to the backtrace output.
+    ///
+    /// This method, unlike the previous, takes the raw arguments in case
+    /// they're being source from different locations. Note that this may be
+    /// called multiple times for one frame.
+    pub fn print_raw(
+        &mut self,
+        frame_ip: *mut c_void,
+        symbol_name: Option<crate::SymbolName>,
+        filename: Option<BytesOrWideString>,
+        lineno: Option<u32>,
+    ) -> fmt::Result {
+        self.print_raw_generic(frame_ip, symbol_name, filename, lineno)?;
+        self.symbol_index += 1;
+        Ok(())
+    }
+
+    #[allow(unused_mut)]
+    fn print_raw_generic(
+        &mut self,
+        mut frame_ip: *mut c_void,
+        symbol_name: Option<crate::SymbolName>,
+        filename: Option<BytesOrWideString>,
+        lineno: Option<u32>,
+    ) -> fmt::Result {
+        // No need to print "null" frames, it basically just means that the
+        // system backtrace was a bit eager to trace back super far.
+        if let PrintFmt::Short = self.fmt.format {
+            if frame_ip.is_null() {
+                return Ok(());
+            }
+        }
+
+        // Print the index of the frame as well as the optional instruction
+        // pointer of the frame. If we're beyond the first symbol of this frame
+        // though we just print appropriate whitespace.
+        if self.symbol_index == 0 {
+            write!(self.fmt.fmt, "{:4}: ", self.fmt.frame_index)?;
+            if let PrintFmt::Full = self.fmt.format {
+                write!(self.fmt.fmt, "{:1$?} - ", frame_ip, HEX_WIDTH)?;
+            }
+        } else {
+            write!(self.fmt.fmt, "      ")?;
+            if let PrintFmt::Full = self.fmt.format {
+                write!(self.fmt.fmt, "{:1$}", "", HEX_WIDTH + 3)?;
+            }
+        }
+
+        // Next up write out the symbol name, using the alternate formatting for
+        // more information if we're a full backtrace. Here we also handle
+        // symbols which don't have a name,
+        match (symbol_name, &self.fmt.format) {
+            (Some(name), PrintFmt::Short) => write!(self.fmt.fmt, "{:#}", name)?,
+            (Some(name), PrintFmt::Full) => write!(self.fmt.fmt, "{}", name)?,
+            (None, _) | (_, PrintFmt::__Nonexhaustive) => write!(self.fmt.fmt, "<unknown>")?,
+        }
+
+        self.fmt.fmt.write_str("\n")?;
+
+        // And last up, print out the filename/line number if they're available.
+        if let (Some(file), Some(line)) = (filename, lineno) {
+            self.print_fileline(file, line)?;
+        }
+
+        Ok(())
+    }
+
+    fn print_fileline(&mut self, file: BytesOrWideString, line: u32) -> fmt::Result {
+        // Filename/line are printed on lines under the symbol name, so print
+        // some appropriate whitespace to sort of right-align ourselves.
+        if let PrintFmt::Full = self.fmt.format {
+            write!(self.fmt.fmt, "{:1$}", "", HEX_WIDTH)?;
+        }
+        write!(self.fmt.fmt, "             at ")?;
+
+        // Delegate to our internal callback to print the filename and then
+        // print out the line number.
+        (self.fmt.print_path)(self.fmt.fmt, file)?;
+        write!(self.fmt.fmt, ":{}\n", line)?;
+        Ok(())
+    }
+}
+
+impl Drop for BacktraceFrameFmt<'_, '_, '_> {
+    fn drop(&mut self) {
+        self.fmt.frame_index += 1;
+    }
+}
diff --git a/sgx_backtrace/src/symbolize/libbacktrace.rs b/sgx_backtrace/src/symbolize/libbacktrace.rs
index 06fc4ee..af8e743 100644
--- a/sgx_backtrace/src/symbolize/libbacktrace.rs
+++ b/sgx_backtrace/src/symbolize/libbacktrace.rs
@@ -39,6 +39,7 @@
 //! platforms. In libstd though this is the default strategy for OSX.
 
 #![allow(bad_style)]
+#![allow(dead_code)]
 
 use core::{ptr, slice};
 use crate::bt;
@@ -63,22 +64,56 @@ pub enum Symbol {
 
 impl Symbol {
     pub fn name(&self) -> Option<SymbolName> {
-        let symbol = |ptr: *const c_char| {
-            unsafe {
-                if ptr.is_null() {
-                    None
-                } else {
-                    let len = sgx_libc::strlen(ptr);
-                    Some(SymbolName::new(slice::from_raw_parts(
-                        ptr as *const u8,
-                        len,
-                    )))
+        let symbol = |ptr: *const c_char| unsafe {
+            if ptr.is_null() {
+                None
+            } else {
+                let len = sgx_libc::strlen(ptr);
+                Some(SymbolName::new(slice::from_raw_parts(
+                    ptr as *const u8,
+                    len,
+                )))
+            }
+        };
+        match *self {
+            Symbol::Syminfo { symname, .. } => symbol(symname),
+            Symbol::Pcinfo {
+                function, symname, ..
+            } => {
+                // If possible prefer the `function` name which comes from
+                // debuginfo and can typically be more accurate for inline
+                // frames for example. If that's not present though fall back to
+                // the symbol table name specified in `symname`.
+                //
+                // Note that sometimes `function` can feel somewhat less
+                // accurate, for example being listed as `try<i32,closure>`
+                // isntead of `std::panicking::try::do_call`. It's not really
+                // clear why, but overall the `function` name seems more accurate.
+                if let Some(sym) = symbol(function) {
+                    return Some(sym);
                 }
+                symbol(symname)
+            }
+        }
+    }
+
+    pub fn name_bytes(&self) -> Option<&[u8]> {
+        let symbol = |ptr: *const c_char| unsafe {
+            if ptr.is_null() {
+                None
+            } else {
+                let len = sgx_libc::strlen(ptr);
+                Some(slice::from_raw_parts(
+                    ptr as *const u8,
+                    len,
+                ))
             }
         };
         match *self {
             Symbol::Syminfo { symname, .. } => symbol(symname),
-            Symbol::Pcinfo { function, symname, .. } => {
+            Symbol::Pcinfo {
+                function, symname, ..
+            } => {
                 // If possible prefer the `function` name which comes from
                 // debuginfo and can typically be more accurate for inline
                 // frames for example. If that's not present though fall back to
@@ -89,7 +124,7 @@ impl Symbol {
                 // isntead of `std::panicking::try::do_call`. It's not really
                 // clear why, but overall the `function` name seems more accurate.
                 if let Some(sym) = symbol(function) {
-                    return Some(sym)
+                    return Some(sym);
                 }
                 symbol(symname)
             }
@@ -108,11 +143,14 @@ impl Symbol {
         }
     }
 
-    fn filename_bytes(&self) -> Option<&[u8]> {
+    pub fn filename_bytes(&self) -> Option<&[u8]> {
         match *self {
             Symbol::Syminfo { .. } => None,
             Symbol::Pcinfo { filename, .. } => {
                 let ptr = filename as *const u8;
+                if ptr.is_null() {
+                    return None;
+                }
                 unsafe {
                     let len = sgx_libc::strlen(filename);
                     Some(slice::from_raw_parts(ptr, len))
@@ -129,7 +167,6 @@ impl Symbol {
     pub fn filename(&self) -> Option<&::std::path::Path> {
         use std::path::Path;
 
-        #[cfg(unix)]
         fn bytes2path(bytes: &[u8]) -> Option<&Path> {
             use std::ffi::OsStr;
             use std::os::unix::prelude::*;
@@ -192,11 +229,15 @@ extern "C" fn syminfo_cb(
             &mut pcinfo_state as *mut _ as *mut _,
         );
         if !pcinfo_state.called {
+            let inner = Symbol::Syminfo {
+                pc: pc,
+                symname: symname,
+            };
             (pcinfo_state.cb)(&super::Symbol {
-                inner: Symbol::Syminfo {
-                    pc: pc,
-                    symname: symname,
-                },
+                name: inner.name_bytes().map(|m| m.to_vec()),
+                addr: inner.addr(),
+                filename: inner.filename_bytes().map(|m| m.to_vec()),
+                lineno: inner.lineno(),
             });
         }
     }
@@ -226,14 +267,18 @@ extern "C" fn pcinfo_cb(
     unsafe {
         let state = &mut *(data as *mut PcinfoState);
         state.called = true;
+        let inner = Symbol::Pcinfo {
+            pc: pc,
+            filename: filename,
+            lineno: lineno,
+            symname: state.symname,
+            function,
+        };
         (state.cb)(&super::Symbol {
-            inner: Symbol::Pcinfo {
-                pc: pc,
-                filename: filename,
-                lineno: lineno,
-                symname: state.symname,
-                function,
-            },
+            name: inner.name_bytes().map(|m| m.to_vec()),
+            addr: inner.addr(),
+            filename: inner.filename_bytes().map(|m| m.to_vec()),
+            lineno: inner.lineno(),
         });
     }
 
@@ -261,8 +306,13 @@ unsafe fn init_state() -> *mut bt::backtrace_state {
         return STATE;
     }
 
+    let filename = load_filename();
+    if filename.is_null() {
+        return ptr::null_mut();
+    }
+
     STATE = bt::backtrace_create_state(
-        load_filename(),
+        filename,
         // Don't exercise threadsafe capabilities of libbacktrace since
         // we're always calling it in a synchronized fashion.
         0,
diff --git a/sgx_backtrace/src/symbolize/mod.rs b/sgx_backtrace/src/symbolize/mod.rs
index 7e83192..1c6ef35 100644
--- a/sgx_backtrace/src/symbolize/mod.rs
+++ b/sgx_backtrace/src/symbolize/mod.rs
@@ -16,19 +16,18 @@
 // under the License..
 
 use core::{fmt, str};
+use alloc::vec::Vec;
 
 cfg_if! {
     if #[cfg(feature = "std")] {
         use std::path::Path;
         use std::prelude::v1::*;
-    } else {
-
     }
 }
 
 use crate::backtrace::Frame;
 use crate::types::BytesOrWideString;
-use sgx_libc::c_void;
+use core::ffi::c_void;
 use sgx_demangle::{try_demangle, Demangle};
 
 /// Resolve an address to a symbol, passing the symbol to the specified
@@ -210,7 +209,10 @@ pub struct Symbol {
     // TODO: this lifetime bound needs to be persisted eventually to `Symbol`,
     // but that's currently a breaking change. For now this is safe since
     // `Symbol` is only ever handed out by reference and can't be cloned.
-    inner: SymbolImp,
+    name: Option<Vec<u8>>,
+    addr: Option<*mut c_void>,
+    filename: Option<Vec<u8>>,
+    lineno: Option<u32>,
 }
 
 impl Symbol {
@@ -224,18 +226,18 @@ impl Symbol {
     ///   utf-8).
     /// * The raw bytes for the symbol name can be accessed.
     pub fn name(&self) -> Option<SymbolName> {
-        self.inner.name()
+        self.name.as_ref().map(|m| SymbolName::new(m.as_slice()))
     }
 
     /// Returns the starting address of this function.
     pub fn addr(&self) -> Option<*mut c_void> {
-        self.inner.addr().map(|p| p as *mut _)
+       self.addr
     }
 
     /// Returns the raw filename as a slice. This is mainly useful for `no_std`
     /// environments.
     pub fn filename_raw(&self) -> Option<BytesOrWideString> {
-        self.inner.filename_raw()
+        self.filename.as_ref().map(|f| BytesOrWideString::Bytes(f.as_slice()))
     }
 
     /// Returns the line number for where this symbol is currently executing.
@@ -243,7 +245,7 @@ impl Symbol {
     /// This return value is typically `Some` if `filename` returns `Some`, and
     /// is consequently subject to similar caveats.
     pub fn lineno(&self) -> Option<u32> {
-        self.inner.lineno()
+        self.lineno
     }
 
     /// Returns the file name where this function was defined.
@@ -260,7 +262,10 @@ impl Symbol {
     #[cfg(feature = "std")]
     #[allow(unreachable_code)]
     pub fn filename(&self) -> Option<&Path> {
-        self.inner.filename()
+        use std::ffi::OsStr;
+        use std::os::unix::prelude::*;
+
+        self.filename.as_ref().map(|f| Path::new(OsStr::from_bytes(f.as_slice())))
     }
 }
 
@@ -392,7 +397,6 @@ pub fn clear_symbol_cache() {
 
 mod libbacktrace;
 use self::libbacktrace::resolve as resolve_imp;
-use self::libbacktrace::Symbol as SymbolImp;
 pub use libbacktrace::set_enclave_path;
 
 #[allow(dead_code)]
diff --git a/sgx_backtrace/src/types.rs b/sgx_backtrace/src/types.rs
index 97f4f6b..7098d70 100644
--- a/sgx_backtrace/src/types.rs
+++ b/sgx_backtrace/src/types.rs
@@ -23,8 +23,6 @@ cfg_if! {
         use std::fmt;
         use std::path::PathBuf;
         use std::prelude::v1::*;
-    } else {
-
     }
 }
 
diff --git a/sgx_backtrace_sys/Cargo.toml b/sgx_backtrace_sys/Cargo.toml
index 4f44fbc..154b90d 100644
--- a/sgx_backtrace_sys/Cargo.toml
+++ b/sgx_backtrace_sys/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_backtrace_sys"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 build = "build.rs"
 repository = "https://github.com/apache/teaclave-sgx-sdk"
diff --git a/sgx_backtrace_sys/src/lib.rs b/sgx_backtrace_sys/src/lib.rs
index 35acddd..68265ff 100644
--- a/sgx_backtrace_sys/src/lib.rs
+++ b/sgx_backtrace_sys/src/lib.rs
@@ -27,37 +27,43 @@ pub use self::bindings::*;
 mod bindings {
 
     pub type backtrace_syminfo_callback = extern "C" fn(
-                data: *mut libc::c_void,
-                pc: libc::uintptr_t,
-                symname: *const libc::c_char,
-                symval: libc::uintptr_t,
-                symsize: libc::uintptr_t);
+        data: *mut libc::c_void,
+        pc: libc::uintptr_t,
+        symname: *const libc::c_char,
+        symval: libc::uintptr_t,
+        symsize: libc::uintptr_t);
     pub type backtrace_full_callback = extern "C" fn(
-                data: *mut libc::c_void,
-                pc: libc::uintptr_t,
-                filename: *const libc::c_char,
-                lineno: libc::c_int,
-                function: *const libc::c_char) -> libc::c_int;
+        data: *mut libc::c_void,
+        pc: libc::uintptr_t,
+        filename: *const libc::c_char,
+        lineno: libc::c_int,
+        function: *const libc::c_char) -> libc::c_int;
     pub type backtrace_error_callback = extern "C" fn(
-                data: *mut libc::c_void,
-                msg: *const libc::c_char,
-                errnum: libc::c_int);
+        data: *mut libc::c_void,
+        msg: *const libc::c_char,
+        errnum: libc::c_int);
     pub enum backtrace_state {}
 
     extern "C" {
-        pub fn backtrace_create_state(filename: *const libc::c_char,
-                                      threaded: libc::c_int,
-                                      error: backtrace_error_callback,
-                                      data: *mut libc::c_void) -> *mut backtrace_state;
-        pub fn backtrace_syminfo(state: *mut backtrace_state,
-                                 addr: libc::uintptr_t,
-                                 cb: backtrace_syminfo_callback,
-                                 error: backtrace_error_callback,
-                                 data: *mut libc::c_void) -> libc::c_int;
-        pub fn backtrace_pcinfo(state: *mut backtrace_state,
-                                addr: libc::uintptr_t,
-                                cb: backtrace_full_callback,
-                                error: backtrace_error_callback,
-                                data: *mut libc::c_void) -> libc::c_int;
+        pub fn backtrace_create_state(
+            filename: *const libc::c_char,
+            threaded: libc::c_int,
+            error: backtrace_error_callback,
+            data: *mut libc::c_void,
+        ) -> *mut backtrace_state;
+        pub fn backtrace_syminfo(
+            state: *mut backtrace_state,
+            addr: libc::uintptr_t,
+            cb: backtrace_syminfo_callback,
+            error: backtrace_error_callback,
+            data: *mut libc::c_void,
+        ) -> libc::c_int;
+        pub fn backtrace_pcinfo(
+            state: *mut backtrace_state,
+            addr: libc::uintptr_t,
+            cb: backtrace_full_callback,
+            error: backtrace_error_callback,
+            data: *mut libc::c_void,
+        ) -> libc::c_int;
     }
 }
\ No newline at end of file
diff --git a/sgx_build_helper/lib.rs b/sgx_build_helper/lib.rs
index 106c45a..123e265 100644
--- a/sgx_build_helper/lib.rs
+++ b/sgx_build_helper/lib.rs
@@ -23,7 +23,7 @@ use std::ffi::OsStr;
 /// * The error itself
 ///
 /// This is currently used judiciously throughout the build system rather than
-/// using a `Result` with `r#try!`, but this may change one day...
+/// using a `Result` with `try!`, but this may change one day...
 #[macro_export]
 macro_rules! t {
     ($e:expr) => {
@@ -32,6 +32,38 @@ macro_rules! t {
             Err(e) => panic!("{} failed with {}", stringify!($e), e),
         }
     };
+    // it can show extra info in the second parameter
+    ($e:expr, $extra:expr) => {
+        match $e {
+            Ok(e) => e,
+            Err(e) => panic!("{} failed with {} ({:?})", stringify!($e), e, $extra),
+        }
+    };
+}
+
+// Because Cargo adds the compiler's dylib path to our library search path, llvm-config may
+// break: the dylib path for the compiler, as of this writing, contains a copy of the LLVM
+// shared library, which means that when our freshly built llvm-config goes to load it's
+// associated LLVM, it actually loads the compiler's LLVM. In particular when building the first
+// compiler (i.e., in stage 0) that's a problem, as the compiler's LLVM is likely different from
+// the one we want to use. As such, we restore the environment to what bootstrap saw. This isn't
+// perfect -- we might actually want to see something from Cargo's added library paths -- but
+// for now it works.
+pub fn restore_library_path() {
+    println!("cargo:rerun-if-env-changed=REAL_LIBRARY_PATH_VAR");
+    println!("cargo:rerun-if-env-changed=REAL_LIBRARY_PATH");
+    let key = env::var_os("REAL_LIBRARY_PATH_VAR").expect("REAL_LIBRARY_PATH_VAR");
+    if let Some(env) = env::var_os("REAL_LIBRARY_PATH") {
+        env::set_var(&key, &env);
+    } else {
+        env::remove_var(&key);
+    }
+}
+
+/// Run the command, printing what we are running.
+pub fn run_verbose(cmd: &mut Command) {
+    println!("running: {:?}", cmd);
+    run_silent(cmd);
 }
 
 pub fn run(cmd: &mut Command) {
@@ -103,8 +135,10 @@ pub fn gnu_target(target: &str) -> &str {
 }
 
 pub fn make(host: &str) -> PathBuf {
-    if host.contains("dragonfly") || host.contains("freebsd")
-        || host.contains("netbsd") || host.contains("openbsd")
+    if host.contains("dragonfly")
+        || host.contains("freebsd")
+        || host.contains("netbsd")
+        || host.contains("openbsd")
     {
         PathBuf::from("gmake")
     } else {
@@ -131,7 +165,8 @@ pub fn output(cmd: &mut Command) -> String {
 }
 
 pub fn rerun_if_changed_anything_in_dir(dir: &Path, filter: &Vec<&str>) {
-    let mut stack = dir.read_dir()
+    let mut stack = dir
+        .read_dir()
         .unwrap()
         .map(|e| e.unwrap())
         .filter(|e| !is_in_filter_list(&*e.file_name(), filter))
@@ -160,7 +195,7 @@ pub fn mtime(path: &Path) -> SystemTime {
         .unwrap_or(UNIX_EPOCH)
 }
 
-/// Returns whether `dst` is up to date given that the file or files in `src`
+/// Returns `true` if `dst` is up to date given that the file or files in `src`
 /// are used to generate it.
 ///
 /// Uses last-modified time checks to verify this.
diff --git a/sgx_cov/Cargo.toml b/sgx_cov/Cargo.toml
index 45d2e07..2f3a06d 100644
--- a/sgx_cov/Cargo.toml
+++ b/sgx_cov/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_cov"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_crypto_helper/Cargo.toml b/sgx_crypto_helper/Cargo.toml
index e82342e..c75f4e1 100644
--- a/sgx_crypto_helper/Cargo.toml
+++ b/sgx_crypto_helper/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_crypto_helper"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
@@ -28,7 +28,7 @@ mesalock_sgx = [
     "serde-big-array-sgx"]
 
 [dependencies]
-sgx_ucrypto = { rev = "v1.1.1", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
+sgx_ucrypto = { rev = "v1.1.2", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
 libc = { version = "0.2", optional = true }
 itertools = { version = "*", default-features = false }
 serde = { version = "1.0.104", optional = true }
@@ -39,43 +39,12 @@ serde_derive-sgx = { git = "https://github.com/mesalock-linux/serde-sgx", packag
 serde-big-array-sgx = { git = "https://github.com/mesalock-linux/serde-big-array-sgx", package = 'serde-big-array', optional = true }
 
 [target.'cfg(not(target_env = "sgx"))'.dependencies]
-sgx_tcrypto = { rev = "v1.1.1", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
-sgx_tstd    = { rev = "v1.1.1", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
-sgx_types   = { rev = "v1.1.1", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
+sgx_tcrypto = { rev = "v1.1.2", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
+sgx_tstd    = { rev = "v1.1.2", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
+sgx_types   = { rev = "v1.1.2", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 
 [dev-dependencies]
-sgx_ucrypto = { rev = "v1.1.1", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
+sgx_ucrypto = { rev = "v1.1.2", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 rdrand = "0.6"
 rand_core = "0.4"
 serde_json = "*"
-
-#[patch.'https://github.com/apache/teaclave-sgx-sdk.git']
-#sgx_align_struct_attribute = { path = "../sgx_align_struct_attribute" }
-#sgx_alloc = { path = "../sgx_alloc" }
-#sgx_backtrace = { path = "../sgx_backtrace" }
-#sgx_backtrace_sys = { path = "../sgx_backtrace_sys" }
-#sgx_build_helper = { path = "../sgx_build_helper" }
-#sgx_cov = { path = "../sgx_cov" }
-#sgx_crypto_helper = { path = "../sgx_crypto_helper" }
-#sgx_demangle = { path = "../sgx_demangle" }
-#sgx_libc = { path = "../sgx_libc" }
-#sgx_no_tstd = { path = "../sgx_no_tstd" }
-#sgx_rand = { path = "../sgx_rand" }
-#sgx_rand_derive = { path = "../sgx_rand_derive" }
-#sgx_serialize = { path = "../sgx_serialize" }
-#sgx_serialize_derive = { path = "../sgx_serialize_derive" }
-#sgx_serialize_derive_internals = { path = "../sgx_serialize_derive_internals" }
-#sgx_tcrypto = { path = "../sgx_tcrypto" }
-#sgx_tcrypto_helper = { path = "../sgx_tcrypto_helper" }
-#sgx_tdh = { path = "../sgx_tdh" }
-#sgx_tkey_exchange = { path = "../sgx_tkey_exchange" }
-#sgx_tprotected_fs = { path = "../sgx_tprotected_fs" }
-#sgx_trts = { path = "../sgx_trts" }
-#sgx_tse = { path = "../sgx_tse" }
-#sgx_tseal = { path = "../sgx_tseal" }
-#sgx_tstd = { path = "../sgx_tstd" }
-#sgx_tunittest = { path = "../sgx_tunittest" }
-#sgx_types = { path = "../sgx_types" }
-#sgx_ucrypto = { path = "../sgx_ucrypto" }
-#sgx_unwind = { path = "../sgx_unwind" }
-#sgx_urts = { path = "../sgx_urts" }
diff --git a/sgx_demangle/Cargo.toml b/sgx_demangle/Cargo.toml
index b0e19a8..c6cf10e 100644
--- a/sgx_demangle/Cargo.toml
+++ b/sgx_demangle/Cargo.toml
@@ -1,7 +1,7 @@
 
 [package]
 name = "sgx_demangle"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_libc/Cargo.toml b/sgx_libc/Cargo.toml
index bcd4509..baeb11b 100644
--- a/sgx_libc/Cargo.toml
+++ b/sgx_libc/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_libc"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_libc/src/linux/x86_64/mod.rs b/sgx_libc/src/linux/x86_64/mod.rs
index b63a66a..4477875 100644
--- a/sgx_libc/src/linux/x86_64/mod.rs
+++ b/sgx_libc/src/linux/x86_64/mod.rs
@@ -31,7 +31,7 @@ use sgx_types::{sgx_thread_mutex_t, sgx_thread_mutex_attr_t, sgx_thread_cond_t,
 use core::ptr;
 use core::mem;
 
-extern {
+extern "C" {
     pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void;
     pub fn malloc(size: size_t) -> *mut c_void;
     pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void;
@@ -40,10 +40,10 @@ extern {
 }
 
 #[link(name = "sgx_pthread")]
-extern {
+extern "C" {
     pub fn pthread_create(native: *mut pthread_t,
                           attr: *const pthread_attr_t,
-                          f: extern fn(*mut c_void) -> *mut c_void,
+                          f: extern "C" fn(*mut c_void) -> *mut c_void,
                           value: *mut c_void) -> c_int;
     pub fn pthread_join(native: pthread_t,
                         value: *mut *mut c_void) -> c_int;
@@ -51,10 +51,10 @@ extern {
     pub fn pthread_self() -> pthread_t;
     pub fn pthread_equal(t1: pthread_t, t2: pthread_t) -> c_int;
 
-    pub fn pthread_once(once_control: *mut pthread_once_t, init_routine: extern fn()) -> c_int;
+    pub fn pthread_once(once_control: *mut pthread_once_t, init_routine: extern "C" fn()) -> c_int;
 
     pub fn pthread_key_create(key: *mut pthread_key_t,
-                              dtor: Option<unsafe extern fn(*mut c_void)>) -> c_int;
+                              dtor: Option<unsafe extern "C" fn(*mut c_void)>) -> c_int;
     pub fn pthread_key_delete(key: pthread_key_t) -> c_int;
     pub fn pthread_getspecific(key: pthread_key_t) -> *mut c_void;
     pub fn pthread_setspecific(key: pthread_key_t, value: *const c_void) -> c_int;
@@ -78,13 +78,13 @@ extern {
 pub type exit_function_t = extern "C" fn();
 
 #[link(name = "sgx_trts")]
-extern {
+extern "C" {
     pub fn abort() -> !;
     pub fn atexit(fun: exit_function_t) -> c_int;
 }
 
 #[link(name = "sgx_tstdc")]
-extern {
+extern "C" {
     //pub fn memchr(s: *const c_void, c: c_int, n: size_t) -> *mut c_void;
     //pub fn memrchr(cx: *const c_void, c: c_int, n: size_t) -> *mut c_void;
     pub fn strlen(s: *const c_char) -> size_t;
@@ -92,7 +92,7 @@ extern {
 }
 
 #[link(name = "sgx_tstdc")]
-extern {
+extern "C" {
     #[cfg_attr(target_os = "linux", link_name = "__errno_location")]
     fn errno_location() -> *mut c_int;
     fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int;
@@ -177,6 +177,8 @@ pub type ino64_t = u64;
 pub type nfds_t = c_ulong;
 pub type pid_t = i32;
 
+pub type sighandler_t = size_t;
+
 pub type pthread_t = *mut c_void;
 pub type pthread_attr_t = *mut c_void;
 pub type pthread_mutex_t = *mut sgx_thread_mutex_t;
@@ -473,6 +475,24 @@ s! {
         pub state: c_int,
         pub mutex: pthread_mutex_t,
     }
+
+    pub struct sigset_t {
+        __val: [u64; 16],
+    }
+
+    pub struct sigaction {
+        pub sa_sigaction: sighandler_t,
+        pub sa_mask: sigset_t,
+        pub sa_flags: c_int,
+        pub sa_restorer: Option<extern fn()>,
+    }
+    pub struct siginfo_t {
+        pub si_signo: c_int,
+        pub si_errno: c_int,
+        pub si_code: c_int,
+        pub _pad: [c_int; 29],
+        _align: [usize; 0],
+    }
 }
 
 pub const AT_FDCWD: c_int = -100;
@@ -966,6 +986,14 @@ pub const POLLNVAL: c_short = 0x20;
 pub const POLLRDNORM: c_short = 0x040;
 pub const POLLRDBAND: c_short = 0x080;
 
+pub const AI_PASSIVE: c_int = 0x0001;
+pub const AI_CANONNAME: c_int = 0x0002;
+pub const AI_NUMERICHOST: c_int = 0x0004;
+pub const AI_V4MAPPED: c_int = 0x0008;
+pub const AI_ALL: c_int = 0x0010;
+pub const AI_ADDRCONFIG: c_int = 0x0020;
+pub const AI_NUMERICSERV: c_int = 0x0400;
+
 pub const EAI_BADFLAGS: c_int = -1;
 pub const EAI_NONAME: c_int = -2;
 pub const EAI_AGAIN: c_int = -3;
@@ -1365,6 +1393,48 @@ pub const EHWPOISON: int32_t          = 133;
 pub const ENOTSUP: int32_t            = EOPNOTSUPP;
 pub const ESGX: int32_t               = 0x0000_FFFF;
 
+pub const SA_NODEFER: c_int = 0x40000000;
+pub const SA_RESETHAND: c_int = 0x80000000;
+pub const SA_RESTART: c_int = 0x10000000;
+pub const SA_NOCLDSTOP: c_int = 0x00000001;
+
+pub const SA_ONSTACK: c_int = 0x08000000;
+pub const SA_SIGINFO: c_int = 0x00000004;
+pub const SA_NOCLDWAIT: c_int = 0x00000002;
+
+pub const SIG_DFL: sighandler_t = 0 as sighandler_t;
+pub const SIG_IGN: sighandler_t = 1 as sighandler_t;
+pub const SIG_ERR: sighandler_t = !0 as sighandler_t;
+
+pub const SIGTRAP: c_int = 5;
+pub const SIGCHLD: c_int = 17;
+pub const SIGBUS: c_int = 7;
+pub const SIGTTIN: c_int = 21;
+pub const SIGTTOU: c_int = 22;
+pub const SIGXCPU: c_int = 24;
+pub const SIGXFSZ: c_int = 25;
+pub const SIGVTALRM: c_int = 26;
+pub const SIGPROF: c_int = 27;
+pub const SIGWINCH: c_int = 28;
+pub const SIGUSR1: c_int = 10;
+pub const SIGUSR2: c_int = 12;
+pub const SIGCONT: c_int = 18;
+pub const SIGSTOP: c_int = 19;
+pub const SIGTSTP: c_int = 20;
+pub const SIGURG: c_int = 23;
+pub const SIGIO: c_int = 29;
+pub const SIGSYS: c_int = 31;
+pub const SIGSTKFLT: c_int = 16;
+pub const SIGPOLL: c_int = 29;
+pub const SIGPWR: c_int = 30;
+pub const SIG_SETMASK: c_int = 2;
+pub const SIG_BLOCK: c_int = 0x000000;
+pub const SIG_UNBLOCK: c_int = 0x01;
+
+pub const SIGRTMIN: c_int = 32;
+pub const SIGRTMAX: c_int = 64;
+pub const NSIG: c_int = SIGRTMAX + 1;
+
 #[inline]
 pub unsafe fn FD_CLR(fd: c_int, set: *mut fd_set) -> () {
     let fd = fd as usize;
@@ -1432,4 +1502,84 @@ pub unsafe fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool {
     set1.bits == set2.bits
 }
 
+#[inline]
+unsafe fn __sigmask(sig: c_int) -> u64 {
+    (1 as u64) << (((sig) - 1) % (8 * mem::size_of::<u64>()) as i32)
+}
+
+#[inline]
+unsafe fn __sigword(sig: c_int) -> u64 {
+   ((sig - 1) / ((8 *  mem::size_of::<u64>()) as i32)) as u64
+}
+
+#[inline]
+unsafe fn __sigaddset(set: *mut sigset_t, sig: c_int) {
+    let mask: u64 = __sigmask (sig);
+    let word: u64 = __sigword (sig);
+    (*set).__val[word as usize] |= mask;
+}
+
+#[inline]
+unsafe fn __sigdelset(set: *mut sigset_t, sig: c_int) {
+    let mask: u64 = __sigmask (sig);
+    let word: u64 = __sigword (sig);
+    (*set).__val[word as usize] &= !mask;
+}
+
+#[inline]
+unsafe fn __sigismember(set: *const sigset_t, sig: c_int) -> c_int {
+    let mask: u64 = __sigmask (sig);
+    let word: u64 = __sigword (sig);
+    let val = if mask != 0 {
+        1
+    } else {
+        0
+    };
+    ((*set).__val[word as usize] & val) as c_int
+}
+
+pub unsafe fn sigemptyset(set: *mut sigset_t) -> c_int {
+    if set.is_null() {
+        set_errno(EINVAL);
+        return -1;
+    }
+    ptr::write_bytes(set as * mut sigset_t, 0,  1);
+    0
+}
+
+pub unsafe fn sigaddset(set: *mut sigset_t, signum: c_int) -> c_int {
+    if set.is_null() || signum <= 0 || signum >= NSIG {
+        set_errno(EINVAL);
+        return -1;
+    }
+    __sigaddset(set, signum);
+    0
+}
+
+pub unsafe fn sigfillset(set: *mut sigset_t) -> c_int {
+    if set.is_null() {
+        set_errno(EINVAL);
+        return -1;
+    }
+    ptr::write_bytes(set, 0xff, 1);
+    0
+}
+
+pub unsafe fn sigdelset(set: *mut sigset_t, signum: c_int) -> c_int {
+    if set.is_null() || signum <= 0 || signum >= NSIG {
+        set_errno(EINVAL);
+        return -1;
+    }
+    __sigdelset(set, signum);
+    0
+}
+
+pub unsafe fn sigismember(set: *const sigset_t, signum: c_int) -> c_int {
+    if set.is_null() || signum <= 0 || signum >= NSIG {
+        set_errno(EINVAL);
+        return -1;
+    }
+    __sigismember(set, signum)
+}
+
 pub mod ocall;
diff --git a/sgx_libc/src/linux/x86_64/ocall.rs b/sgx_libc/src/linux/x86_64/ocall.rs
index 29e3daa..973d836 100644
--- a/sgx_libc/src/linux/x86_64/ocall.rs
+++ b/sgx_libc/src/linux/x86_64/ocall.rs
@@ -444,6 +444,21 @@ extern "C" {
                               error: *mut c_int,
                               rqtp: *const timespec,
                               rmtp: *mut timespec) -> sgx_status_t;
+    //signal
+    pub fn u_sigaction_ocall(result: *mut c_int,
+                             error: *mut c_int,
+                             signum: c_int,
+                             act: *const sigaction,
+                             oldact: *mut sigaction,
+                             enclave_id: uint64_t) -> sgx_status_t;
+    pub fn u_sigprocmask_ocall(result: *mut c_int,
+                                error: *mut c_int,
+                                signum: c_int,
+                                set: *const sigset_t,
+                                oldset: *mut sigset_t) -> sgx_status_t;
+    pub fn u_raise_ocall(result: *mut c_int, signum: c_int) -> sgx_status_t;
+    //process
+    pub fn u_getpid_ocall(result: *mut pid_t) -> sgx_status_t;
 }
 
 pub unsafe fn malloc(size: size_t) -> *mut c_void {
@@ -2581,15 +2596,28 @@ pub unsafe fn getaddrinfo(node: *const c_char,
     let mut result: c_int = 0;
     let mut error: c_int = 0;
     let mut ret_res: *mut addrinfo = ptr::null_mut();
-    let hint: addrinfo = addrinfo {
-        ai_flags: (*hints).ai_flags,
-        ai_family: (*hints).ai_family,
-        ai_socktype: (*hints).ai_socktype,
-        ai_protocol: (*hints).ai_protocol,
-        ai_addrlen: 0,
-        ai_addr: ptr::null_mut(),
-        ai_canonname: ptr::null_mut(),
-        ai_next: ptr::null_mut(),
+    let hint: addrinfo = if !hints.is_null() {
+        addrinfo {
+            ai_flags: (*hints).ai_flags,
+            ai_family: (*hints).ai_family,
+            ai_socktype: (*hints).ai_socktype,
+            ai_protocol: (*hints).ai_protocol,
+            ai_addrlen: 0,
+            ai_addr: ptr::null_mut(),
+            ai_canonname: ptr::null_mut(),
+            ai_next: ptr::null_mut(),
+        }
+    } else {
+        addrinfo {
+            ai_flags: AI_V4MAPPED | AI_ADDRCONFIG,
+            ai_family: AF_UNSPEC,
+            ai_socktype: 0,
+            ai_protocol: 0,
+            ai_addrlen: 0,
+            ai_addr: ptr::null_mut(),
+            ai_canonname: ptr::null_mut(),
+            ai_next: ptr::null_mut(),
+        }
     };
 
     let status = u_getaddrinfo_ocall(&mut result as *mut c_int,
@@ -2644,11 +2672,12 @@ pub unsafe fn getaddrinfo(node: *const c_char,
                 for i in 0..addrinfo_vec.len() - 1 {
                     addrinfo_vec[i].ai_next = addrinfo_vec[i + 1].as_mut() as *mut addrinfo;
                 }
-                *res = addrinfo_vec[0].as_mut() as *mut addrinfo;
+                let res_ptr = addrinfo_vec[0].as_mut() as *mut addrinfo;
 
                 for info in addrinfo_vec {
                     let _ = Box::into_raw(info);
                 }
+                *res = res_ptr;
             }
             let _ = u_freeaddrinfo_ocall(ret_res);
 
@@ -2921,4 +2950,70 @@ pub unsafe fn nanosleep(rqtp: *const timespec, rmtp: *mut timespec) -> c_int {
         result = -1;
     }
     result
-}
\ No newline at end of file
+}
+
+pub unsafe fn sigaction(signum: c_int,
+                        act: *const sigaction,
+                        oldact: *mut sigaction,
+                        enclave_id: uint64_t) -> c_int {
+    let mut result: c_int = 0;
+    let mut error: c_int = 0;
+    let status = u_sigaction_ocall(&mut result as *mut c_int,
+                                   &mut error as *mut c_int,
+                                   signum,
+                                   act,
+                                   oldact,
+                                   enclave_id);
+    if status == sgx_status_t::SGX_SUCCESS {
+        if result == -1 {
+            set_errno(error);
+        }
+    } else {
+        set_errno(ESGX);
+        result = -1;
+    }
+    result
+}
+
+pub unsafe fn sigprocmask(signum: c_int,
+                          set: *const sigset_t,
+                          oldset: *mut sigset_t) -> c_int {
+    let mut result: c_int = 0;
+    let mut error: c_int = 0;
+    let status =  u_sigprocmask_ocall(&mut result as *mut c_int,
+                                      &mut error as *mut c_int,
+                                      signum,
+                                      set,
+                                      oldset);
+    if status == sgx_status_t::SGX_SUCCESS {
+        if result == -1 {
+            set_errno(error);
+        }
+    } else {
+        set_errno(ESGX);
+        result = -1;
+    }
+    result
+}
+
+pub unsafe fn raise(signum: c_int) -> c_int {
+    let mut result: c_int = -1;
+    let status = u_raise_ocall(&mut result as *mut c_int, signum);
+    if status != sgx_status_t::SGX_SUCCESS {
+       result = -1;
+    }
+    result
+}
+
+pub unsafe fn pthread_sigmask(signum: c_int, set: &sigset_t, oldset: &mut sigset_t) -> c_int {
+    sigprocmask(signum, set, oldset)
+}
+
+pub unsafe fn getpid() -> pid_t {
+    let mut result = -1;
+    let status = u_getpid_ocall(&mut result as *mut pid_t);
+    if status != sgx_status_t::SGX_SUCCESS {
+        result = -1;
+    }
+    result
+}
diff --git a/sgx_libc/src/macros.rs b/sgx_libc/src/macros.rs
index 07cf560..d946f7a 100644
--- a/sgx_libc/src/macros.rs
+++ b/sgx_libc/src/macros.rs
@@ -138,7 +138,6 @@ macro_rules! f {
     )*)
 }
 
-
 macro_rules! __item {
     ($i:item) => {
         $i
diff --git a/sgx_no_tstd/Cargo.toml b/sgx_no_tstd/Cargo.toml
index 4e41e12..af03c60 100644
--- a/sgx_no_tstd/Cargo.toml
+++ b/sgx_no_tstd/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_no_tstd"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 build = "build.rs"
 repository = "https://github.com/apache/teaclave-sgx-sdk"
diff --git a/sgx_no_tstd/build.rs b/sgx_no_tstd/build.rs
index e1f40f2..2fea965 100644
--- a/sgx_no_tstd/build.rs
+++ b/sgx_no_tstd/build.rs
@@ -44,7 +44,29 @@ fn build_libunwind(host: &str, target: &str) -> Result<(), ()> {
                     "unwind",
                     "src/.libs",
                     &filter)?;
-    let cflags = env::var("CFLAGS").unwrap_or_default() + " -fvisibility=hidden -O2";
+
+    let mut cflags = String::new();
+    cflags += " -fstack-protector -ffreestanding -nostdinc -fvisibility=hidden -fpie -fno-strict-overflow -fno-delete-null-pointer-checks";
+    cflags += " -O2";
+
+    let mitigation_cflags = " -mindirect-branch-register -mfunction-return=thunk-extern";
+    let mitigation_asflags = " -fno-plt";
+    let mitigation_loadflags = " -Wa,-mlfence-after-load=yes -Wa,-mlfence-before-ret=not";
+    let mitigation_cfflags = " -Wa,-mlfence-before-indirect-branch=register -Wa,-mlfence-before-ret=not";
+    let mitigation = env::var("MITIGATION_CVE_2020_0551").unwrap_or_default();
+    match mitigation.as_ref() {
+        "LOAD" => {
+            cflags += mitigation_cflags;
+            cflags += mitigation_asflags;
+            cflags += mitigation_loadflags;
+        },
+        "CF" => {
+            cflags += mitigation_cflags;
+            cflags += mitigation_asflags;
+            cflags += mitigation_cfflags;
+        },
+        _  => {},
+    }
 
     run(Command::new("sh")
                 .current_dir(&native.out_dir)
@@ -58,4 +80,4 @@ fn build_libunwind(host: &str, target: &str) -> Result<(), ()> {
                 .arg(format!("INCDIR={}", native.src_dir.display()))
                 .arg("-j5"));
     Ok(())
-}
+}
\ No newline at end of file
diff --git a/sgx_no_tstd/src/lib.rs b/sgx_no_tstd/src/lib.rs
index 500be30..c70955d 100644
--- a/sgx_no_tstd/src/lib.rs
+++ b/sgx_no_tstd/src/lib.rs
@@ -38,7 +38,7 @@ pub use sgx_alloc::System;
 static ALLOC: sgx_alloc::System = sgx_alloc::System;
 
 #[panic_handler]
-fn rust_begin_panic(_info: &PanicInfo<'_>) -> ! {
+fn begin_panic_handler(_info: &PanicInfo<'_>) -> ! {
     sgx_abort();
 }
 
@@ -92,7 +92,9 @@ pub fn rust_oom(layout: Layout) -> ! {
 }
 
 #[link(name = "sgx_trts")]
-extern { pub fn abort() -> !; }
+extern "C" {
+    pub fn abort() -> !;
+}
 
 fn sgx_abort() -> ! {
     unsafe { abort() }
diff --git a/sgx_panic_abort/lib.rs b/sgx_panic_abort/lib.rs
index 26301ad..6078713 100644
--- a/sgx_panic_abort/lib.rs
+++ b/sgx_panic_abort/lib.rs
@@ -14,16 +14,11 @@
 #![feature(staged_api)]
 #![feature(rustc_attrs)]
 
+use core::any::Any;
 
-// Rust's "try" function, but if we're aborting on panics we just call the
-// function as there's nothing else we need to do here.
 #[rustc_std_internal_symbol]
-pub unsafe extern fn __rust_maybe_catch_panic(f: fn(*mut u8),
-                                              data: *mut u8,
-                                              _data_ptr: *mut usize,
-                                              _vtable_ptr: *mut usize) -> u32 {
-    f(data);
-    0
+pub unsafe extern "C" fn __rust_panic_cleanup(_: *mut u8) -> *mut (dyn Any + Send + 'static) {
+    unreachable!()
 }
 
 // "Leak" the payload and shim to the relevant abort on the platform in
@@ -37,11 +32,13 @@ pub unsafe extern fn __rust_maybe_catch_panic(f: fn(*mut u8),
 // will kill us with an illegal instruction, which will do a good enough job for
 // now hopefully.
 #[rustc_std_internal_symbol]
-pub unsafe extern fn __rust_start_panic(_payload: usize) -> u32 {
+pub unsafe extern "C" fn __rust_start_panic(_payload: usize) -> u32 {
     sgx_abort();
 
     #[link(name = "sgx_trts")]
-    extern { pub fn abort() -> !; }
+    extern "C" {
+        pub fn abort() -> !;
+    }
 
     fn sgx_abort() -> ! {
         unsafe { abort() }
@@ -75,6 +72,6 @@ pub unsafe extern fn __rust_start_panic(_payload: usize) -> u32 {
 // binaries, but it should never be called as we don't link in an unwinding
 // runtime at all.
 pub mod personalities {
-    #[no_mangle]
-    pub extern fn rust_eh_personality() {}
+    #[rustc_std_internal_symbol]
+    pub extern "C" fn rust_eh_personality() {}
 }
diff --git a/sgx_panic_unwind/dwarf/eh.rs b/sgx_panic_unwind/dwarf/eh.rs
index 07fa297..302478c 100644
--- a/sgx_panic_unwind/dwarf/eh.rs
+++ b/sgx_panic_unwind/dwarf/eh.rs
@@ -36,8 +36,8 @@ pub const DW_EH_PE_indirect: u8 = 0x80;
 
 #[derive(Copy, Clone)]
 pub struct EHContext<'a> {
-    pub ip: usize, // Current instruction pointer
-    pub func_start: usize, // Address of the current function
+    pub ip: usize,                             // Current instruction pointer
+    pub func_start: usize,                     // Address of the current function
     pub get_text_start: &'a dyn Fn() -> usize, // Get address of the code section
     pub get_data_start: &'a dyn Fn() -> usize, // Get address of the data section
 }
@@ -51,11 +51,13 @@ pub enum EHAction {
 
 pub const USING_SJLJ_EXCEPTIONS: bool = cfg!(all(target_os = "ios", target_arch = "arm"));
 
-pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>)
-    -> Result<EHAction, ()>
-{
+pub unsafe fn find_eh_action(
+    lsda: *const u8,
+    context: &EHContext<'_>,
+    foreign_exception: bool,
+) -> Result<EHAction, ()> {
     if lsda.is_null() {
-        return Ok(EHAction::None)
+        return Ok(EHAction::None);
     }
 
     let func_start = context.func_start;
@@ -93,10 +95,10 @@ pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>)
             }
             if ip < func_start + cs_start + cs_len {
                 if cs_lpad == 0 {
-                    return Ok(EHAction::None)
+                    return Ok(EHAction::None);
                 } else {
                     let lpad = lpad_base + cs_lpad;
-                    return Ok(interpret_cs_action(cs_action, lpad))
+                    return Ok(interpret_cs_action(cs_action, lpad, foreign_exception));
                 }
             }
         }
@@ -121,41 +123,45 @@ pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>)
                 // Can never have null landing pad for sjlj -- that would have
                 // been indicated by a -1 call site index.
                 let lpad = (cs_lpad + 1) as usize;
-                return Ok(interpret_cs_action(cs_action, lpad))
+                return Ok(interpret_cs_action(cs_action, lpad, foreign_exception));
             }
         }
     }
 }
 
-fn interpret_cs_action(cs_action: u64, lpad: usize) -> EHAction {
+fn interpret_cs_action(cs_action: u64, lpad: usize, foreign_exception: bool) -> EHAction {
     if cs_action == 0 {
+        // If cs_action is 0 then this is a cleanup (Drop::drop). We run these
+        // for both Rust panics and foreign exceptions.
         EHAction::Cleanup(lpad)
+    } else if foreign_exception {
+        // catch_unwind should not catch foreign exceptions, only Rust panics.
+        // Instead just continue unwinding.
+        EHAction::None
     } else {
+        // Stop unwinding Rust panics at catch_unwind.
         EHAction::Catch(lpad)
     }
 }
 
 #[inline]
 fn round_up(unrounded: usize, align: usize) -> Result<usize, ()> {
-    if align.is_power_of_two() {
-        Ok((unrounded + align - 1) & !(align - 1))
-    } else {
-        Err(())
-    }
+    if align.is_power_of_two() { Ok((unrounded + align - 1) & !(align - 1)) } else { Err(()) }
 }
 
-unsafe fn read_encoded_pointer(reader: &mut DwarfReader,
-                               context: &EHContext<'_>,
-                               encoding: u8)
-                               -> Result<usize, ()> {
+unsafe fn read_encoded_pointer(
+    reader: &mut DwarfReader,
+    context: &EHContext<'_>,
+    encoding: u8,
+) -> Result<usize, ()> {
     if encoding == DW_EH_PE_omit {
-        return Err(())
+        return Err(());
     }
 
     // DW_EH_PE_aligned implies it's an absolute pointer value
     if encoding == DW_EH_PE_aligned {
         reader.ptr = round_up(reader.ptr as usize, mem::size_of::<usize>())? as *const u8;
-        return Ok(reader.read::<usize>())
+        return Ok(reader.read::<usize>());
     }
 
     let mut result = match encoding & 0x0F {
@@ -177,7 +183,7 @@ unsafe fn read_encoded_pointer(reader: &mut DwarfReader,
         DW_EH_PE_pcrel => reader.ptr as usize,
         DW_EH_PE_funcrel => {
             if context.func_start == 0 {
-                return Err(())
+                return Err(());
             }
             context.func_start
         }
diff --git a/sgx_panic_unwind/dwarf/mod.rs b/sgx_panic_unwind/dwarf/mod.rs
index 6b6b080..e350580 100644
--- a/sgx_panic_unwind/dwarf/mod.rs
+++ b/sgx_panic_unwind/dwarf/mod.rs
@@ -14,7 +14,7 @@ pub struct DwarfReader {
     pub ptr: *const u8,
 }
 
-#[repr(C,packed)]
+#[repr(C, packed)]
 struct Unaligned<T>(T);
 
 impl DwarfReader {
diff --git a/sgx_panic_unwind/gcc.rs b/sgx_panic_unwind/gcc.rs
index d35d674..8eb1d6b 100644
--- a/sgx_panic_unwind/gcc.rs
+++ b/sgx_panic_unwind/gcc.rs
@@ -4,7 +4,7 @@
 //! "Exception Handling in LLVM" (llvm.org/docs/ExceptionHandling.html) and
 //! documents linked from it.
 //! These are also good reads:
-//!     http://mentorembedded.github.io/cxx-abi/abi-eh.html
+//!     https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html
 //!     http://monoinfinito.wordpress.com/series/exception-handling-in-c/
 //!     http://www.airs.com/blog/index.php?s=exception+frames
 //!
@@ -44,18 +44,17 @@
 //! end of the landing pads. `eh_unwind_resume` is used only if
 //! `custom_unwind_resume` flag in the target options is set.
 
-use core::any::Any;
-use core::ptr;
 use alloc::boxed::Box;
+use core::any::Any;
 
-use sgx_unwind as uw;
+use crate::dwarf::eh::{self, EHAction, EHContext};
 use sgx_libc::{c_int, uintptr_t};
-use crate::dwarf::eh::{self, EHContext, EHAction};
+use sgx_unwind as uw;
 
 #[repr(C)]
 struct Exception {
     _uwe: uw::_Unwind_Exception,
-    cause: Option<Box<dyn Any + Send>>,
+    cause: Box<dyn Any + Send>,
 }
 
 pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
@@ -65,28 +64,25 @@ pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
             exception_cleanup,
             private: [0; uw::unwinder_private_data_size],
         },
-        cause: Some(data),
+        cause: data,
     });
     let exception_param = Box::into_raw(exception) as *mut uw::_Unwind_Exception;
     return uw::_Unwind_RaiseException(exception_param) as u32;
 
-    extern "C" fn exception_cleanup(_unwind_code: uw::_Unwind_Reason_Code,
-                                    exception: *mut uw::_Unwind_Exception) {
+    extern "C" fn exception_cleanup(
+        _unwind_code: uw::_Unwind_Reason_Code,
+        exception: *mut uw::_Unwind_Exception,
+    ) {
         unsafe {
             let _: Box<Exception> = Box::from_raw(exception as *mut Exception);
+            super::__rust_drop_panic();
         }
     }
 }
 
-pub fn payload() -> *mut u8 {
-    ptr::null_mut()
-}
-
 pub unsafe fn cleanup(ptr: *mut u8) -> Box<dyn Any + Send> {
-    let my_ep = ptr as *mut Exception;
-    let cause = (*my_ep).cause.take();
-    uw::_Unwind_DeleteException(ptr as *mut _);
-    cause.unwrap()
+    let exception = Box::from_raw(ptr as *mut Exception);
+    exception.cause
 }
 
 // Rust's exception class identifier.  This is used by personality routines to
@@ -96,7 +92,6 @@ fn rust_exception_class() -> uw::_Unwind_Exception_Class {
     0x4d4f5a_00_52555354
 }
 
-
 // Register ids were lifted from LLVM's TargetLowering::getExceptionPointerRegister()
 // and TargetLowering::getExceptionSelectorRegister() for each architecture,
 // then mapped to DWARF register numbers via register definition tables
@@ -113,49 +108,64 @@ const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX
 // https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/libsupc++/eh_personality.cc
 // https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c
 
-// The personality routine for most of our targets
-#[lang = "eh_personality"]
-#[no_mangle]
-#[allow(unused)]
-unsafe extern "C" fn rust_eh_personality(version: c_int,
-                                         actions: uw::_Unwind_Action,
-                                         exception_class: uw::_Unwind_Exception_Class,
-                                         exception_object: *mut uw::_Unwind_Exception,
-                                         context: *mut uw::_Unwind_Context)
-                                         -> uw::_Unwind_Reason_Code {
+unsafe extern "C" fn rust_eh_personality_impl(
+    version: c_int,
+    actions: uw::_Unwind_Action,
+    exception_class: uw::_Unwind_Exception_Class,
+    exception_object: *mut uw::_Unwind_Exception,
+    context: *mut uw::_Unwind_Context)
+-> uw::_Unwind_Reason_Code {
     if version != 1 {
         return uw::_URC_FATAL_PHASE1_ERROR;
     }
-    let eh_action = match find_eh_action(context) {
+    let foreign_exception = exception_class != rust_exception_class();
+    let eh_action = match find_eh_action(context, foreign_exception) {
         Ok(action) => action,
         Err(_) => return uw::_URC_FATAL_PHASE1_ERROR,
     };
     if actions as i32 & uw::_UA_SEARCH_PHASE as i32 != 0 {
         match eh_action {
             EHAction::None |
-            EHAction::Cleanup(_) => return uw::_URC_CONTINUE_UNWIND,
-            EHAction::Catch(_) => return uw::_URC_HANDLER_FOUND,
-            EHAction::Terminate => return uw::_URC_FATAL_PHASE1_ERROR,
+            EHAction::Cleanup(_) => uw::_URC_CONTINUE_UNWIND,
+            EHAction::Catch(_) => uw::_URC_HANDLER_FOUND,
+            EHAction::Terminate => uw::_URC_FATAL_PHASE1_ERROR,
         }
     } else {
         match eh_action {
-            EHAction::None => return uw::_URC_CONTINUE_UNWIND,
+            EHAction::None => uw::_URC_CONTINUE_UNWIND,
             EHAction::Cleanup(lpad) |
             EHAction::Catch(lpad) => {
-                uw::_Unwind_SetGR(context, UNWIND_DATA_REG.0, exception_object as uintptr_t);
+                uw::_Unwind_SetGR(context, UNWIND_DATA_REG.0,
+                    exception_object as uintptr_t);
                 uw::_Unwind_SetGR(context, UNWIND_DATA_REG.1, 0);
                 uw::_Unwind_SetIP(context, lpad);
-                return uw::_URC_INSTALL_CONTEXT;
+                uw::_URC_INSTALL_CONTEXT
             }
-            EHAction::Terminate => return uw::_URC_FATAL_PHASE2_ERROR,
+            EHAction::Terminate => uw::_URC_FATAL_PHASE2_ERROR,
         }
     }
 }
 
+#[lang = "eh_personality"]
+unsafe extern "C" fn rust_eh_personality(
+    version: c_int,
+    actions: uw::_Unwind_Action,
+    exception_class: uw::_Unwind_Exception_Class,
+    exception_object: *mut uw::_Unwind_Exception,
+    context: *mut uw::_Unwind_Context)
+-> uw::_Unwind_Reason_Code {
+    rust_eh_personality_impl(
+        version,
+        actions,
+        exception_class,
+        exception_object,
+        context)
+}
 
-unsafe fn find_eh_action(context: *mut uw::_Unwind_Context)
-    -> Result<EHAction, ()>
-{
+unsafe fn find_eh_action(
+    context: *mut uw::_Unwind_Context,
+    foreign_exception: bool,
+) -> Result<EHAction, ()> {
     let lsda = uw::_Unwind_GetLanguageSpecificData(context) as *const u8;
     let mut ip_before_instr: c_int = 0;
     let ip = uw::_Unwind_GetIPInfo(context, &mut ip_before_instr);
@@ -167,5 +177,5 @@ unsafe fn find_eh_action(context: *mut uw::_Unwind_Context)
         get_text_start: &|| uw::_Unwind_GetTextRelBase(context),
         get_data_start: &|| uw::_Unwind_GetDataRelBase(context),
     };
-    eh::find_eh_action(lsda, &eh_context)
+    eh::find_eh_action(lsda, &eh_context, foreign_exception)
 }
diff --git a/sgx_panic_unwind/lib.rs b/sgx_panic_unwind/lib.rs
index 2166bb6..ecfb931 100644
--- a/sgx_panic_unwind/lib.rs
+++ b/sgx_panic_unwind/lib.rs
@@ -1,20 +1,12 @@
 //! Implementation of panics via stack unwinding
 //!
 //! This crate is an implementation of panics in Rust using "most native" stack
-//! unwinding mechanism of the platform this is being compiled for. This
-//! essentially gets categorized into three buckets currently:
-//!
-//! 1. MSVC targets use SEH in the `seh.rs` file.
-//! 2. The 64-bit MinGW target half-uses SEH and half-use gcc-like information
-//!    in the `seh64_gnu.rs` module.
-//! 3. All other targets use libunwind/libgcc in the `gcc/mod.rs` module.
-//!
-//! More documentation about each implementation can be found in the respective
-//! module.
+//! unwinding mechanism of the platform this is being compiled for.
 
 #![no_std]
-#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))]
 #![unstable(feature = "panic_unwind", issue = "32837")]
+#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))]
+
 #![feature(core_intrinsics)]
 #![feature(lang_items)]
 #![feature(nll)]
@@ -23,53 +15,41 @@
 #![feature(staged_api)]
 #![feature(std_internals)]
 #![feature(unwind_attributes)]
-
+#![feature(abi_thiscall)]
 #![panic_runtime]
 #![feature(panic_runtime)]
+#![feature(rustc_attrs)]
 
 extern crate alloc;
 extern crate sgx_libc;
 extern crate sgx_unwind;
 
 use alloc::boxed::Box;
-use core::intrinsics;
-use core::mem;
-use core::raw;
+use core::any::Any;
 use core::panic::BoxMeUp;
 
-
 #[path = "gcc.rs"]
 mod imp;
+
+extern "C" {
+    /// Handler in libstd called when a panic object is dropped outside of
+    /// `catch_unwind`.
+    fn __rust_drop_panic() -> !;
+}
+
 mod dwarf;
 
-// Entry point for catching an exception, implemented using the `try` intrinsic
-// in the compiler.
-//
-// The interaction between the `payload` function and the compiler is pretty
-// hairy and tightly coupled, for more information see the compiler's
-// implementation of this.
-#[no_mangle]
-pub unsafe extern "C" fn __rust_maybe_catch_panic(f: fn(*mut u8),
-                                                  data: *mut u8,
-                                                  data_ptr: *mut usize,
-                                                  vtable_ptr: *mut usize)
-                                                  -> u32 {
-    let mut payload = imp::payload();
-    if intrinsics::r#try(f, data, &mut payload as *mut _ as *mut _) == 0 {
-        0
-    } else {
-        let obj = mem::transmute::<_, raw::TraitObject>(imp::cleanup(payload));
-        *data_ptr = obj.data as usize;
-        *vtable_ptr = obj.vtable as usize;
-        1
-    }
+#[rustc_std_internal_symbol]
+pub unsafe extern "C" fn __rust_panic_cleanup(payload: *mut u8) -> *mut (dyn Any + Send + 'static) {
+    Box::into_raw(imp::cleanup(payload))
 }
 
 // Entry point for raising an exception, just delegates to the platform-specific
 // implementation.
-#[no_mangle]
+#[rustc_std_internal_symbol]
 #[unwind(allowed)]
 pub unsafe extern "C" fn __rust_start_panic(payload: usize) -> u32 {
     let payload = payload as *mut &mut dyn BoxMeUp;
-    imp::panic(Box::from_raw((*payload).take_box()))
+    let payload = (*payload).take_box();
+    imp::panic(Box::from_raw(payload))
 }
diff --git a/sgx_rand/Cargo.toml b/sgx_rand/Cargo.toml
index efa52e3..b04423e 100644
--- a/sgx_rand/Cargo.toml
+++ b/sgx_rand/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_rand"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_rand/src/chacha.rs b/sgx_rand/src/chacha.rs
index 6d0ccc9..ee3a981 100644
--- a/sgx_rand/src/chacha.rs
+++ b/sgx_rand/src/chacha.rs
@@ -20,7 +20,7 @@
 use std::num::Wrapping as w;
 use crate::{Rng, SeedableRng, Rand, w32};
 
-const KEY_WORDS    : usize =  8; // 8 words for the 256-bit key
+const KEY_WORDS    : usize = 8; // 8 words for the 256-bit key
 const STATE_WORDS  : usize = 16;
 const CHACHA_ROUNDS: u32 = 20; // Cryptographically secure from 8 upwards as of this writing
 
@@ -35,9 +35,9 @@ const CHACHA_ROUNDS: u32 = 20; // Cryptographically secure from 8 upwards as of
 /// Salsa20*](http://cr.yp.to/chacha.html)
 #[derive(Copy, Clone, Debug)]
 pub struct ChaChaRng {
-    buffer:  [w32; STATE_WORDS], // Internal buffer of output
-    state:   [w32; STATE_WORDS], // Initial state
-    index:   usize,                 // Index into state
+    buffer: [w32; STATE_WORDS], // Internal buffer of output
+    state: [w32; STATE_WORDS],  // Initial state
+    index: usize,               // Index into state
 }
 
 static EMPTY: ChaChaRng = ChaChaRng {
diff --git a/sgx_rand/src/lib.rs b/sgx_rand/src/lib.rs
index 6775b77..afd1fd8 100644
--- a/sgx_rand/src/lib.rs
+++ b/sgx_rand/src/lib.rs
@@ -20,7 +20,7 @@
 //! This crate provides similar functionalities as `librand` in Rust
 
 #![cfg_attr(not(target_env = "sgx"), no_std)]
-#![cfg_attr(target_env = "sgx", feature(rustc_private))]
+#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))]
 
 extern crate sgx_types;
 extern crate sgx_trts;
diff --git a/sgx_rand/src/read.rs b/sgx_rand/src/read.rs
index c0a3a05..de513df 100644
--- a/sgx_rand/src/read.rs
+++ b/sgx_rand/src/read.rs
@@ -75,8 +75,10 @@ impl<R: Read> Rng for ReadRng<R> {
 fn fill(r: &mut dyn Read, mut buf: &mut [u8]) -> io::Result<()> {
     while buf.len() > 0 {
         match (r.read(buf))? {
-            0 => return Err(io::Error::new(io::ErrorKind::Other,
-                                           "end of file reached")),
+            0 => return Err(io::Error::new(
+                io::ErrorKind::Other,
+                "end of file reached",
+            )),
             n => buf = &mut mem::replace(&mut buf, &mut [])[n..],
         }
     }
diff --git a/sgx_rand_derive/Cargo.toml b/sgx_rand_derive/Cargo.toml
index 22c6d90..aa077f8 100644
--- a/sgx_rand_derive/Cargo.toml
+++ b/sgx_rand_derive/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_rand_derive"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_serialize/Cargo.toml b/sgx_serialize/Cargo.toml
index 7ae2120..3be836b 100644
--- a/sgx_serialize/Cargo.toml
+++ b/sgx_serialize/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_serialize"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_serialize/src/leb128.rs b/sgx_serialize/src/leb128.rs
index 7f293b5..0c33684 100644
--- a/sgx_serialize/src/leb128.rs
+++ b/sgx_serialize/src/leb128.rs
@@ -32,7 +32,8 @@ fn write_to_vec(vec: &mut Vec<u8>, position: usize, byte: u8) {
 /// The callback function `write` is called once on writing one byte out.
 #[inline]
 pub fn write_unsigned_leb128_to<W>(mut value: u128, mut write: W) -> usize
-    where W: FnMut(usize, u8)
+where
+    W: FnMut(usize, u8),
 {
     let mut position = 0;
     loop {
@@ -86,7 +87,8 @@ pub fn read_unsigned_leb128(data: &[u8], start_position: usize) -> (u128, usize)
 /// The callback function `write` is called once on writing one byte out.
 #[inline]
 pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W) -> usize
-    where W: FnMut(usize, u8)
+where
+    W: FnMut(usize, u8),
 {
     let mut position = 0;
 
diff --git a/sgx_serialize/src/lib.rs b/sgx_serialize/src/lib.rs
index 7a887d1..3aaa9bc 100644
--- a/sgx_serialize/src/lib.rs
+++ b/sgx_serialize/src/lib.rs
@@ -22,7 +22,7 @@ Core encoding and decoding interfaces.
 */
 
 #![cfg_attr(not(target_env = "sgx"), no_std)]
-#![cfg_attr(target_env = "sgx", feature(rustc_private))]
+#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))]
 
 #[cfg(not(target_env = "sgx"))]
 extern crate sgx_tstd as std;
diff --git a/sgx_serialize/src/serialize.rs b/sgx_serialize/src/serialize.rs
index 3255c55..c662d18 100644
--- a/sgx_serialize/src/serialize.rs
+++ b/sgx_serialize/src/serialize.rs
@@ -57,97 +57,173 @@ pub trait Encoder {
 
     // Compound types:
     fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
 
-    fn emit_enum_variant<F>(&mut self, _v_name: &str,
-                            v_id: usize,
-                            _len: usize,
-                            f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+    fn emit_enum_variant<F>(
+        &mut self, _v_name: &str,
+        v_id: usize,
+        _len: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_usize(v_id)?;
         f(self)
     }
-    fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F)
-                                -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    fn emit_enum_variant_arg<F>(
+        &mut self,
+        _a_idx: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
 
-    fn emit_enum_struct_variant<F>(&mut self, v_name: &str,
-                                   v_id: usize,
-                                   len: usize,
-                                   f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+    fn emit_enum_struct_variant<F>(
+        &mut self, v_name: &str,
+        v_id: usize,
+        len: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_enum_variant(v_name, v_id, len, f)
     }
-    fn emit_enum_struct_variant_field<F>(&mut self,
-                                         _f_name: &str,
-                                         f_idx: usize,
-                                         f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+
+    fn emit_enum_struct_variant_field<F>(
+        &mut self,
+        _f_name: &str,
+        f_idx: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_enum_variant_arg(f_idx, f)
     }
 
-    fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F)
-                      -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
-    fn emit_struct_field<F>(&mut self, _f_name: &str, _f_idx: usize, f: F)
-                            -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    fn emit_struct<F>(
+        &mut self,
+        _name: &str,
+        _len: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
+
+    fn emit_struct_field<F>(
+        &mut self,
+        _f_name: &str,
+        _f_idx: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
 
     fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
+
     fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
 
-    fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F)
-                            -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+    fn emit_tuple_struct<F>(
+        &mut self,
+        _name: &str,
+        len: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_tuple(len, f)
     }
-    fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F)
-                                -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+
+    fn emit_tuple_struct_arg<F>(
+        &mut self,
+        f_idx: usize,
+        f: F,
+    ) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_tuple_arg(f_idx, f)
     }
 
     // Specialized types:
     fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_enum("Option", f)
     }
+
     fn emit_option_none(&mut self) -> Result<(), Self::Error> {
         self.emit_enum_variant("None", 0, 0, |_| Ok(()))
     }
+
     fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_enum_variant("Some", 1, 1, f)
     }
 
     fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_usize(len)?;
         f(self)
     }
+
     fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
 
     fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error>
+    where F: FnOnce(&mut Self) -> Result<(), Self::Error>,
     {
         self.emit_usize(len)?;
         f(self)
     }
     fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
+
     fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error>
-        where F: FnOnce(&mut Self) -> Result<(), Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<(), Self::Error>,
+    {
+        f(self)
+    }
 }
 
 pub trait Decoder {
@@ -175,67 +251,123 @@ pub trait Decoder {
 
     // Compound types:
     fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
 
-    fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F)
-                               -> Result<T, Self::Error>
-        where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
+    fn read_enum_variant<T, F>(
+        &mut self,
+        _names: &[&str],
+        mut f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
     {
         let disr = self.read_usize()?;
         f(self, disr)
     }
-    fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F)
-                                   -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
 
-    fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F)
-                                      -> Result<T, Self::Error>
-        where F: FnMut(&mut Self, usize) -> Result<T, Self::Error>
+    fn read_enum_variant_arg<T, F>(
+        &mut self,
+        _a_idx: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
+
+    fn read_enum_struct_variant<T, F>(
+        &mut self,
+        names: &[&str],
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnMut(&mut Self, usize) -> Result<T, Self::Error>,
     {
         self.read_enum_variant(names, f)
     }
-    fn read_enum_struct_variant_field<T, F>(&mut self,
-                                            _f_name: &str,
-                                            f_idx: usize,
-                                            f: F)
-                                            -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error>
+
+    fn read_enum_struct_variant_field<T, F>(
+        &mut self,
+        _f_name: &str,
+        f_idx: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
     {
         self.read_enum_variant_arg(f_idx, f)
     }
 
-    fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F)
-                         -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
-    fn read_struct_field<T, F>(&mut self,
-                               _f_name: &str,
-                               _f_idx: usize,
-                               f: F)
-                               -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
+    fn read_struct<T, F>(
+        &mut self,
+        _s_name: &str,
+        _len: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
+
+    fn read_struct_field<T, F>(
+        &mut self,
+        _f_name: &str,
+        _f_idx: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
 
     fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
-    fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F)
-                            -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
-
-    fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F)
-                               -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
+
+    fn read_tuple_arg<T, F>(
+        &mut self,
+        _a_idx: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
+
+    fn read_tuple_struct<T, F>(
+        &mut self,
+        _s_name: &str,
+        len: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
     {
         self.read_tuple(len, f)
     }
-    fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F)
-                                   -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error>
+
+    fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
     {
         self.read_tuple_arg(a_idx, f)
     }
 
     // Specialized types:
     fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error>
-        where F: FnMut(&mut Self, bool) -> Result<T, Self::Error>
+    where
+        F: FnMut(&mut Self, bool) -> Result<T, Self::Error>,
     {
         self.read_enum("Option", move |this| {
             this.read_enum_variant(&["None", "Some"], move |this, idx| {
@@ -249,26 +381,49 @@ pub trait Decoder {
     }
 
     fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
     {
         let len = self.read_usize()?;
         f(self, len)
     }
+
     fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
 
     fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>,
     {
         let len = self.read_usize()?;
         f(self, len)
     }
-    fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F)
-                              -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
-    fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F)
-                              -> Result<T, Self::Error>
-        where F: FnOnce(&mut Self) -> Result<T, Self::Error> { f(self) }
+
+    fn read_map_elt_key<T, F>(
+        &mut self,
+        _idx: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
+
+    fn read_map_elt_val<T, F>(
+        &mut self,
+        _idx: usize,
+        f: F,
+    ) -> Result<T, Self::Error>
+    where
+        F: FnOnce(&mut Self) -> Result<T, Self::Error>,
+    {
+        f(self)
+    }
 
     // Failure
     fn error(&mut self, err: &str) -> Self::Error;
@@ -282,7 +437,6 @@ pub trait Serializable {
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error>;
 }
 
-
 impl Serializable for usize {
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
         s.emit_usize(*self)
@@ -579,7 +733,8 @@ impl<T:DeSerializable> DeSerializable for Vec<T> {
 }
 
 impl<'a, T:Serializable> Serializable for Cow<'a, [T]>
-where [T]: ToOwned<Owned = Vec<T>>
+where
+    [T]: ToOwned<Owned = Vec<T>>,
 {
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
         s.emit_seq(self.len(), |s| {
@@ -592,7 +747,8 @@ where [T]: ToOwned<Owned = Vec<T>>
 }
 
 impl<T:DeSerializable+ToOwned> DeSerializable for Cow<'static, [T]>
-where [T]: ToOwned<Owned = Vec<T>>
+where
+    [T]: ToOwned<Owned = Vec<T>>,
 {
     fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> {
         d.read_seq(|d, len| {
@@ -881,8 +1037,9 @@ impl<T: DeSerializable + Ord> DeSerializable for BTreeSet<T> {
 }
 
 impl<K, V> Serializable for HashMap<K, V>
-    where K: Serializable + Hash + Eq,
-          V: Serializable,
+where
+    K: Serializable + Hash + Eq,
+    V: Serializable,
 {
     fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> {
         e.emit_map(self.len(), |e| {
@@ -898,8 +1055,9 @@ impl<K, V> Serializable for HashMap<K, V>
 }
 
 impl<K, V> DeSerializable for HashMap<K, V>
-    where K: DeSerializable + Hash + Eq,
-          V: DeSerializable,
+where
+    K: DeSerializable + Hash + Eq,
+    V: DeSerializable,
 {
     fn decode<D: Decoder>(d: &mut D) -> Result<HashMap<K, V>, D::Error> {
         d.read_map(|d, len| {
@@ -914,7 +1072,10 @@ impl<K, V> DeSerializable for HashMap<K, V>
     }
 }
 
-impl<T> Serializable for HashSet<T> where T: Serializable + Hash + Eq {
+impl<T> Serializable for HashSet<T>
+where
+    T: Serializable + Hash + Eq,
+{
     fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> {
         s.emit_seq(self.len(), |s| {
             let mut i = 0;
@@ -927,7 +1088,10 @@ impl<T> Serializable for HashSet<T> where T: Serializable + Hash + Eq {
     }
 }
 
-impl<T> DeSerializable for HashSet<T> where T: DeSerializable + Hash + Eq, {
+impl<T> DeSerializable for HashSet<T>
+where
+    T: DeSerializable + Hash + Eq,
+{
     fn decode<D: Decoder>(d: &mut D) -> Result<HashSet<T>, D::Error> {
         d.read_seq(|d, len| {
             let mut set = HashSet::with_capacity(cap_capacity::<T>(len));
@@ -1048,4 +1212,4 @@ impl<'a, T: 'a + ?Sized + DeSerializable> DeSerializeHelper<'a, T> {
             Result::Ok(d) => Option::Some(d),
         }
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_serialize_derive/Cargo.toml b/sgx_serialize_derive/Cargo.toml
index e765162..e18b77a 100644
--- a/sgx_serialize_derive/Cargo.toml
+++ b/sgx_serialize_derive/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_serialize_derive"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_serialize_derive_internals/Cargo.toml b/sgx_serialize_derive_internals/Cargo.toml
index dd75733..75abc68 100644
--- a/sgx_serialize_derive_internals/Cargo.toml
+++ b/sgx_serialize_derive_internals/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_serialize_derive_internals"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_rand/Cargo.toml b/sgx_signal/Cargo.toml
similarity index 84%
copy from sgx_rand/Cargo.toml
copy to sgx_signal/Cargo.toml
index efa52e3..3d9b89b 100644
--- a/sgx_rand/Cargo.toml
+++ b/sgx_signal/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
-name = "sgx_rand"
-version = "1.1.1"
+name = "sgx_signal"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
@@ -9,14 +9,14 @@ description = "Rust SGX SDK provides the ability to write Intel SGX applications
 edition = "2018"
 
 [lib]
-name = "sgx_rand"
+name = "sgx_signal"
 crate-type = ["rlib"]
 
 [features]
 default = []
 
 [target.'cfg(not(target_env = "sgx"))'.dependencies]
+sgx_tstd = { path = "../sgx_tstd" }
 sgx_types = { path = "../sgx_types" }
+sgx_libc = { path = "../sgx_libc" }
 sgx_trts = { path = "../sgx_trts" }
-sgx_tstd = { path = "../sgx_tstd" }
-
diff --git a/sgx_signal/src/exception.rs b/sgx_signal/src/exception.rs
new file mode 100644
index 0000000..54e562a
--- /dev/null
+++ b/sgx_signal/src/exception.rs
@@ -0,0 +1,260 @@
+// 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..
+
+use std::sync::{Arc, SgxThreadMutex, SgxRwLock, Once, ONCE_INIT};
+use std::collections::LinkedList;
+use std::num::NonZeroU64;
+use std::u64;
+use std::ops::Drop;
+use sgx_types::{EXCEPTION_CONTINUE_SEARCH, EXCEPTION_CONTINUE_EXECUTION};
+use sgx_types::{sgx_exception_info_t, sgx_exception_vector_t};
+use sgx_types::SE_WORDSIZE;
+use sgx_libc::int32_t;
+use sgx_trts::veh::{
+    rsgx_register_exception_handler,
+    rsgx_unregister_exception_handler,
+    exception_handle
+};
+
+pub enum ContinueType {
+    Search,
+    Execution,
+}
+
+impl Into<i32> for ContinueType {
+    fn into(self) -> i32 {
+        match self {
+            ContinueType::Search => EXCEPTION_CONTINUE_SEARCH,
+            ContinueType::Execution => EXCEPTION_CONTINUE_EXECUTION,
+        }
+    }
+}
+
+#[allow(unknown_lints, bare_trait_objects)]
+type ExceptionHandler = Fn(&mut sgx_exception_info_t) -> ContinueType + Send + Sync;
+
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
+pub struct HandlerId(NonZeroU64);
+
+impl HandlerId {
+    fn new() -> HandlerId {
+        static GUARD: SgxThreadMutex = SgxThreadMutex::new();
+        static mut COUNTER: u64 = 1;
+
+        unsafe {
+            let _guard = GUARD.lock();
+            if COUNTER == u64::MAX {
+                panic!("failed to generate unique HandlerId : bitspace exhausted");
+            }
+            let id = COUNTER;
+            COUNTER += 1;
+            let _ = GUARD.unlock();
+            HandlerId(NonZeroU64::new(id).unwrap())
+        }
+    }
+}
+
+struct HandlerNode {
+    id: HandlerId,
+    handler: Arc<ExceptionHandler>,
+}
+
+impl HandlerNode {
+    // add code here
+    pub fn new(id: HandlerId, handler: Arc<ExceptionHandler>) -> Self {
+        HandlerNode {
+            id,
+            handler,
+        }
+    }
+    pub fn get_handler_id(&self) -> HandlerId {
+        self.id
+    }
+}
+
+struct ExceptionManager {
+    exception_handler: SgxRwLock<LinkedList<HandlerNode>>,
+    native_handle: Option<exception_handle>,
+}
+
+static mut GLOBAL_DATA: Option<GlobalData> = None;
+
+#[allow(deprecated)]
+static GLOBAL_INIT: Once = ONCE_INIT;
+struct GlobalData {
+    manager: ExceptionManager,
+}
+
+impl GlobalData {
+    fn get() -> &'static Self {
+        unsafe { GLOBAL_DATA.as_ref().unwrap() }
+    }
+    fn ensure() -> &'static Self {
+        GLOBAL_INIT.call_once(|| unsafe {
+            GLOBAL_DATA = Some(GlobalData {
+                manager: ExceptionManager::new(),
+            });
+        });
+        Self::get()
+    }
+}
+
+extern "C" fn native_exception_handler(info : *mut sgx_exception_info_t) -> int32_t {
+    if let Ok(handlers) = GlobalData::get().manager.exception_handler.read() {
+        let info = unsafe { info.as_mut().unwrap() };
+        for h in handlers.iter() {
+            match (h.handler)(info) {
+                ContinueType::Search => {},
+                ContinueType::Execution => return EXCEPTION_CONTINUE_EXECUTION,
+            }
+        }
+    }
+    unsafe { panic_handler(info).into() }
+}
+
+unsafe extern "C" fn panic_handler(info : *mut sgx_exception_info_t) -> ContinueType {
+    let exception_info = info.as_mut().unwrap();
+    let mut rsp = exception_info.cpu_context.rsp;
+    if rsp & 0xF == 0 {
+        rsp -= SE_WORDSIZE as u64;
+        exception_info.cpu_context.rsp = rsp;
+        let addr = rsp as * mut u64;
+        *addr = exception_info.cpu_context.rip;
+    } else {
+
+    }
+
+    exception_info.cpu_context.rdi = exception_info.exception_vector as u32 as u64;
+    exception_info.cpu_context.rsi = exception_info.cpu_context.rip;
+    exception_info.cpu_context.rip = exception_panic as u64;
+
+    ContinueType::Execution
+}
+
+#[no_mangle]
+#[inline(never)]
+unsafe extern "C" fn exception_panic(vector: sgx_exception_vector_t, rip: usize) {
+    let exception = match vector {
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_DE => "#DE",
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_DB => "#DB",
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_BP => "#BP",
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_BR => "#BR",
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_UD => "#UD",
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_MF => "#MF",
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_AC => "#AC",
+        sgx_exception_vector_t::SGX_EXCEPTION_VECTOR_XM => "#XM",
+    };
+    panic!("enclave exception: {}, at rip: 0x{:x}", exception, rip);
+}
+
+impl ExceptionManager {
+    // add code here
+    pub fn new() -> Self {
+        ExceptionManager {
+            exception_handler: SgxRwLock::new(LinkedList::new()),
+            native_handle: rsgx_register_exception_handler(0, native_exception_handler),
+        }
+    }
+}
+
+#[allow(dead_code)]
+impl Drop for ExceptionManager {
+    fn drop(&mut self) {
+        if let Some(handler) = self.native_handle {
+            rsgx_unregister_exception_handler(handler);
+            self.native_handle = None;
+            if let Ok(ref mut handlers) = self.exception_handler.write() {
+                handlers.clear();
+            }
+        }
+    }
+}
+
+fn register_exception_impl<F>(is_first_handler: bool, handler: F) -> Option<HandlerId>
+where
+    F: Fn(&mut sgx_exception_info_t) -> ContinueType + Sync + Send + 'static,
+{
+    let globals = GlobalData::ensure();
+
+    if let Ok(ref mut handlers) = globals.manager.exception_handler.write() {
+        let handler_id = HandlerId::new();
+        if is_first_handler {
+            handlers.push_front(HandlerNode::new(handler_id, Arc::from(handler)));
+        } else {
+            handlers.push_back(HandlerNode::new(handler_id, Arc::from(handler)));
+        }
+        Some(handler_id)
+    } else {
+        None
+    }
+}
+
+///
+/// The register_exception function allows developers to register an exception handler,
+/// and specify whether to prepend (when is_first is true) or append the handler to the handler chain.
+///
+/// # Description
+///
+/// The Rust SGX SDK supports the registration of custom exception handler
+/// functions. You can write your own code to handle a limited set of hardware
+/// exceptions.
+///
+/// # Note
+///
+/// 1. OCALLs are not allowed in the exception handler.
+/// 2. Custom exception handing only saves general purpose registers in sgx_exception_info_t. You should be careful when touching other registers inthe exception handlers.
+///
+pub fn register_exception<F>(is_first: bool, handler: F) -> Option<HandlerId>
+where
+    F: Fn(&mut sgx_exception_info_t) -> ContinueType + Sync + Send + 'static,
+{
+    register_exception_impl(is_first, handler)
+}
+
+///
+/// The register function allows developers to register an exception handler.
+///
+/// # Description
+///
+/// The Rust SGX SDK supports the registration of custom exception handler
+/// functions. You can write your own code to handle a limited set of hardware
+/// exceptions.
+///
+/// # Note
+///
+/// 1. OCALLs are not allowed in the exception handler.
+/// 2. Custom exception handing only saves general purpose registers in sgx_exception_info_t. You should be careful when touching other registers inthe exception handlers.
+///
+pub fn register<F>(handler: F) -> Option<HandlerId>
+where
+    F: Fn(&mut sgx_exception_info_t) -> ContinueType + Sync + Send + 'static,
+{
+    register_exception_impl(true, handler)
+}
+
+pub fn unregister(id: HandlerId) -> bool {
+    let globals = GlobalData::ensure();
+    if let Ok(ref mut handlers) = globals.manager.exception_handler.write() {
+        handlers.drain_filter(|n| {
+            n.get_handler_id() == id
+        })
+        .next()
+        .is_some()
+    } else {
+        false
+    }
+}
diff --git a/sgx_serialize/src/lib.rs b/sgx_signal/src/lib.rs
similarity index 75%
copy from sgx_serialize/src/lib.rs
copy to sgx_signal/src/lib.rs
index 7a887d1..8cf5c8a 100644
--- a/sgx_serialize/src/lib.rs
+++ b/sgx_signal/src/lib.rs
@@ -15,21 +15,23 @@
 // specific language governing permissions and limitations
 // under the License..
 
-//! Support code for encoding and decoding types.
-
-/*
-Core encoding and decoding interfaces.
-*/
-
 #![cfg_attr(not(target_env = "sgx"), no_std)]
-#![cfg_attr(target_env = "sgx", feature(rustc_private))]
+#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))]
+
+#![feature(drain_filter)]
 
 #[cfg(not(target_env = "sgx"))]
+#[macro_use]
 extern crate sgx_tstd as std;
 
-mod serialize;
-pub use self::serialize::{Decoder, Encoder, DeSerializable, Serializable, SerializeHelper, DeSerializeHelper};
+extern crate sgx_types;
+extern crate sgx_trts;
+extern crate sgx_libc;
+
+pub mod signal;
+pub use self::signal::*;
 
-mod opaque;
-mod leb128;
+pub mod exception;
+pub use self::exception::*;
 
+mod manager;
diff --git a/sgx_signal/src/manager.rs b/sgx_signal/src/manager.rs
new file mode 100644
index 0000000..811a51d
--- /dev/null
+++ b/sgx_signal/src/manager.rs
@@ -0,0 +1,320 @@
+// 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..
+#[allow(deprecated)]
+use std::sync::{SgxThreadMutex, SgxMutex};
+use std::sync::Arc;
+use std::collections::{HashSet, HashMap, BTreeMap};
+use std::cell::Cell;
+use std::mem;
+use std::num::NonZeroU64;
+use std::u64;
+use sgx_libc::{c_int, c_void};
+use sgx_libc::{SA_SIGINFO, SIGRTMAX, NSIG};
+use sgx_libc::{siginfo_t, sigset_t, sigemptyset,
+               sigaction, sigfillset, sigismember,
+               sigaddset, sigdelset};
+
+thread_local! { static SIGNAL_MASK: Cell<SigSet> = Cell::new(SigSet::new()) }
+
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
+pub struct SigNum(i32);
+
+impl SigNum {
+    // add code here
+    pub fn from_raw(signo: i32) -> Option<SigNum> {
+        if signo <= 0 || signo >= NSIG {
+            None
+        } else {
+            Some(SigNum(signo))
+        }
+    }
+
+    pub unsafe fn from_raw_uncheck(signo: i32) -> SigNum {
+        SigNum(signo)
+    }
+
+    pub fn raw(&self) -> i32 { self.0 }
+}
+#[derive(Copy, Clone)]
+pub struct SigSet(sigset_t);
+
+impl SigSet {
+    // add code here
+    pub fn new() -> SigSet {
+        let set = unsafe {
+            let mut set: sigset_t = mem::zeroed();
+            sigemptyset(&mut set as *mut sigset_t);
+            set
+        };
+        SigSet(set)
+    }
+    #[allow(dead_code)]
+    pub fn empty(&mut self) {
+        unsafe { sigemptyset(&mut self.0 as *mut sigset_t); }
+    }
+
+    pub fn add(&mut self, signo: SigNum) -> bool {
+        unsafe { sigaddset(&mut self.0 as *mut sigset_t, signo.raw()) == 0 }
+    }
+
+    pub fn delete(&mut self, signo: SigNum) -> bool {
+        unsafe { sigdelset(&mut self.0 as *mut sigset_t, signo.raw()) == 0 }
+    }
+
+    pub fn fill(&mut self) {
+        unsafe { sigfillset(&mut self.0 as *mut sigset_t); }
+    }
+
+    pub fn is_member(&self, signo: SigNum) -> bool {
+        unsafe { sigismember(&self.0 as *const sigset_t, signo.raw()) == 1 }
+    }
+
+    pub fn complement(&self) -> SigSet {
+        let mut set = SigSet::new();
+        for num in 0..=SIGRTMAX {
+            let signo = unsafe { SigNum::from_raw_uncheck(num) };
+            if !self.is_member(signo) {
+                set.add(signo);
+            }
+        }
+        set
+    }
+
+    pub unsafe fn from_raw(set: sigset_t) -> SigSet {
+        SigSet(set)
+    }
+
+    pub fn raw(&self) -> sigset_t {
+        self.0
+    }
+}
+
+pub fn block(set: &SigSet) {
+    let mut old_mask = get_block_mask();
+    for num in 0..SIGRTMAX {
+        let signo = unsafe { SigNum::from_raw_uncheck(num)};
+        if set.is_member(signo) {
+            old_mask.add(signo);
+        }
+    }
+    set_block_mask(old_mask);
+}
+
+pub fn unblock(set: &SigSet) {
+    let mut old_mask = get_block_mask();
+    for num in 0..=SIGRTMAX {
+        let signo = unsafe { SigNum::from_raw_uncheck(num) };
+        if set.is_member(signo) {
+            old_mask.delete(signo);
+        }
+    }
+    set_block_mask(old_mask);
+}
+
+#[inline]
+pub fn get_block_mask() -> SigSet {
+    SIGNAL_MASK.with(|s|s.get())
+}
+
+#[inline]
+pub fn set_block_mask(set: SigSet) {
+    SIGNAL_MASK.with(|s|s.set(set));
+}
+
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
+pub struct ActionId(NonZeroU64);
+
+impl ActionId {
+    fn new() -> Self {
+        static GUARD: SgxThreadMutex = SgxThreadMutex::new();
+        static mut COUNTER: u64 = 1;
+
+        unsafe {
+            let _guard = GUARD.lock();
+            if COUNTER == u64::MAX {
+                panic!("failed to generate unique ActionId : bitspace exhausted");
+            }
+            let id = COUNTER;
+            COUNTER += 1;
+            let _ = GUARD.unlock();
+            ActionId(NonZeroU64::new(id).unwrap())
+        }
+    }
+}
+
+pub type Action = dyn Fn(&siginfo_t) + Send + Sync;
+
+#[derive(Clone)]
+pub struct ActionSlot {
+    cur: sigaction,
+    actions: BTreeMap<ActionId, Arc<Action>>,
+}
+
+impl ActionSlot {
+    pub fn new(cur: &sigaction) -> Self {
+        ActionSlot {
+            cur: *cur,
+            actions: BTreeMap::new(),
+        }
+    }
+    pub fn set(&mut self, action: Arc<Action>) -> ActionId {
+        let id = ActionId::new();
+        self.actions.insert(id, action);
+        id
+    }
+    pub fn remove(&mut self, id: ActionId) -> bool {
+        self.actions.remove(&id).is_some()
+    }
+    pub fn get_act(&self) -> sigaction {
+        self.cur
+    }
+}
+
+pub struct SignalManager {
+    action_set: SgxMutex<HashMap<SigNum, ActionSlot>>,
+    reset_set: SgxMutex<HashSet<SigNum>>,
+}
+
+impl SignalManager {
+    // add code here
+    pub fn new() -> Self {
+        SignalManager {
+            action_set: SgxMutex::new(HashMap::new()),
+            reset_set: SgxMutex::new(HashSet::new()),
+        }
+    }
+
+    pub fn set_action(&self, signo: SigNum, act: &sigaction) {
+        self.action_set
+        .lock()
+        .unwrap()
+        .insert(signo, ActionSlot::new(act));
+    }
+
+    pub fn set_action_impl<F>(&self, signo: SigNum, act: &sigaction, action: Arc<F>) -> ActionId
+    where
+        F: Fn(&siginfo_t) + Sync + Send + 'static,
+    {
+        let action_id = if !self.action_set
+                                .lock()
+                                .unwrap()
+                                .contains_key(&signo) {
+            let mut slot = ActionSlot::new(act);
+            let id = slot.set(action);
+            self.action_set
+                .lock()
+                .unwrap()
+                .insert(signo, slot);
+            id
+        } else {
+            self.action_set
+                .lock()
+                .unwrap()
+                .get_mut(&signo)
+                .map(|slot|slot.set(action)).unwrap()
+        };
+        action_id
+    }
+
+    pub fn get_action(&self, signo: SigNum) -> Option<ActionSlot> {
+        if let Some(slot) = self.action_set
+            .lock()
+            .unwrap()
+            .get(&signo) {
+            Some(slot.clone())
+        } else {
+            None
+        }
+    }
+
+    pub fn remove_action(&self, signo: SigNum, id: ActionId)  -> bool {
+        if let Some(ref mut slot) = self.action_set
+            .lock()
+            .unwrap()
+            .get_mut(&signo) {
+            slot.remove(id)
+        } else {
+            false
+        }
+    }
+
+    pub fn clear_action(&self, signo: SigNum) -> bool {
+        self.action_set
+            .lock()
+            .unwrap()
+            .remove(&signo)
+            .is_some()
+    }
+
+    pub fn is_action_empty(&self) -> bool {
+        self.action_set
+            .lock()
+            .unwrap()
+            .is_empty()
+    }
+
+    pub fn set_reset_on_handle(&self, signo: SigNum) {
+        self.reset_set
+            .lock()
+            .unwrap()
+            .insert(signo);
+    }
+
+    pub fn is_reset_on_handle(&self, signo: SigNum) -> bool {
+        self.reset_set
+            .lock()
+            .unwrap()
+            .contains(&signo)
+    }
+
+    pub unsafe fn handler(&self, signum: i32, info: *const siginfo_t, context: *const c_void) {
+        type FnSaSigaction = extern "C" fn(c_int, *const siginfo_t, *const c_void);
+        type FnSaHandler = extern "C" fn(c_int);
+
+        let signo = match SigNum::from_raw(signum) {
+            Some(signo) => signo,
+            None => return,
+        };
+
+        let action_slot = match self.get_action(signo) {
+            Some(slot) => slot,
+            None => return,
+        };
+        let act = action_slot.get_act();
+
+        if self.is_reset_on_handle(signo) {
+            self.clear_action(signo);
+        }
+
+        let old_mask = get_block_mask();
+        block(&SigSet::from_raw(act.sa_mask));
+        let is_siginfo: bool = (act.sa_flags & SA_SIGINFO) != 0;
+        if is_siginfo && (act.sa_sigaction != 0) {
+            let fn_sa_sigaction = mem::transmute::<*const(), FnSaSigaction>(act.sa_sigaction as *const());
+            fn_sa_sigaction(signo.raw(), info, context);
+        } else if !is_siginfo && (act.sa_sigaction != 0) {
+            let fn_sa_handler = mem::transmute::<*const(), FnSaHandler>(act.sa_sigaction as *const());
+            fn_sa_handler(signo.raw());
+        }
+
+        let info = info.as_ref().unwrap();
+        for action in action_slot.actions.values() {
+            action(info);
+        }
+        set_block_mask(old_mask);
+    }
+}
diff --git a/sgx_signal/src/signal.rs b/sgx_signal/src/signal.rs
new file mode 100644
index 0000000..3ebdd5e
--- /dev/null
+++ b/sgx_signal/src/signal.rs
@@ -0,0 +1,366 @@
+// 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..
+
+use std::enclave::get_enclave_id;
+use std::sync::{Once, Arc, SgxMutex};
+use std::rt::*;
+use std::mem;
+use std::io::Error;
+use sgx_libc::set_errno;
+use sgx_libc::{EINVAL, ESGX};
+use sgx_libc::{sighandler_t, sigset_t, siginfo_t, sigemptyset, sigaction};
+use sgx_libc::{
+    SIGSTOP, SIGKILL, SIGILL, SIGSEGV, SIGFPE, SIGBUS,
+    SIGTRAP, SIG_DFL, SIG_ERR, SIG_BLOCK, SIG_UNBLOCK,
+    SIG_SETMASK, SA_RESETHAND
+};
+use sgx_libc::ocall::{sigaction, sigprocmask, raise};
+use sgx_types::{c_int, c_void, sgx_status_t, sgx_enclave_id_t, SysResult};
+use crate::manager::{self, ActionId, SignalManager, SigNum, SigSet};
+
+pub const FORBIDDEN: &[c_int] = FORBIDDEN_IMPL;
+const FORBIDDEN_IMPL: &[c_int] = &[SIGKILL,
+                                   SIGSTOP,
+                                   SIGILL,
+                                   SIGFPE,
+                                   SIGSEGV,
+                                   SIGBUS,
+                                   SIGTRAP];
+
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
+pub struct SignalId {
+    signal: SigNum,
+    action: ActionId,
+}
+
+struct GlobalData {
+   signal_manager: SignalManager,
+   signal_action_lock: SgxMutex<()>,
+}
+
+static mut GLOBAL_DATA: Option<GlobalData> = None;
+static MANAGER_INIT: Once = Once::new();
+
+extern "C" {
+    pub fn u_signal_clear_ocall(enclave_id: sgx_enclave_id_t) -> sgx_status_t;
+}
+
+impl GlobalData {
+    // add code here
+    fn get() -> &'static Self {
+        unsafe { GLOBAL_DATA.as_ref().unwrap() }
+    }
+
+    fn ensure() -> &'static Self {
+        MANAGER_INIT.call_once(|| unsafe {
+            GLOBAL_DATA = Some(GlobalData {
+                signal_manager: SignalManager::new(),
+                signal_action_lock: SgxMutex::new(()),
+            });
+
+            let _r = at_exit(|| Self::clear() );
+        });
+        Self::get()
+    }
+
+    fn clear() {
+        if !Self::get().signal_manager.is_action_empty() {
+            //ocall
+            unsafe { u_signal_clear_ocall(get_enclave_id()) };
+        }
+    }
+}
+
+#[no_mangle]
+pub extern "C" fn t_signal_handler_ecall(info: *const siginfo_t) -> c_int {
+    if info.is_null() {
+        return -1;
+    }
+    let si_info = unsafe { &*(info) };
+    let global = GlobalData::get();
+    let mask = manager::get_block_mask();
+    // If the signal is blocked and still passed into the enclave. The signal
+    // masks inside the enclave is out of sync with the untrusted signal mask.
+    unsafe {
+        let signo = SigNum::from_raw_uncheck(si_info.si_signo);
+        if mask.is_member(signo) {
+           -1
+        } else {
+            global.signal_manager.handler(
+                si_info.si_signo,
+                info as *const siginfo_t,
+                0 as *const c_void);
+            0
+        }
+    }
+}
+
+fn native_sigaction(signo: SigNum, act: &sigaction, oldact: &mut sigaction) -> c_int {
+    let global = GlobalData::ensure();
+    let mut mask = SigSet::new();
+    let old_mask = SigSet::new();
+
+    mask.fill();
+
+    // Guards sigaction calls. This is to ensure that signal handlers are not
+    // overwritten between the time sigaction gets |oldact| and sets |act|.
+    {
+        let _guard = global.signal_action_lock.lock();
+        if let Some(t) = global.signal_manager.get_action(signo) {
+            *oldact = t.get_act();
+        } else {
+            oldact.sa_sigaction = SIG_DFL;
+        }
+
+        rsgx_sigprocmask(SIG_SETMASK, &mask.raw(), &mut old_mask.raw());
+        global.signal_manager.set_action(signo, act);
+        rsgx_sigprocmask(SIG_SETMASK, &old_mask.raw(), &mut mask.raw());
+    }
+
+    let new_act = sigaction {
+        sa_sigaction: 0,
+        sa_mask: act.sa_mask,
+        sa_flags: act.sa_flags,
+        sa_restorer: None,
+    };
+    if (new_act.sa_flags & SA_RESETHAND) != 0 {
+        global.signal_manager.set_reset_on_handle(signo);
+    }
+
+    unsafe {
+        sigaction(
+            signo.raw(),
+            &new_act,
+            oldact as *mut sigaction,
+            get_enclave_id(),
+        )
+    }
+}
+
+fn native_sigaction_impl<F>(
+    signo: SigNum,
+    act: &sigaction,
+    oldact: &mut sigaction,
+    f: Arc<F>,
+) -> SysResult<ActionId>
+where
+    F: Fn(&siginfo_t) + Sync + Send + 'static,
+{
+    let global = GlobalData::ensure();
+    let mut mask = SigSet::new();
+    let old_mask = SigSet::new();
+
+    mask.fill();
+
+    // Guards sigaction calls. This is to ensure that signal handlers are not
+    // overwritten between the time sigaction gets |oldact| and sets |act|.
+    let (exist, action_id) = {
+        let _guard = global.signal_action_lock.lock();
+        let exist = if let Some(t) = global.signal_manager.get_action(signo) {
+            *oldact = t.get_act();
+            true
+        } else {
+            oldact.sa_sigaction = SIG_DFL;
+            false
+        };
+
+        rsgx_sigprocmask(SIG_SETMASK, &mask.raw(), &mut old_mask.raw());
+        let action_id = global.signal_manager.set_action_impl(signo, act, f);
+        rsgx_sigprocmask(SIG_SETMASK, &old_mask.raw(), &mut mask.raw());
+        (exist, action_id)
+    };
+
+    if exist {
+        return Ok(action_id);
+    }
+
+    let new_act = sigaction {
+        sa_sigaction: 0,
+        sa_mask: act.sa_mask,
+        sa_flags: act.sa_flags,
+        sa_restorer: None,
+    };
+    if (new_act.sa_flags & SA_RESETHAND) != 0 {
+        global.signal_manager.set_reset_on_handle(signo);
+    }
+
+    let result = unsafe {
+        sigaction(
+            signo.raw(),
+            &new_act,
+            oldact as *mut sigaction,
+            get_enclave_id(),
+        )
+    };
+    if result == 0 {
+        Ok(action_id)
+    } else {
+        Err(result)
+    }
+}
+
+pub fn rsgx_sigaction(signum: c_int, act: &sigaction, oldact: &mut sigaction) -> c_int {
+    if FORBIDDEN.contains(&signum) {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let eid = get_enclave_id();
+    if eid == 0 {
+        set_errno(ESGX);
+        return -1;
+    }
+
+    let signo = match SigNum::from_raw(signum) {
+        Some(signo) => signo,
+        None => {
+            set_errno(EINVAL);
+            return -1;
+        }
+    };
+    native_sigaction(signo, act, oldact)
+}
+
+pub fn rsgx_signal(signum: c_int, handler: sighandler_t) -> sighandler_t {
+    let mut act: sigaction = unsafe { mem::zeroed() };
+    let mut oldact: sigaction = unsafe { mem::zeroed() };
+    act.sa_sigaction = handler;
+    unsafe { sigemptyset(&mut act.sa_mask as *mut sigset_t) };
+    if rsgx_sigaction(signum, &act, &mut oldact) != 0  {
+        // Errno is set by sigaction.
+        return SIG_ERR;
+    }
+    oldact.sa_sigaction
+}
+
+pub fn rsgx_sigprocmask(how: c_int, set: &sigset_t, oldset: &mut sigset_t) -> c_int {
+    if how != SIG_BLOCK && how != SIG_UNBLOCK && how != SIG_SETMASK {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let mut signals_to_block = SigSet::new();
+    let mut signals_to_unblock = SigSet::new();
+
+    *oldset = manager::get_block_mask().raw();
+    let newset = unsafe { SigSet::from_raw(*set) };
+
+    if how == SIG_BLOCK || how == SIG_SETMASK {
+        signals_to_block = newset;
+    }
+    if how == SIG_UNBLOCK {
+        signals_to_unblock = newset;
+    } else if how == SIG_SETMASK {
+        signals_to_unblock = newset.complement();
+    }
+    // Unblock signals inside the enclave before unblocking signals on the host.
+    // |oldset| is already filled with the signal mask inside the enclave.
+    manager::unblock(&signals_to_unblock);
+    let result = unsafe {
+        sigprocmask(
+            how,
+            set as *const sigset_t,
+            0 as *mut sigset_t,
+        )
+    };
+    // Block signals inside the enclave after the host.
+    manager::block(&signals_to_block);
+    result
+}
+
+pub fn rsgx_raise(signum: c_int) -> c_int {
+    unsafe { raise(signum) }
+}
+
+pub fn register<F>(signal: c_int, action: F) -> Result<SignalId, Error>
+where
+    F: Fn() + Sync + Send + 'static,
+{
+    register_sigaction_impl(signal, move |_: &_| action())
+}
+
+pub fn register_sigaction<F>(signal: c_int, action: F) -> Result<SignalId, Error>
+where
+    F: Fn(&siginfo_t) + Sync + Send + 'static,
+{
+    register_sigaction_impl(signal, action)
+}
+
+fn register_sigaction_impl<F>(signal: c_int, action: F) -> Result<SignalId, Error>
+where
+    F: Fn(&siginfo_t) + Sync + Send + 'static,
+{
+    register_impl(signal, action)
+}
+
+fn register_impl<F>(signal: c_int, action: F) -> Result<SignalId, Error>
+where
+    F: Fn(&siginfo_t) + Sync + Send + 'static,
+{
+    if FORBIDDEN.contains(&signal) {
+        set_errno(EINVAL);
+        return Err(Error::from_raw_os_error(EINVAL));
+    }
+
+    let eid = get_enclave_id();
+    if eid == 0 {
+        set_errno(ESGX);
+        return Err(Error::from_sgx_error(sgx_status_t::SGX_ERROR_INVALID_ENCLAVE_ID));
+    }
+
+    let signo = match SigNum::from_raw(signal) {
+        Some(signo) => signo,
+        None => {
+            set_errno(EINVAL);
+            return Err(Error::from_raw_os_error(EINVAL));
+        }
+    };
+
+    let act: sigaction = unsafe { mem::zeroed() };
+    let mut oldact: sigaction = unsafe { mem::zeroed() };
+
+    native_sigaction_impl(
+        signo,
+        &act,
+        &mut oldact,
+        Arc::from(action),
+    )
+    .map(|action_id|
+        SignalId {
+            signal: signo,
+            action: action_id,
+        }
+    )
+    .map_err(|err|
+        Error::from_raw_os_error(err)
+    )
+}
+
+pub fn unregister(id: SignalId) -> bool {
+    let globals = GlobalData::ensure();
+    globals.signal_manager.remove_action(id.signal, id.action)
+}
+
+pub fn unregister_signal(signal: c_int) -> bool {
+    let globals = GlobalData::ensure();
+    let signo = unsafe { SigNum::from_raw_uncheck(signal) };
+    globals.signal_manager.clear_action(signo)
+}
+
+pub fn raise_signal(signal: c_int) -> bool {
+   rsgx_raise(signal) == 0
+}
diff --git a/sgx_tcrypto/Cargo.toml b/sgx_tcrypto/Cargo.toml
index 7a1363f..a9ec625 100644
--- a/sgx_tcrypto/Cargo.toml
+++ b/sgx_tcrypto/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tcrypto"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tcrypto/src/crypto.rs b/sgx_tcrypto/src/crypto.rs
index aa3403a..a34b583 100644
--- a/sgx_tcrypto/src/crypto.rs
+++ b/sgx_tcrypto/src/crypto.rs
@@ -67,8 +67,9 @@ use core::cell::{Cell, RefCell};
 /// The SHA256 hash calculation failed.
 ///
 pub fn rsgx_sha256_msg<T>(src: &T) -> SgxResult<sgx_sha256_hash_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -89,8 +90,9 @@ pub fn rsgx_sha256_msg<T>(src: &T) -> SgxResult<sgx_sha256_hash_t>
 /// The rsgx_sha256_slice function performs a standard SHA256 hash over the input data buffer.
 ///
 pub fn rsgx_sha256_slice<T>(src: &[T]) -> SgxResult<sgx_sha256_hash_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -114,8 +116,9 @@ fn rsgx_sha256_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
 }
 
 fn rsgx_sha256_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -130,8 +133,9 @@ fn rsgx_sha256_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx
 }
 
 fn rsgx_sha256_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -153,8 +157,9 @@ fn rsgx_sha256_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
 }
 
 pub fn rsgx_sha1_msg<T>(src: &T) -> SgxResult<sgx_sha1_hash_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -172,8 +177,9 @@ pub fn rsgx_sha1_msg<T>(src: &T) -> SgxResult<sgx_sha1_hash_t>
 }
 
 pub fn rsgx_sha1_slice<T>(src: &[T]) -> SgxResult<sgx_sha1_hash_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -197,8 +203,9 @@ fn rsgx_sha1_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
 }
 
 fn rsgx_sha1_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -213,8 +220,9 @@ fn rsgx_sha1_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_s
 }
 
 fn rsgx_sha1_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -251,7 +259,7 @@ impl SgxShaHandle {
     ///
     /// Constructs a new, empty SgxShaHandle.
     ///
-    pub fn new() -> Self {
+    pub fn new() -> SgxShaHandle {
         SgxShaHandle{
             handle: RefCell::new(ptr::null_mut() as sgx_sha_state_handle_t),
             initflag: Cell::new(false),
@@ -301,7 +309,7 @@ impl SgxShaHandle {
             sgx_status_t::SGX_SUCCESS => {
                 self.initflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -346,8 +354,9 @@ impl SgxShaHandle {
     /// An internal cryptography library failure occurred while performing the SHA256 hash calculation.
     ///
     pub fn update_msg<T>(&self, src: &T) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -363,8 +372,9 @@ impl SgxShaHandle {
     /// update_slice performs a SHA256 hash over the input dataset provided.
     ///
     pub fn update_slice<T>(&self, src: &[T]) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -456,7 +466,7 @@ impl SgxShaHandle {
                 self.initflag.set(false);
                 *self.handle.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -484,8 +494,7 @@ pub struct SgxSha1Handle {
 }
 
 impl SgxSha1Handle {
-
-    pub fn new() -> Self {
+    pub fn new() -> SgxSha1Handle {
         SgxSha1Handle{
             handle: RefCell::new(ptr::null_mut() as sgx_sha_state_handle_t),
             initflag: Cell::new(false),
@@ -502,14 +511,15 @@ impl SgxSha1Handle {
             sgx_status_t::SGX_SUCCESS => {
                 self.initflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
 
     pub fn update_msg<T>(&self, src: &T) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -522,8 +532,9 @@ impl SgxSha1Handle {
     }
 
     pub fn update_slice<T>(&self, src: &[T]) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -567,7 +578,7 @@ impl SgxSha1Handle {
                 self.initflag.set(false);
                 *self.handle.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -662,13 +673,14 @@ impl Drop for SgxSha1Handle {
 ///
 /// An internal cryptography library failure occurred.
 ///
-pub fn rsgx_rijndael128GCM_encrypt(key: &sgx_aes_gcm_128bit_key_t,
-                                   src: &[u8],
-                                   iv: &[u8],
-                                   aad: &[u8],
-                                   dst: &mut [u8],
-                                   mac: &mut sgx_aes_gcm_128bit_tag_t) -> SgxError {
-
+pub fn rsgx_rijndael128GCM_encrypt(
+    key: &sgx_aes_gcm_128bit_key_t,
+    src: &[u8],
+    iv: &[u8],
+    aad: &[u8],
+    dst: &mut [u8],
+    mac: &mut sgx_aes_gcm_128bit_tag_t,
+) -> SgxError {
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -698,15 +710,17 @@ pub fn rsgx_rijndael128GCM_encrypt(key: &sgx_aes_gcm_128bit_key_t,
             (ptr::null(), ptr::null_mut())
         };
 
-        sgx_rijndael128GCM_encrypt(key as *const sgx_aes_gcm_128bit_key_t,
-                                   p_src,
-                                   src_len as u32,
-                                   p_dst,
-                                   iv.as_ptr(),
-                                   iv_len as u32,
-                                   p_aad,
-                                   aad_len as u32,
-                                   mac as *mut sgx_aes_gcm_128bit_tag_t)
+        sgx_rijndael128GCM_encrypt(
+            key as *const sgx_aes_gcm_128bit_key_t,
+            p_src,
+            src_len as u32,
+            p_dst,
+            iv.as_ptr(),
+            iv_len as u32,
+            p_aad,
+            aad_len as u32,
+            mac as *mut sgx_aes_gcm_128bit_tag_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -790,12 +804,14 @@ pub fn rsgx_rijndael128GCM_encrypt(key: &sgx_aes_gcm_128bit_key_t,
 ///
 /// An internal cryptography library failure occurred.
 ///
-pub fn rsgx_rijndael128GCM_decrypt(key: &sgx_aes_gcm_128bit_key_t,
-                                   src: &[u8],
-                                   iv: &[u8],
-                                   aad: &[u8],
-                                   mac: &sgx_aes_gcm_128bit_tag_t,
-                                   dst: &mut [u8]) -> SgxError {
+pub fn rsgx_rijndael128GCM_decrypt(
+    key: &sgx_aes_gcm_128bit_key_t,
+    src: &[u8],
+    iv: &[u8],
+    aad: &[u8],
+    mac: &sgx_aes_gcm_128bit_tag_t,
+    dst: &mut [u8],
+) -> SgxError {
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -825,15 +841,17 @@ pub fn rsgx_rijndael128GCM_decrypt(key: &sgx_aes_gcm_128bit_key_t,
             (ptr::null(), ptr::null_mut())
         };
 
-        sgx_rijndael128GCM_decrypt(key as *const sgx_aes_gcm_128bit_key_t,
-                                   p_src,
-                                   src_len as u32,
-                                   p_dst,
-                                   iv.as_ptr(),
-                                   iv_len as u32,
-                                   p_aad,
-                                   aad_len as u32,
-                                   mac as *const sgx_aes_gcm_128bit_tag_t)
+        sgx_rijndael128GCM_decrypt(
+            key as *const sgx_aes_gcm_128bit_key_t,
+            p_src,
+            src_len as u32,
+            p_dst,
+            iv.as_ptr(),
+            iv_len as u32,
+            p_aad,
+            aad_len as u32,
+            mac as *const sgx_aes_gcm_128bit_tag_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -886,8 +904,9 @@ pub fn rsgx_rijndael128GCM_decrypt(key: &sgx_aes_gcm_128bit_key_t,
 /// An internal cryptography library failure occurred.
 ///
 pub fn rsgx_rijndael128_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> SgxResult<sgx_cmac_128bit_tag_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -898,10 +917,12 @@ pub fn rsgx_rijndael128_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> Sgx
 
     let mut mac = sgx_cmac_128bit_tag_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
-                                 src as *const _ as *const u8,
-                                 size as u32,
-                                 &mut mac as *mut sgx_cmac_128bit_tag_t)
+        sgx_rijndael128_cmac_msg(
+            key as *const sgx_cmac_128bit_key_t,
+            src as *const _ as *const u8,
+            size as u32,
+            &mut mac as *mut sgx_cmac_128bit_tag_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(mac),
@@ -910,8 +931,9 @@ pub fn rsgx_rijndael128_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> Sgx
 }
 
 pub fn rsgx_rijndael128_align_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> SgxResult<sgx_align_mac_128bit_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -922,10 +944,12 @@ pub fn rsgx_rijndael128_align_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T)
 
     let mut align_mac = sgx_align_mac_128bit_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
-                                 src as *const _ as *const u8,
-                                 size as u32,
-                                 &mut align_mac.mac as *mut sgx_cmac_128bit_tag_t)
+        sgx_rijndael128_cmac_msg(
+            key as *const sgx_cmac_128bit_key_t,
+            src as *const _ as *const u8,
+            size as u32,
+            &mut align_mac.mac as *mut sgx_cmac_128bit_tag_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_mac),
@@ -937,8 +961,9 @@ pub fn rsgx_rijndael128_align_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T)
 /// The rsgx_rijndael128_cmac_slice function performs a standard 128bit CMAC hash over the input data buffer.
 ///
 pub fn rsgx_rijndael128_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) -> SgxResult<sgx_cmac_128bit_tag_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -949,10 +974,12 @@ pub fn rsgx_rijndael128_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) ->
 
     let mut mac = sgx_cmac_128bit_tag_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
-                                 src.as_ptr() as *const u8,
-                                 size as u32,
-                                 &mut mac as *mut sgx_cmac_128bit_tag_t)
+        sgx_rijndael128_cmac_msg(
+            key as *const sgx_cmac_128bit_key_t,
+            src.as_ptr() as *const u8,
+            size as u32,
+            &mut mac as *mut sgx_cmac_128bit_tag_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(mac),
@@ -961,8 +988,9 @@ pub fn rsgx_rijndael128_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) ->
 }
 
 pub fn rsgx_rijndael128_align_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) -> SgxResult<sgx_align_mac_128bit_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -973,10 +1001,12 @@ pub fn rsgx_rijndael128_align_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[
 
     let mut align_mac = sgx_align_mac_128bit_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
-                                 src.as_ptr() as *const u8,
-                                 size as u32,
-                                 &mut align_mac.mac as *mut sgx_cmac_128bit_tag_t)
+        sgx_rijndael128_cmac_msg(
+            key as *const sgx_cmac_128bit_key_t,
+            src.as_ptr() as *const u8,
+            size as u32,
+            &mut align_mac.mac as *mut sgx_cmac_128bit_tag_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_mac),
@@ -986,14 +1016,17 @@ pub fn rsgx_rijndael128_align_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[
 
 fn rsgx_cmac128_init(key: &sgx_cmac_128bit_key_t, cmac_handle: &mut sgx_cmac_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_cmac128_init(key as *const sgx_cmac_128bit_key_t,
-                         cmac_handle as *mut sgx_cmac_state_handle_t)
+        sgx_cmac128_init(
+            key as *const sgx_cmac_128bit_key_t,
+            cmac_handle as *mut sgx_cmac_state_handle_t,
+        )
     }
 }
 
 fn rsgx_cmac128_update_msg<T>(src: &T, cmac_handle: sgx_cmac_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1007,8 +1040,9 @@ fn rsgx_cmac128_update_msg<T>(src: &T, cmac_handle: sgx_cmac_state_handle_t) ->
 }
 
 fn rsgx_cmac128_update_slice<T>(src: &[T], cmac_handle: sgx_cmac_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1042,15 +1076,14 @@ pub struct SgxCmacHandle {
 }
 
 impl SgxCmacHandle {
-
     ///
     /// Constructs a new, empty SgxCmacHandle.
     ///
-    pub fn new() -> Self {
-        SgxCmacHandle{
+    pub fn new() -> SgxCmacHandle {
+        SgxCmacHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_cmac_state_handle_t),
             initflag: Cell::new(false),
-            }
+        }
     }
 
     ///
@@ -1103,7 +1136,7 @@ impl SgxCmacHandle {
             sgx_status_t::SGX_SUCCESS => {
                 self.initflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -1153,8 +1186,9 @@ impl SgxCmacHandle {
     /// An internal cryptography library failure occurred while performing the CMAC hash calculation.
     ///
     pub fn update_msg<T>(&self, src: &T) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1170,8 +1204,9 @@ impl SgxCmacHandle {
     /// update_slice performs a CMAC 128-bit hash over the input dataset provided.
     ///
     pub fn update_slice<T>(&self, src: &[T]) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1276,7 +1311,7 @@ impl SgxCmacHandle {
                 self.initflag.set(false);
                 *self.handle.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -1298,8 +1333,9 @@ impl Drop for SgxCmacHandle {
 }
 
 pub fn rsgx_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResult<sgx_hmac_256bit_tag_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -1310,12 +1346,14 @@ pub fn rsgx_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResul
 
     let mut mac = sgx_hmac_256bit_tag_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src as *const _ as *const u8,
-                            size as i32,
-                            key as *const u8,
-                            SGX_HMAC256_KEY_SIZE as i32,
-                            &mut mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
-                            SGX_HMAC256_MAC_SIZE as i32)
+        sgx_hmac_sha256_msg(
+            src as *const _ as *const u8,
+            size as i32,
+            key as *const u8,
+            SGX_HMAC256_KEY_SIZE as i32,
+            &mut mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
+            SGX_HMAC256_MAC_SIZE as i32,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(mac),
@@ -1324,8 +1362,9 @@ pub fn rsgx_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResul
 }
 
 pub fn rsgx_align_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResult<sgx_align_mac_256bit_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -1336,12 +1375,14 @@ pub fn rsgx_align_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> Sg
 
     let mut align_mac = sgx_align_mac_256bit_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src as *const _ as *const u8,
-                            size as i32,
-                            key as *const u8,
-                            SGX_HMAC256_KEY_SIZE as i32,
-                            &mut align_mac.mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
-                            SGX_HMAC256_MAC_SIZE as i32)
+        sgx_hmac_sha256_msg(
+            src as *const _ as *const u8,
+            size as i32,
+            key as *const u8,
+            SGX_HMAC256_KEY_SIZE as i32,
+            &mut align_mac.mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
+            SGX_HMAC256_MAC_SIZE as i32,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_mac),
@@ -1350,8 +1391,9 @@ pub fn rsgx_align_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> Sg
 }
 
 pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxResult<sgx_hmac_256bit_tag_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -1362,12 +1404,14 @@ pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxR
 
     let mut mac = sgx_hmac_256bit_tag_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src.as_ptr() as *const u8,
-                            size as i32,
-                            key as *const u8,
-                            SGX_HMAC256_KEY_SIZE as i32,
-                            &mut mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
-                            SGX_HMAC256_MAC_SIZE as i32)
+        sgx_hmac_sha256_msg(
+            src.as_ptr() as *const u8,
+            size as i32,
+            key as *const u8,
+            SGX_HMAC256_KEY_SIZE as i32,
+            &mut mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
+            SGX_HMAC256_MAC_SIZE as i32,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(mac),
@@ -1376,8 +1420,9 @@ pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxR
 }
 
 pub fn rsgx_align_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxResult<sgx_align_mac_256bit_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -1388,12 +1433,14 @@ pub fn rsgx_align_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -
 
     let mut align_mac = sgx_align_mac_256bit_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src.as_ptr() as *const u8,
-                            size as i32,
-                            key as *const u8,
-                            SGX_HMAC256_KEY_SIZE as i32,
-                            &mut align_mac.mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
-                            SGX_HMAC256_MAC_SIZE as i32)
+        sgx_hmac_sha256_msg(
+            src.as_ptr() as *const u8,
+            size as i32,
+            key as *const u8,
+            SGX_HMAC256_KEY_SIZE as i32,
+            &mut align_mac.mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
+            SGX_HMAC256_MAC_SIZE as i32,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_mac),
@@ -1403,15 +1450,18 @@ pub fn rsgx_align_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -
 
 fn rsgx_hmac256_init(key: &sgx_hmac_256bit_key_t, hmac_handle: &mut sgx_hmac_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_hmac256_init(key as *const sgx_hmac_256bit_key_t as *const u8,
-                         SGX_HMAC256_KEY_SIZE as i32,
-                         hmac_handle as *mut sgx_hmac_state_handle_t)
+        sgx_hmac256_init(
+            key as *const sgx_hmac_256bit_key_t as *const u8,
+            SGX_HMAC256_KEY_SIZE as i32,
+            hmac_handle as *mut sgx_hmac_state_handle_t,
+        )
     }
 }
 
 fn rsgx_hmac256_update_msg<T>(src: &T, hmac_handle: sgx_hmac_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1425,8 +1475,9 @@ fn rsgx_hmac256_update_msg<T>(src: &T, hmac_handle: sgx_hmac_state_handle_t) ->
 }
 
 fn rsgx_hmac256_update_slice<T>(src: &[T], hmac_handle: sgx_hmac_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(src);
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1441,9 +1492,11 @@ fn rsgx_hmac256_update_slice<T>(src: &[T], hmac_handle: sgx_hmac_state_handle_t)
 
 fn rsgx_hmac256_final(hmac_handle: sgx_hmac_state_handle_t, hash: &mut sgx_hmac_256bit_tag_t) -> sgx_status_t {
     unsafe {
-        sgx_hmac256_final(hash as *mut sgx_hmac_256bit_tag_t as *mut u8,
-                          SGX_HMAC256_MAC_SIZE as i32,
-                          hmac_handle)
+        sgx_hmac256_final(
+            hash as *mut sgx_hmac_256bit_tag_t as *mut u8,
+            SGX_HMAC256_MAC_SIZE as i32,
+            hmac_handle,
+        )
     }
 }
 
@@ -1457,12 +1510,11 @@ pub struct SgxHmacHandle {
 }
 
 impl SgxHmacHandle {
-
-    pub fn new() -> Self {
+    pub fn new() -> SgxHmacHandle {
         SgxHmacHandle{
             handle: RefCell::new(ptr::null_mut() as sgx_hmac_state_handle_t),
             initflag: Cell::new(false),
-            }
+        }
     }
 
     pub fn init(&self, key: &sgx_hmac_256bit_key_t) -> SgxError {
@@ -1475,14 +1527,15 @@ impl SgxHmacHandle {
             sgx_status_t::SGX_SUCCESS => {
                 self.initflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
 
     pub fn update_msg<T>(&self, src: &T) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1495,8 +1548,9 @@ impl SgxHmacHandle {
     }
 
     pub fn update_slice<T>(&self, src: &[T]) -> SgxError
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1553,7 +1607,7 @@ impl SgxHmacHandle {
                 self.initflag.set(false);
                 *self.handle.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -1632,12 +1686,13 @@ pub type sgx_aes_ctr_128bit_ctr_t = [uint8_t; SGX_AESCTR_CTR_SIZE];
 ///
 /// An internal cryptography library failure occurred.
 ///
-pub fn rsgx_aes_ctr_encrypt(key: &sgx_aes_ctr_128bit_key_t,
-                            src: &[u8],
-                            ctr: &sgx_aes_ctr_128bit_ctr_t,
-                            ctr_inc_bits: u32,
-                            dst: &mut [u8]) -> SgxError {
-
+pub fn rsgx_aes_ctr_encrypt(
+    key: &sgx_aes_ctr_128bit_key_t,
+    src: &[u8],
+    ctr: &sgx_aes_ctr_128bit_ctr_t,
+    ctr_inc_bits: u32,
+    dst: &mut [u8],
+) -> SgxError {
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -1654,12 +1709,14 @@ pub fn rsgx_aes_ctr_encrypt(key: &sgx_aes_ctr_128bit_key_t,
     }
 
     let ret = unsafe {
-        sgx_aes_ctr_encrypt(key as *const sgx_aes_ctr_128bit_key_t,
-                            src.as_ptr(),
-                            src_len as u32,
-                            ctr as *const sgx_aes_ctr_128bit_ctr_t as *const u8,
-                            ctr_inc_bits,
-                            dst.as_mut_ptr())
+        sgx_aes_ctr_encrypt(
+            key as *const sgx_aes_ctr_128bit_key_t,
+            src.as_ptr(),
+            src_len as u32,
+            ctr as *const sgx_aes_ctr_128bit_ctr_t as *const u8,
+            ctr_inc_bits,
+            dst.as_mut_ptr(),
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -1725,12 +1782,13 @@ pub fn rsgx_aes_ctr_encrypt(key: &sgx_aes_ctr_128bit_key_t,
 ///
 /// An internal cryptography library failure occurred.
 ///
-pub fn rsgx_aes_ctr_decrypt(key: &sgx_aes_ctr_128bit_key_t,
-                            src: &[u8],
-                            ctr: &sgx_aes_ctr_128bit_ctr_t,
-                            ctr_inc_bits: u32,
-                            dst: &mut [u8]) -> SgxError {
-
+pub fn rsgx_aes_ctr_decrypt(
+    key: &sgx_aes_ctr_128bit_key_t,
+    src: &[u8],
+    ctr: &sgx_aes_ctr_128bit_ctr_t,
+    ctr_inc_bits: u32,
+    dst: &mut [u8],
+) -> SgxError {
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -1747,12 +1805,14 @@ pub fn rsgx_aes_ctr_decrypt(key: &sgx_aes_ctr_128bit_key_t,
     }
 
     let ret = unsafe {
-        sgx_aes_ctr_decrypt(key as *const sgx_aes_ctr_128bit_key_t,
-                            src.as_ptr(),
-                            src.len() as u32,
-                            ctr as *const sgx_aes_ctr_128bit_ctr_t as *const u8,
-                            ctr_inc_bits,
-                            dst.as_mut_ptr())
+        sgx_aes_ctr_decrypt(
+            key as *const sgx_aes_ctr_128bit_key_t,
+            src.as_ptr(),
+            src.len() as u32,
+            ctr as *const sgx_aes_ctr_128bit_ctr_t as *const u8,
+            ctr_inc_bits,
+            dst.as_mut_ptr(),
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -1768,13 +1828,17 @@ fn rsgx_ecc256_close_context(ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t
     unsafe { sgx_ecc256_close_context(ecc_handle) }
 }
 
-fn rsgx_ecc256_create_key_pair(private: &mut sgx_ec256_private_t,
-                               public: &mut sgx_ec256_public_t,
-                               ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
+fn rsgx_ecc256_create_key_pair(
+    private: &mut sgx_ec256_private_t,
+    public: &mut sgx_ec256_public_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t {
     unsafe {
-        sgx_ecc256_create_key_pair(private as *mut sgx_ec256_private_t,
-                                   public as *mut sgx_ec256_public_t,
-                                   ecc_handle)
+        sgx_ecc256_create_key_pair(
+            private as *mut sgx_ec256_private_t,
+            public as *mut sgx_ec256_public_t,
+            ecc_handle,
+        )
     }
 }
 
@@ -1782,38 +1846,49 @@ fn rsgx_ecc256_check_point(point: &sgx_ec256_public_t, ecc_handle: sgx_ecc_state
     unsafe { sgx_ecc256_check_point(point as *const sgx_ec256_public_t, ecc_handle, valid as *mut i32) }
 }
 
-fn rsgx_ecc256_compute_shared_dhkey(private_b: &sgx_ec256_private_t,
-                                    public_ga: &sgx_ec256_public_t,
-                                    shared_key: &mut sgx_ec256_dh_shared_t,
-                                    ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
+fn rsgx_ecc256_compute_shared_dhkey(
+    private_b: &sgx_ec256_private_t,
+    public_ga: &sgx_ec256_public_t,
+    shared_key: &mut sgx_ec256_dh_shared_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t {
     unsafe {
-        sgx_ecc256_compute_shared_dhkey(private_b as *const _ as *mut sgx_ec256_private_t,
-                                        public_ga as *const _ as *mut sgx_ec256_public_t,
-                                        shared_key as *mut sgx_ec256_dh_shared_t,
-                                        ecc_handle)
+        sgx_ecc256_compute_shared_dhkey(
+            private_b as *const _ as *mut sgx_ec256_private_t,
+            public_ga as *const _ as *mut sgx_ec256_public_t,
+            shared_key as *mut sgx_ec256_dh_shared_t,
+            ecc_handle,
+        )
     }
 }
 
 /* delete (intel sgx sdk 2.0)
-fn rsgx_ecc256_compute_shared_dhkey512(private_b: &sgx_ec256_private_t,
-                                       public_ga: &sgx_ec256_public_t,
-                                       shared_key: &mut sgx_ec256_dh_shared512_t,
-                                       ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
+fn rsgx_ecc256_compute_shared_dhkey512(
+    private_b: &sgx_ec256_private_t,
+    public_ga: &sgx_ec256_public_t,
+    shared_key: &mut sgx_ec256_dh_shared512_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t {
     unsafe {
-        sgx_ecc256_compute_shared_dhkey512(private_b as *const _ as *mut sgx_ec256_private_t,
-                                           public_ga as *const _ as *mut sgx_ec256_public_t,
-                                           shared_key as *mut sgx_ec256_dh_shared512_t,
-                                           ecc_handle)
+        sgx_ecc256_compute_shared_dhkey512(
+            private_b as *const _ as *mut sgx_ec256_private_t,
+            public_ga as *const _ as *mut sgx_ec256_public_t,
+            shared_key as *mut sgx_ec256_dh_shared512_t,
+            ecc_handle,
+        )
     }
 }
 */
 
-fn rsgx_ecdsa_sign_msg<T>(data: &T,
-                          private: &sgx_ec256_private_t,
-                          signature: &mut sgx_ec256_signature_t,
-                          ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+fn rsgx_ecdsa_sign_msg<T>(
+    data: &T,
+    private: &sgx_ec256_private_t,
+    signature: &mut sgx_ec256_signature_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1831,12 +1906,15 @@ fn rsgx_ecdsa_sign_msg<T>(data: &T,
     }
 }
 
-fn rsgx_ecdsa_sign_slice<T>(data: &[T],
-                            private: &sgx_ec256_private_t,
-                            signature: &mut sgx_ec256_signature_t,
-                            ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+fn rsgx_ecdsa_sign_slice<T>(
+    data: &[T],
+    private: &sgx_ec256_private_t,
+    signature: &mut sgx_ec256_signature_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(data);
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1846,21 +1924,26 @@ fn rsgx_ecdsa_sign_slice<T>(data: &[T],
     }
 
     unsafe {
-        sgx_ecdsa_sign(data.as_ptr() as *const _  as *const u8,
-                       size as u32,
-                       private as *const _ as *mut sgx_ec256_private_t,
-                       signature as *mut sgx_ec256_signature_t,
-                       ecc_handle)
-    }
-}
-
-fn rsgx_ecdsa_verify_msg<T>(data: &T,
-                            public: &sgx_ec256_public_t,
-                            signature: &sgx_ec256_signature_t,
-                            result: &mut sgx_generic_ecresult_t,
-                            ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+        sgx_ecdsa_sign(
+            data.as_ptr() as *const _  as *const u8,
+            size as u32,
+            private as *const _ as *mut sgx_ec256_private_t,
+            signature as *mut sgx_ec256_signature_t,
+            ecc_handle,
+        )
+    }
+}
+
+fn rsgx_ecdsa_verify_msg<T>(
+    data: &T,
+    public: &sgx_ec256_public_t,
+    signature: &sgx_ec256_signature_t,
+    result: &mut sgx_generic_ecresult_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1871,30 +1954,34 @@ fn rsgx_ecdsa_verify_msg<T>(data: &T,
 
     unsafe {
         let mut verify: u8 = 0;
-        let ret = sgx_ecdsa_verify(data as *const _ as *const u8,
-                                   size as u32,
-                                   public as *const sgx_ec256_public_t,
-                                   signature as *const _ as *mut sgx_ec256_signature_t,
-                                   &mut verify as *mut u8,
-                                   ecc_handle);
+        let ret = sgx_ecdsa_verify(
+            data as *const _ as *const u8,
+            size as u32,
+            public as *const sgx_ec256_public_t,
+            signature as *const _ as *mut sgx_ec256_signature_t,
+            &mut verify as *mut u8,
+            ecc_handle);
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 let ecresult = sgx_generic_ecresult_t::from_repr(u32::from(verify));
                 *result = ecresult.unwrap_or(sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE);
-            },
-            _ => { *result = sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE; },
+            }
+            _ => { *result = sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE; }
         };
         ret
     }
 }
 
-fn rsgx_ecdsa_verify_slice<T>(data: &[T],
-                              public: &sgx_ec256_public_t,
-                              signature: &sgx_ec256_signature_t,
-                              result: &mut sgx_generic_ecresult_t,
-                              ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t
-    where T: Copy + ContiguousMemory {
-
+fn rsgx_ecdsa_verify_slice<T>(
+    data: &[T],
+    public: &sgx_ec256_public_t,
+    signature: &sgx_ec256_signature_t,
+    result: &mut sgx_generic_ecresult_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(data);
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -1905,41 +1992,47 @@ fn rsgx_ecdsa_verify_slice<T>(data: &[T],
 
     unsafe {
         let mut verify: u8 = 0;
-        let ret = sgx_ecdsa_verify(data.as_ptr() as *const _ as *const u8,
-                                   size as u32,
-                                   public as *const sgx_ec256_public_t,
-                                   signature as *const _ as *mut sgx_ec256_signature_t,
-                                   &mut verify as *mut u8,
-                                   ecc_handle);
+        let ret = sgx_ecdsa_verify(
+            data.as_ptr() as *const _ as *const u8,
+            size as u32,
+            public as *const sgx_ec256_public_t,
+            signature as *const _ as *mut sgx_ec256_signature_t,
+            &mut verify as *mut u8,
+            ecc_handle,
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 let ecresult = sgx_generic_ecresult_t::from_repr(u32::from(verify));
                 *result = ecresult.unwrap_or(sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE);
-            },
-            _ => { *result = sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE; },
+            }
+            _ => { *result = sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE; }
         };
         ret
     }
 }
 
-fn rsgx_ecdsa_verify_hash(hash: &sgx_sha256_hash_t,
-                          public: &sgx_ec256_public_t,
-                          signature: &sgx_ec256_signature_t,
-                          result: &mut sgx_generic_ecresult_t,
-                          ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
+fn rsgx_ecdsa_verify_hash(
+    hash: &sgx_sha256_hash_t,
+    public: &sgx_ec256_public_t,
+    signature: &sgx_ec256_signature_t,
+    result: &mut sgx_generic_ecresult_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+) -> sgx_status_t {
     unsafe {
         let mut verify: u8 = 0;
-        let ret = sgx_ecdsa_verify_hash(hash as *const sgx_sha256_hash_t as *const u8,
-                                        public as *const sgx_ec256_public_t,
-                                        signature as *const _ as *mut sgx_ec256_signature_t,
-                                        &mut verify as *mut u8,
-                                        ecc_handle);
+        let ret = sgx_ecdsa_verify_hash(
+            hash as *const sgx_sha256_hash_t as *const u8,
+            public as *const sgx_ec256_public_t,
+            signature as *const _ as *mut sgx_ec256_signature_t,
+            &mut verify as *mut u8,
+            ecc_handle,
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 let ecresult = sgx_generic_ecresult_t::from_repr(u32::from(verify));
                 *result = ecresult.unwrap_or(sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE);
-            },
-            _ => { *result = sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE; },
+            }
+            _ => { *result = sgx_generic_ecresult_t::SGX_EC_INVALID_SIGNATURE; }
         };
         ret
     }
@@ -1959,15 +2052,14 @@ pub struct SgxEccHandle{
 }
 
 impl SgxEccHandle {
-
     ///
     /// Constructs a new, empty SgxEccHandle.
     ///
-    pub fn new() -> Self {
-        SgxEccHandle{
+    pub fn new() -> SgxEccHandle {
+        SgxEccHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_ecc_state_handle_t),
             initflag: Cell::new(false),
-            }
+        }
     }
 
     ///
@@ -2036,7 +2128,7 @@ impl SgxEccHandle {
             sgx_status_t::SGX_SUCCESS => {
                 self.initflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -2187,7 +2279,7 @@ impl SgxEccHandle {
                 } else {
                     Ok(false)
                 }
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -2310,7 +2402,6 @@ impl SgxEccHandle {
 
     /* delete (intel sgx sdk 2.0)
     pub fn compute_shared_dhkey512(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_ec256_dh_shared512_t> {
-
         if self.initflag.get() == false {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2385,8 +2476,9 @@ impl SgxEccHandle {
     /// The signature generation process failed due to an internal cryptography library failure.
     ///
     pub fn ecdsa_sign_msg<T>(&self, data: &T, private: &sgx_ec256_private_t) -> SgxResult<sgx_ec256_signature_t>
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2403,8 +2495,9 @@ impl SgxEccHandle {
     /// ecdsa_sign_slice computes a digital signature with a given private key over an input dataset.
     ///
     pub fn ecdsa_sign_slice<T>(&self, data: &[T], private: &sgx_ec256_private_t) -> SgxResult<sgx_ec256_signature_t>
-        where T: Copy + ContiguousMemory {
-
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2477,12 +2570,15 @@ impl SgxEccHandle {
     ///
     /// The verification process failed due to an internal cryptography library failure.
     ///
-    pub fn ecdsa_verify_msg<T>(&self,
-                               data: &T,
-                               public: &sgx_ec256_public_t,
-                               signature: &sgx_ec256_signature_t) -> SgxResult<bool>
-        where T: Copy + ContiguousMemory {
-
+    pub fn ecdsa_verify_msg<T>(
+        &self,
+        data: &T,
+        public: &sgx_ec256_public_t,
+        signature: &sgx_ec256_signature_t,
+    ) -> SgxResult<bool>
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2495,7 +2591,7 @@ impl SgxEccHandle {
                     sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
                     _ => Ok(false),
                 }
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -2503,12 +2599,15 @@ impl SgxEccHandle {
     ///
     /// ecdsa_verify_slice verifies the input digital signature with a given public key over an input dataset.
     ///
-    pub fn ecdsa_verify_slice<T>(&self,
-                                 data: &[T],
-                                 public: &sgx_ec256_public_t,
-                                 signature: &sgx_ec256_signature_t) -> SgxResult<bool>
-        where T: Copy + ContiguousMemory {
-
+    pub fn ecdsa_verify_slice<T>(
+        &self,
+        data: &[T],
+        public: &sgx_ec256_public_t,
+        signature: &sgx_ec256_signature_t,
+    ) -> SgxResult<bool>
+    where
+        T: Copy + ContiguousMemory,
+    {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2521,15 +2620,17 @@ impl SgxEccHandle {
                     sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
                     _ => Ok(false),
                 }
-            },
+            }
             _ => Err(ret),
         }
     }
 
-    pub fn ecdsa_verify_hash(&self,
-                             hash: &sgx_sha256_hash_t,
-                             public: &sgx_ec256_public_t,
-                             signature: &sgx_ec256_signature_t) -> SgxResult<bool> {
+    pub fn ecdsa_verify_hash(
+        &self,
+        hash: &sgx_sha256_hash_t,
+        public: &sgx_ec256_public_t,
+        signature: &sgx_ec256_signature_t,
+    ) -> SgxResult<bool> {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2542,7 +2643,7 @@ impl SgxEccHandle {
                     sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
                     _ => Ok(false),
                 }
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -2584,7 +2685,7 @@ impl SgxEccHandle {
                 self.initflag.set(false);
                 *self.handle.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -2652,8 +2753,9 @@ impl Drop for SgxEccHandle {
 /// The signature generation process failed due to an internal cryptography library failure.
 ///
 pub fn rsgx_rsa3072_sign_msg<T>(data: &T, key: &sgx_rsa3072_key_t) -> SgxResult<sgx_rsa3072_signature_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -2664,10 +2766,12 @@ pub fn rsgx_rsa3072_sign_msg<T>(data: &T, key: &sgx_rsa3072_key_t) -> SgxResult<
 
     let mut sign = sgx_rsa3072_signature_t::default();
     let ret = unsafe {
-        sgx_rsa3072_sign(data as *const _ as *const u8,
-                         size as u32,
-                         key as *const sgx_rsa3072_key_t,
-                         &mut sign as *mut sgx_rsa3072_signature_t)
+        sgx_rsa3072_sign(
+            data as *const _ as *const u8,
+            size as u32,
+            key as *const sgx_rsa3072_key_t,
+            &mut sign as *mut sgx_rsa3072_signature_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(sign),
@@ -2679,8 +2783,9 @@ pub fn rsgx_rsa3072_sign_msg<T>(data: &T, key: &sgx_rsa3072_key_t) -> SgxResult<
 /// The rsgx_rsa3072_sign_slice computes a digital signature for a given dataset based on RSA 3072 private key.
 ///
 pub fn rsgx_rsa3072_sign_slice<T>(data: &[T], key: &sgx_rsa3072_key_t) -> SgxResult<sgx_rsa3072_signature_t>
-    where T: Copy + ContiguousMemory {
-
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(data);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -2691,10 +2796,12 @@ pub fn rsgx_rsa3072_sign_slice<T>(data: &[T], key: &sgx_rsa3072_key_t) -> SgxRes
 
     let mut sign = sgx_rsa3072_signature_t::default();
     let ret = unsafe {
-        sgx_rsa3072_sign(data.as_ptr() as *const _ as *const u8,
-                         size as u32,
-                         key as *const sgx_rsa3072_key_t,
-                         &mut sign as *mut sgx_rsa3072_signature_t)
+        sgx_rsa3072_sign(
+            data.as_ptr() as *const _ as *const u8,
+            size as u32,
+            key as *const sgx_rsa3072_key_t,
+            &mut sign as *mut sgx_rsa3072_signature_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(sign),
@@ -2754,11 +2861,14 @@ pub fn rsgx_rsa3072_sign_slice<T>(data: &[T], key: &sgx_rsa3072_key_t) -> SgxRes
 ///
 /// The verification process failed due to an internal cryptography library failure.
 ///
-pub fn rsgx_rsa3072_verify_msg<T>(data: &T,
-                                  public: &sgx_rsa3072_public_key_t,
-                                  signature: &sgx_rsa3072_signature_t) -> SgxResult<bool>
-    where T: Copy + ContiguousMemory {
-
+pub fn rsgx_rsa3072_verify_msg<T>(
+    data: &T,
+    public: &sgx_rsa3072_public_key_t,
+    signature: &sgx_rsa3072_signature_t,
+) -> SgxResult<bool>
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of::<T>();
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -2768,20 +2878,21 @@ pub fn rsgx_rsa3072_verify_msg<T>(data: &T,
     }
 
     unsafe {
-
         let mut verify = sgx_rsa_result_t::SGX_RSA_INVALID_SIGNATURE;
-        let ret = sgx_rsa3072_verify(data as *const _ as *const u8,
-                                     size as u32,
-                                     public as *const sgx_rsa3072_public_key_t,
-                                     signature as *const sgx_rsa3072_signature_t,
-                                     &mut verify as *mut sgx_rsa_result_t);
+        let ret = sgx_rsa3072_verify(
+            data as *const _ as *const u8,
+            size as u32,
+            public as *const sgx_rsa3072_public_key_t,
+            signature as *const sgx_rsa3072_signature_t,
+            &mut verify as *mut sgx_rsa_result_t,
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 match verify {
                     sgx_rsa_result_t::SGX_RSA_VALID => Ok(true),
                     _ => Ok(false),
                 }
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -2790,11 +2901,14 @@ pub fn rsgx_rsa3072_verify_msg<T>(data: &T,
 ///
 /// rsgx_rsa3072_verify_slice verifies the input digital signature for the given data- set based on the RSA 3072 public key.
 ///
-pub fn rsgx_rsa3072_verify_slice<T>(data: &[T],
-                                    public: &sgx_rsa3072_public_key_t,
-                                    signature: &sgx_rsa3072_signature_t) -> SgxResult<bool>
-    where T: Copy + ContiguousMemory {
-
+pub fn rsgx_rsa3072_verify_slice<T>(
+    data: &[T],
+    public: &sgx_rsa3072_public_key_t,
+    signature: &sgx_rsa3072_signature_t,
+) -> SgxResult<bool>
+where
+    T: Copy + ContiguousMemory,
+{
     let size = mem::size_of_val(data);
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -2804,36 +2918,39 @@ pub fn rsgx_rsa3072_verify_slice<T>(data: &[T],
     }
 
     unsafe {
-
         let mut verify = sgx_rsa_result_t::SGX_RSA_INVALID_SIGNATURE;
-        let ret = sgx_rsa3072_verify(data.as_ptr() as *const _ as *const u8,
-                                     size as u32,
-                                     public as *const sgx_rsa3072_public_key_t,
-                                     signature as *const sgx_rsa3072_signature_t,
-                                     &mut verify as *mut sgx_rsa_result_t);
+        let ret = sgx_rsa3072_verify(
+            data.as_ptr() as *const _ as *const u8,
+            size as u32,
+            public as *const sgx_rsa3072_public_key_t,
+            signature as *const sgx_rsa3072_signature_t,
+            &mut verify as *mut sgx_rsa_result_t,
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 match verify {
                     sgx_rsa_result_t::SGX_RSA_VALID => Ok(true),
                     _ => Ok(false),
                 }
-            },
+            }
             _ => Err(ret),
         }
     }
 }
 
 #[allow(clippy::many_single_char_names)]
-pub fn rsgx_create_rsa_key_pair(n_byte_size: i32,
-                                e_byte_size: i32,
-                                n: &mut [u8],
-                                d: &mut [u8],
-                                e: &mut [u8],
-                                p: &mut [u8],
-                                q: &mut [u8],
-                                dmp1: &mut [u8],
-                                dmq1: &mut [u8],
-                                iqmp: &mut [u8]) -> SgxError {
+pub fn rsgx_create_rsa_key_pair(
+    n_byte_size: i32,
+    e_byte_size: i32,
+    n: &mut [u8],
+    d: &mut [u8],
+    e: &mut [u8],
+    p: &mut [u8],
+    q: &mut [u8],
+    dmp1: &mut [u8],
+    dmq1: &mut [u8],
+    iqmp: &mut [u8],
+) -> SgxError {
     if (n_byte_size <= 0) || (e_byte_size <= 0) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
@@ -2863,16 +2980,18 @@ pub fn rsgx_create_rsa_key_pair(n_byte_size: i32,
     }
 
     let ret = unsafe {
-        sgx_create_rsa_key_pair(n_byte_size,
-                                e_byte_size,
-                                n.as_mut_ptr(),
-                                d.as_mut_ptr(),
-                                e.as_mut_ptr(),
-                                p.as_mut_ptr(),
-                                q.as_mut_ptr(),
-                                dmp1.as_mut_ptr(),
-                                dmq1.as_mut_ptr(),
-                                iqmp.as_mut_ptr())
+        sgx_create_rsa_key_pair(
+            n_byte_size,
+            e_byte_size,
+            n.as_mut_ptr(),
+            d.as_mut_ptr(),
+            e.as_mut_ptr(),
+            p.as_mut_ptr(),
+            q.as_mut_ptr(),
+            dmp1.as_mut_ptr(),
+            dmq1.as_mut_ptr(),
+            iqmp.as_mut_ptr(),
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -2880,15 +2999,17 @@ pub fn rsgx_create_rsa_key_pair(n_byte_size: i32,
     }
 }
 
-fn rsgx_create_rsa_priv2_key(mod_size: i32,
-                             exp_size: i32,
-                             e: &[u8],
-                             p: &[u8],
-                             q: &[u8],
-                             dmp1: &[u8],
-                             dmq1: &[u8],
-                             iqmp: &[u8],
-                             new_pri_key: &mut sgx_rsa_key_t) -> sgx_status_t {
+fn rsgx_create_rsa_priv2_key(
+    mod_size: i32,
+    exp_size: i32,
+    e: &[u8],
+    p: &[u8],
+    q: &[u8],
+    dmp1: &[u8],
+    dmq1: &[u8],
+    iqmp: &[u8],
+    new_pri_key: &mut sgx_rsa_key_t,
+) -> sgx_status_t {
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2912,25 +3033,29 @@ fn rsgx_create_rsa_priv2_key(mod_size: i32,
     }
 
     unsafe {
-        sgx_create_rsa_priv2_key(mod_size,
-                                 exp_size,
-                                 e.as_ptr(),
-                                 p.as_ptr(),
-                                 q.as_ptr(),
-                                 dmp1.as_ptr(),
-                                 dmq1.as_ptr(),
-                                 iqmp.as_ptr(),
-                                 new_pri_key as *mut sgx_rsa_key_t)
-    }
-}
-
-fn rsgx_create_rsa_priv1_key(n_size: i32,
-                            e_size: i32,
-                            d_size: i32,
-                            n: &[u8],
-                            e: &[u8],
-                            d: &[u8],
-                            new_pri_key: &mut sgx_rsa_key_t) -> sgx_status_t {
+        sgx_create_rsa_priv2_key(
+            mod_size,
+            exp_size,
+            e.as_ptr(),
+            p.as_ptr(),
+            q.as_ptr(),
+            dmp1.as_ptr(),
+            dmq1.as_ptr(),
+            iqmp.as_ptr(),
+            new_pri_key as *mut sgx_rsa_key_t,
+        )
+    }
+}
+
+fn rsgx_create_rsa_priv1_key(
+    n_size: i32,
+    e_size: i32,
+    d_size: i32,
+    n: &[u8],
+    e: &[u8],
+    d: &[u8],
+    new_pri_key: &mut sgx_rsa_key_t,
+) -> sgx_status_t {
     if (n_size <= 0) || (e_size <= 0) || (d_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2945,21 +3070,25 @@ fn rsgx_create_rsa_priv1_key(n_size: i32,
     }
 
     unsafe {
-        sgx_create_rsa_priv1_key(n_size,
-                                 e_size,
-                                 d_size,
-                                 n.as_ptr(),
-                                 e.as_ptr(),
-                                 d.as_ptr(),
-                                 new_pri_key as *mut sgx_rsa_key_t)
-    }
-}
-
-fn rsgx_create_rsa_pub1_key(mod_size: i32,
-                           exp_size: i32,
-                           n: &[u8],
-                           e: &[u8],
-                           new_pub_key: &mut sgx_rsa_key_t) -> sgx_status_t {
+        sgx_create_rsa_priv1_key(
+            n_size,
+            e_size,
+            d_size,
+            n.as_ptr(),
+            e.as_ptr(),
+            d.as_ptr(),
+            new_pri_key as *mut sgx_rsa_key_t,
+        )
+    }
+}
+
+fn rsgx_create_rsa_pub1_key(
+    mod_size: i32,
+    exp_size: i32,
+    n: &[u8],
+    e: &[u8],
+    new_pub_key: &mut sgx_rsa_key_t,
+) -> sgx_status_t {
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2971,31 +3100,36 @@ fn rsgx_create_rsa_pub1_key(mod_size: i32,
     }
 
     unsafe {
-        sgx_create_rsa_pub1_key(mod_size,
-                                exp_size,
-                                n.as_ptr(),
-                                e.as_ptr(),
-                                new_pub_key as *mut sgx_rsa_key_t)
-    }
-}
-
-fn rsgx_free_rsa_key(rsa_key: sgx_rsa_key_t,
-                     key_type: sgx_rsa_key_type_t,
-                     mod_size: i32,
-                     exp_size: i32) -> sgx_status_t {
+        sgx_create_rsa_pub1_key(
+            mod_size,
+            exp_size,
+            n.as_ptr(),
+            e.as_ptr(),
+            new_pub_key as *mut sgx_rsa_key_t,
+        )
+    }
+}
+
+fn rsgx_free_rsa_key(
+    rsa_key: sgx_rsa_key_t,
+    key_type: sgx_rsa_key_type_t,
+    mod_size: i32,
+    exp_size: i32,
+) -> sgx_status_t {
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-
     unsafe {
         sgx_free_rsa_key(rsa_key, key_type, mod_size, exp_size)
     }
 }
 
-fn rsgx_rsa_priv_decrypt_sha256(rsa_key: sgx_rsa_key_t,
-                                out_data: &mut [u8],
-                                out_len: &mut usize,
-                                in_data: &[u8]) -> sgx_status_t {
+fn rsgx_rsa_priv_decrypt_sha256(
+    rsa_key: sgx_rsa_key_t,
+    out_data: &mut [u8],
+    out_len: &mut usize,
+    in_data: &[u8],
+) -> sgx_status_t {
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -3009,19 +3143,22 @@ fn rsgx_rsa_priv_decrypt_sha256(rsa_key: sgx_rsa_key_t,
         } else {
             ptr::null_mut()
         };
-
-        sgx_rsa_priv_decrypt_sha256(rsa_key,
-                                    p_out_data,
-                                    out_len as *mut usize,
-                                    in_data.as_ptr(),
-                                    in_data.len())
-    }
-}
-
-fn rsgx_rsa_pub_encrypt_sha256(rsa_key: sgx_rsa_key_t,
-                               out_data: &mut [u8],
-                               out_len: &mut usize,
-                               in_data: &[u8]) -> sgx_status_t {
+        sgx_rsa_priv_decrypt_sha256(
+            rsa_key,
+            p_out_data,
+            out_len as *mut usize,
+            in_data.as_ptr(),
+            in_data.len(),
+        )
+    }
+}
+
+fn rsgx_rsa_pub_encrypt_sha256(
+    rsa_key: sgx_rsa_key_t,
+    out_data: &mut [u8],
+    out_len: &mut usize,
+    in_data: &[u8],
+) -> sgx_status_t {
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -3035,12 +3172,13 @@ fn rsgx_rsa_pub_encrypt_sha256(rsa_key: sgx_rsa_key_t,
         } else {
             ptr::null_mut()
         };
-
-        sgx_rsa_pub_encrypt_sha256(rsa_key,
-                                   p_out_data,
-                                   out_len as *mut usize,
-                                   in_data.as_ptr(),
-                                   in_data.len())
+        sgx_rsa_pub_encrypt_sha256(
+            rsa_key,
+            p_out_data,
+            out_len as *mut usize,
+            in_data.as_ptr(),
+            in_data.len(),
+        )
     }
 }
 
@@ -3052,8 +3190,7 @@ pub struct SgxRsaPrivKey {
 }
 
 impl SgxRsaPrivKey {
-
-    pub fn new() -> Self {
+    pub fn new() -> SgxRsaPrivKey {
         SgxRsaPrivKey {
             key: RefCell::new(ptr::null_mut() as sgx_rsa_key_t),
             mod_size: Cell::new(0),
@@ -3063,96 +3200,108 @@ impl SgxRsaPrivKey {
     }
 
     #[inline]
-    pub fn create(&self,
-                  mod_size: i32,
-                  exp_size: i32,
-                  e: &[u8],
-                  p: &[u8],
-                  q: &[u8],
-                  dmp1: &[u8],
-                  dmq1: &[u8],
-                  iqmp: &[u8]) -> SgxError {
+    pub fn create(
+        &self,
+        mod_size: i32,
+        exp_size: i32,
+        e: &[u8],
+        p: &[u8],
+        q: &[u8],
+        dmp1: &[u8],
+        dmq1: &[u8],
+        iqmp: &[u8],
+    ) -> SgxError {
         self.create2(mod_size, exp_size, e, p, q, dmp1, dmq1, iqmp)
     }
 
-    pub fn create2(&self,
-                   mod_size: i32,
-                   exp_size: i32,
-                   e: &[u8],
-                   p: &[u8],
-                   q: &[u8],
-                   dmp1: &[u8],
-                   dmq1: &[u8],
-                   iqmp: &[u8]) -> SgxError {
+    pub fn create2(
+        &self,
+        mod_size: i32,
+        exp_size: i32,
+        e: &[u8],
+        p: &[u8],
+        q: &[u8],
+        dmp1: &[u8],
+        dmq1: &[u8],
+        iqmp: &[u8],
+    ) -> SgxError {
         if self.createflag.get() {
             return Ok(());
         }
 
-        let ret = rsgx_create_rsa_priv2_key(mod_size,
-                                            exp_size,
-                                            e,
-                                            p,
-                                            q,
-                                            dmp1,
-                                            dmq1,
-                                            iqmp,
-                                            self.key.borrow_mut().deref_mut());
+        let ret = rsgx_create_rsa_priv2_key(
+            mod_size,
+            exp_size,
+            e,
+            p,
+            q,
+            dmp1,
+            dmq1,
+            iqmp,
+            self.key.borrow_mut().deref_mut(),
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 self.mod_size.set(mod_size);
                 self.exp_size.set(exp_size);
                 self.createflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
 
-    pub fn create1(&self,
-                   mod_size: i32,
-                   exp_size: i32,
-                   priv_exp_size: i32,
-                   n: &[u8],
-                   e: &[u8],
-                   d: &[u8]) -> SgxError {
+    pub fn create1(
+        &self,
+        mod_size: i32,
+        exp_size: i32,
+        priv_exp_size: i32,
+        n: &[u8],
+        e: &[u8],
+        d: &[u8],
+    ) -> SgxError {
         if self.createflag.get() {
             return Ok(());
         }
 
-        let ret = rsgx_create_rsa_priv1_key(mod_size,
-                                            exp_size,
-                                            priv_exp_size,
-                                            n,
-                                            e,
-                                            d,
-                                            self.key.borrow_mut().deref_mut());
+        let ret = rsgx_create_rsa_priv1_key(
+            mod_size,
+            exp_size,
+            priv_exp_size,
+            n,
+            e,
+            d,
+            self.key.borrow_mut().deref_mut(),
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 self.mod_size.set(mod_size);
                 self.exp_size.set(exp_size);
                 self.createflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
 
-    pub fn decrypt_sha256(&self,
-                          out_data: &mut [u8],
-                          out_len: &mut usize,
-                          in_data: &[u8]) -> SgxError {
+    pub fn decrypt_sha256(
+        &self,
+        out_data: &mut [u8],
+        out_len: &mut usize,
+        in_data: &[u8],
+    ) -> SgxError {
         if !self.createflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
 
-        let ret = rsgx_rsa_priv_decrypt_sha256(*self.key.borrow(),
-                                               out_data,
-                                               out_len,
-                                               in_data);
+        let ret = rsgx_rsa_priv_decrypt_sha256(
+            *self.key.borrow(),
+            out_data,
+            out_len,
+            in_data,
+        );
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                Ok(())
-            },
+            sgx_status_t::SGX_SUCCESS => Ok(()),
             _ => Err(ret),
         }
     }
@@ -3167,10 +3316,12 @@ impl SgxRsaPrivKey {
             if key.is_null() {
                 sgx_status_t::SGX_SUCCESS
             } else {
-                rsgx_free_rsa_key(key,
-                                  sgx_rsa_key_type_t::SGX_RSA_PRIVATE_KEY,
-                                  self.mod_size.get(),
-                                  self.exp_size.get())
+                rsgx_free_rsa_key(
+                    key,
+                    sgx_rsa_key_type_t::SGX_RSA_PRIVATE_KEY,
+                    self.mod_size.get(),
+                    self.exp_size.get(),
+                )
             }
         };
 
@@ -3179,7 +3330,7 @@ impl SgxRsaPrivKey {
                 self.createflag.set(false);
                 *self.key.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -3205,8 +3356,7 @@ pub struct SgxRsaPubKey {
 }
 
 impl SgxRsaPubKey {
-
-    pub fn new() -> Self {
+    pub fn new() -> SgxRsaPubKey {
         SgxRsaPubKey {
             key: RefCell::new(ptr::null_mut() as sgx_rsa_key_t),
             mod_size: Cell::new(0),
@@ -3215,47 +3365,53 @@ impl SgxRsaPubKey {
         }
     }
 
-    pub fn create(&self,
-                  mod_size: i32,
-                  exp_size: i32,
-                  n: &[u8],
-                  e: &[u8]) -> SgxError {
+    pub fn create(
+        &self,
+        mod_size: i32,
+        exp_size: i32,
+        n: &[u8],
+        e: &[u8],
+    ) -> SgxError {
         if self.createflag.get() {
             return Ok(());
         }
 
-        let ret = rsgx_create_rsa_pub1_key(mod_size,
-                                           exp_size,
-                                           n,
-                                           e,
-                                           self.key.borrow_mut().deref_mut());
+        let ret = rsgx_create_rsa_pub1_key(
+            mod_size,
+            exp_size,
+            n,
+            e,
+            self.key.borrow_mut().deref_mut(),
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 self.mod_size.set(mod_size);
                 self.exp_size.set(exp_size);
                 self.createflag.set(true);
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
 
-    pub fn encrypt_sha256(&self,
-                          out_data: &mut [u8],
-                          out_len: &mut usize,
-                          in_data: &[u8]) -> SgxError {
+    pub fn encrypt_sha256(
+        &self,
+        out_data: &mut [u8],
+        out_len: &mut usize,
+        in_data: &[u8],
+    ) -> SgxError {
         if !self.createflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
 
-        let ret = rsgx_rsa_pub_encrypt_sha256(*self.key.borrow(),
-                                              out_data,
-                                              out_len,
-                                              in_data);
+        let ret = rsgx_rsa_pub_encrypt_sha256(
+            *self.key.borrow(),
+            out_data,
+            out_len,
+            in_data,
+        );
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                Ok(())
-            },
+            sgx_status_t::SGX_SUCCESS => Ok(()),
             _ => Err(ret),
         }
     }
@@ -3270,10 +3426,12 @@ impl SgxRsaPubKey {
             if key.is_null() {
                 sgx_status_t::SGX_SUCCESS
             } else {
-                rsgx_free_rsa_key(key,
-                                  sgx_rsa_key_type_t::SGX_RSA_PUBLIC_KEY,
-                                  self.mod_size.get(),
-                                  self.exp_size.get())
+                rsgx_free_rsa_key(
+                    key,
+                    sgx_rsa_key_type_t::SGX_RSA_PUBLIC_KEY,
+                    self.mod_size.get(),
+                    self.exp_size.get(),
+                )
             }
         };
 
@@ -3282,7 +3440,7 @@ impl SgxRsaPubKey {
                 self.createflag.set(false);
                 *self.key.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -3335,9 +3493,11 @@ impl Drop for SgxRsaPubKey {
 ///
 /// Unexpected error occurred during the ECDSA private key generation.
 ///
-pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
-                                     sgx_nistp256_r_m1: &[u8],
-                                     out_key: &mut [u8]) -> SgxError {
+pub fn rsgx_calculate_ecdsa_priv_key(
+    hash_drg: &[u8],
+    sgx_nistp256_r_m1: &[u8],
+    out_key: &mut [u8],
+) -> SgxError {
     if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
@@ -3349,12 +3509,14 @@ pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
     }
 
     let ret = unsafe {
-        sgx_calculate_ecdsa_priv_key(hash_drg.as_ptr(),
-                                     hash_drg.len() as i32,
-                                     sgx_nistp256_r_m1.as_ptr(),
-                                     sgx_nistp256_r_m1.len() as i32,
-                                     out_key.as_mut_ptr(),
-                                     out_key.len() as i32)
+        sgx_calculate_ecdsa_priv_key(
+            hash_drg.as_ptr(),
+            hash_drg.len() as i32,
+            sgx_nistp256_r_m1.as_ptr(),
+            sgx_nistp256_r_m1.len() as i32,
+            out_key.as_mut_ptr(),
+            out_key.len() as i32,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -3362,11 +3524,15 @@ pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
     }
 }
 
-pub fn rsgx_ecc256_calculate_pub_from_priv(priv_key: &sgx_ec256_private_t,
-                                           pub_key: &mut sgx_ec256_public_t) -> SgxError {
+pub fn rsgx_ecc256_calculate_pub_from_priv(
+    priv_key: &sgx_ec256_private_t,
+    pub_key: &mut sgx_ec256_public_t,
+) -> SgxError {
     let ret = unsafe {
-        sgx_ecc256_calculate_pub_from_priv(priv_key as *const sgx_ec256_private_t,
-                                           pub_key as *mut sgx_ec256_public_t)
+        sgx_ecc256_calculate_pub_from_priv(
+            priv_key as *const sgx_ec256_private_t,
+            pub_key as *mut sgx_ec256_public_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -3384,12 +3550,14 @@ pub fn rsgx_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxRes
 
     let mut priv_key = sgx_ec256_private_t::default();
     let ret = unsafe {
-        sgx_calculate_ecdsa_priv_key(hash_drg.as_ptr(),
-                                     hash_drg.len() as i32,
-                                     sgx_nistp256_r_m1.as_ptr(),
-                                     sgx_nistp256_r_m1.len() as i32,
-                                     &mut priv_key as *mut sgx_ec256_private_t as *mut u8,
-                                     mem::size_of::<sgx_ec256_private_t>() as i32)
+        sgx_calculate_ecdsa_priv_key(
+            hash_drg.as_ptr(),
+            hash_drg.len() as i32,
+            sgx_nistp256_r_m1.as_ptr(),
+            sgx_nistp256_r_m1.len() as i32,
+            &mut priv_key as *mut sgx_ec256_private_t as *mut u8,
+            mem::size_of::<sgx_ec256_private_t>() as i32,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(priv_key),
@@ -3407,12 +3575,14 @@ pub fn rsgx_align_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) ->
 
     let mut align_priv_key = sgx_align_ec256_private_t::default();
     let ret = unsafe {
-        sgx_calculate_ecdsa_priv_key(hash_drg.as_ptr(),
-                                     hash_drg.len() as i32,
-                                     sgx_nistp256_r_m1.as_ptr(),
-                                     sgx_nistp256_r_m1.len() as i32,
-                                     &mut align_priv_key.key as *mut sgx_ec256_private_t as *mut u8,
-                                     mem::size_of::<sgx_ec256_private_t>() as i32)
+        sgx_calculate_ecdsa_priv_key(
+            hash_drg.as_ptr(),
+            hash_drg.len() as i32,
+            sgx_nistp256_r_m1.as_ptr(),
+            sgx_nistp256_r_m1.len() as i32,
+            &mut align_priv_key.key as *mut sgx_ec256_private_t as *mut u8,
+            mem::size_of::<sgx_ec256_private_t>() as i32,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_priv_key),
@@ -3423,8 +3593,10 @@ pub fn rsgx_align_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) ->
 pub fn rsgx_ecc256_pub_from_priv(priv_key: &sgx_ec256_private_t) -> SgxResult<sgx_ec256_public_t> {
     let mut pub_key = sgx_ec256_public_t::default();
     let ret = unsafe {
-        sgx_ecc256_calculate_pub_from_priv(priv_key as *const sgx_ec256_private_t,
-                                           &mut pub_key as *mut sgx_ec256_public_t)
+        sgx_ecc256_calculate_pub_from_priv(
+            priv_key as *const sgx_ec256_private_t,
+            &mut pub_key as *mut sgx_ec256_public_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(pub_key),
@@ -3432,10 +3604,12 @@ pub fn rsgx_ecc256_pub_from_priv(priv_key: &sgx_ec256_private_t) -> SgxResult<sg
     }
 }
 
-fn rsgx_aes_gcm128_enc_init(key: &sgx_aes_gcm_128bit_key_t,
-                            iv: &[u8],
-                            aad: &[u8],
-                            aes_gcm_state: &mut sgx_aes_state_handle_t) -> sgx_status_t {
+fn rsgx_aes_gcm128_enc_init(
+    key: &sgx_aes_gcm_128bit_key_t,
+    iv: &[u8],
+    aad: &[u8],
+    aes_gcm_state: &mut sgx_aes_state_handle_t,
+) -> sgx_status_t {
     let iv_len = iv.len();
     if iv_len != SGX_AESGCM_IV_SIZE {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -3447,18 +3621,22 @@ fn rsgx_aes_gcm128_enc_init(key: &sgx_aes_gcm_128bit_key_t,
 
     unsafe {
         let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
-        sgx_aes_gcm128_enc_init(key as *const sgx_aes_gcm_128bit_key_t as *const u8,
-                                iv.as_ptr(),
-                                iv_len as u32,
-                                p_aad,
-                                aad_len as u32,
-                                aes_gcm_state as *mut sgx_aes_state_handle_t)
-    }
-}
-
-fn rsgx_aes_gcm128_enc_update(src: &[u8],
-                              dst: &mut [u8],
-                              aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
+        sgx_aes_gcm128_enc_init(
+            key as *const sgx_aes_gcm_128bit_key_t as *const u8,
+            iv.as_ptr(),
+            iv_len as u32,
+            p_aad,
+            aad_len as u32,
+            aes_gcm_state as *mut sgx_aes_state_handle_t,
+        )
+    }
+}
+
+fn rsgx_aes_gcm128_enc_update(
+    src: &[u8],
+    dst: &mut [u8],
+    aes_gcm_state: sgx_aes_state_handle_t,
+) -> sgx_status_t {
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
@@ -3475,15 +3653,19 @@ fn rsgx_aes_gcm128_enc_update(src: &[u8],
     }
 
     unsafe {
-        sgx_aes_gcm128_enc_update(src.as_ptr(),
-                                  src_len as u32,
-                                  dst.as_mut_ptr(),
-                                  aes_gcm_state)
+        sgx_aes_gcm128_enc_update(
+            src.as_ptr(),
+            src_len as u32,
+            dst.as_mut_ptr(),
+            aes_gcm_state,
+        )
     }
 }
 
-fn rsgx_aes_gcm128_enc_get_mac(mac: &mut sgx_aes_gcm_128bit_tag_t,
-                               aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
+fn rsgx_aes_gcm128_enc_get_mac(
+    mac: &mut sgx_aes_gcm_128bit_tag_t,
+    aes_gcm_state: sgx_aes_state_handle_t,
+) -> sgx_status_t {
     unsafe {
         sgx_aes_gcm128_enc_get_mac(mac as *mut sgx_aes_gcm_128bit_tag_t as *mut u8, aes_gcm_state)
     }
@@ -3499,12 +3681,11 @@ pub struct SgxAesHandle {
 }
 
 impl SgxAesHandle {
-
-    pub fn new() -> Self {
+    pub fn new() -> SgxAesHandle {
         SgxAesHandle{
             handle: RefCell::new(ptr::null_mut() as sgx_aes_state_handle_t),
             initflag: Cell::new(false),
-            }
+        }
     }
 
     pub fn init(&self, key: &sgx_aes_gcm_128bit_key_t, iv: &[u8], aad: &[u8]) -> SgxError {
@@ -3571,7 +3752,7 @@ impl SgxAesHandle {
                 self.initflag.set(false);
                 *self.handle.borrow_mut() = ptr::null_mut();
                 Ok(())
-            },
+            }
             _ => Err(ret),
         }
     }
@@ -3588,3 +3769,4 @@ impl Drop for SgxAesHandle {
        let _ = self.close();
     }
 }
+
diff --git a/sgx_tcrypto_helper/Cargo.toml b/sgx_tcrypto_helper/Cargo.toml
index 2e3f71a..c91bd8e 100644
--- a/sgx_tcrypto_helper/Cargo.toml
+++ b/sgx_tcrypto_helper/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tcrypto_helper"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tdh/Cargo.toml b/sgx_tdh/Cargo.toml
index e7f3f8f..5e32f0d 100644
--- a/sgx_tdh/Cargo.toml
+++ b/sgx_tdh/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tdh"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tdh/src/dh.rs b/sgx_tdh/src/dh.rs
index c5f822e..b324cc6 100644
--- a/sgx_tdh/src/dh.rs
+++ b/sgx_tdh/src/dh.rs
@@ -55,7 +55,7 @@ impl SgxDhMsg3 {
     ///
     /// Create a SgxDhMsg3 with default values.
     ///
-    pub fn new() -> Self {
+    pub fn new() -> SgxDhMsg3 {
         SgxDhMsg3::default()
     }
 
@@ -67,7 +67,6 @@ impl SgxDhMsg3 {
     /// The size of sgx_dh_msg3_t needed.
     ///
     pub fn calc_raw_sealed_data_size(&self) -> u32 {
-
         let max = u32::max_value();
         let dh_msg3_size = mem::size_of::<sgx_dh_msg3_t>();
         let additional_prop_len = self.msg3_body.additional_prop.len();
@@ -103,7 +102,6 @@ impl SgxDhMsg3 {
     /// The parameters p and len are not available for the conversion.
     ///
     pub unsafe fn to_raw_dh_msg3_t(&self, p: *mut sgx_dh_msg3_t, len: u32) -> Option<*mut sgx_dh_msg3_t> {
-
         if p.is_null() {
             return None;
         }
@@ -155,8 +153,7 @@ impl SgxDhMsg3 {
     ///
     /// The parameters p and len are not available for the conversion.
     ///
-    pub unsafe fn from_raw_dh_msg3_t(p: *mut sgx_dh_msg3_t, len: u32) -> Option<Self> {
-
+    pub unsafe fn from_raw_dh_msg3_t(p: *mut sgx_dh_msg3_t, len: u32) -> Option<SgxDhMsg3> {
         if p.is_null() {
             return None;
         }
@@ -209,7 +206,7 @@ pub struct SgxDhResponder {
 }
 
 impl Default for SgxDhResponder {
-    fn default() -> Self {
+    fn default() -> SgxDhResponder {
         SgxDhResponder {
            state: SgxDhSessionState::SGX_DH_SESSION_STATE_RESET,
            prv_key: sgx_align_ec256_private_t::default(),
@@ -234,7 +231,7 @@ impl SgxDhResponder {
     ///
     /// Library: libsgx_tservice.a or libsgx_tservice_sim.a (simulation)
     ///
-    pub fn init_session() -> Self {
+    pub fn init_session() -> SgxDhResponder {
         Self::default()
     }
     ///
@@ -272,7 +269,6 @@ impl SgxDhResponder {
     /// An unexpected error occurred.
     ///
     pub fn gen_msg1(&mut self, msg1: &mut SgxDhMsg1) -> SgxError {
-
         if !rsgx_data_is_within_enclave(self) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
@@ -364,12 +360,13 @@ impl SgxDhResponder {
     ///
     /// An unexpected error occurred.
     ///
-    pub fn proc_msg2(&mut self,
-                     msg2: &SgxDhMsg2,
-                     msg3: &mut SgxDhMsg3,
-                     aek: &mut sgx_key_128bit_t,
-                     initiator_identity: &mut sgx_dh_session_enclave_identity_t) -> SgxError {
-
+    pub fn proc_msg2(
+        &mut self,
+        msg2: &SgxDhMsg2,
+        msg3: &mut SgxDhMsg3,
+        aek: &mut sgx_key_128bit_t,
+        initiator_identity: &mut sgx_dh_session_enclave_identity_t,
+    ) -> SgxError {
         if !rsgx_data_is_within_enclave(self) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
@@ -426,7 +423,6 @@ impl SgxDhResponder {
     }
 
     fn dh_generate_message1(&mut self, msg1: &mut SgxDhMsg1) -> SgxError {
-
         msg1.target = Default::default();
         msg1.g_a = Default::default();
 
@@ -449,7 +445,6 @@ impl SgxDhResponder {
     }
 
     fn dh_verify_message2(&self, msg2: &SgxDhMsg2) -> SgxError {
-
         let kdf_id = &msg2.report.body.report_data.d[SGX_SHA256_HASH_SIZE..SGX_SHA256_HASH_SIZE + 2];
         let data_hash = &msg2.report.body.report_data.d[..SGX_SHA256_HASH_SIZE];
 
@@ -479,7 +474,6 @@ impl SgxDhResponder {
     }
 
     fn lav2_verify_message2(&self, msg2: &SgxDhMsg2) -> SgxError {
-
         let sha_handle = SgxShaHandle::new();
         sha_handle.init()?;
         sha_handle.update_msg(&msg2.report.body.report_data)?;
@@ -505,7 +499,6 @@ impl SgxDhResponder {
     }
 
     fn dh_generate_message3(&self, msg2: &SgxDhMsg2, msg3: &mut SgxDhMsg3) -> SgxError {
-
         msg3.cmac = Default::default();
         msg3.msg3_body.report = Default::default();
 
@@ -537,7 +530,6 @@ impl SgxDhResponder {
     }
 
     fn lav2_generate_message3(&self, msg2: &SgxDhMsg2, msg3: &mut SgxDhMsg3) -> SgxError {
-
         msg3.cmac = Default::default();
         msg3.msg3_body.report = Default::default();
 
@@ -568,7 +560,6 @@ impl SgxDhResponder {
     }
 
     fn set_error(&mut self, sgx_ret: sgx_status_t) -> sgx_status_t {
-
         *self = Self::default();
         self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
         match sgx_ret {
@@ -590,7 +581,7 @@ pub struct SgxDhInitiator {
 }
 
 impl Default for SgxDhInitiator {
-    fn default() -> Self {
+    fn default() -> SgxDhInitiator {
         SgxDhInitiator {
            state: SgxDhSessionState::SGX_DH_SESSION_INITIATOR_WAIT_M1,
            smk_aek: sgx_align_key_128bit_t::default(),
@@ -615,7 +606,7 @@ impl SgxDhInitiator {
     ///
     /// Library: libsgx_tservice.a or libsgx_tservice_sim.a (simulation)
     ///
-    pub fn init_session() -> Self {
+    pub fn init_session() -> SgxDhInitiator {
         Self::default()
     }
 
@@ -656,7 +647,6 @@ impl SgxDhInitiator {
     /// An unexpected error occurred.
     ///
     pub fn proc_msg1(&mut self, msg1: &SgxDhMsg1, msg2: &mut SgxDhMsg2) -> SgxError {
-
         if !rsgx_data_is_within_enclave(self) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
@@ -752,11 +742,12 @@ impl SgxDhInitiator {
     ///
     /// An unexpected error occurred.
     ///
-    pub fn proc_msg3(&mut self,
-                     msg3: &SgxDhMsg3,
-                     aek: &mut sgx_key_128bit_t,
-                     responder_identity: &mut sgx_dh_session_enclave_identity_t) -> SgxError {
-
+    pub fn proc_msg3(
+        &mut self,
+        msg3: &SgxDhMsg3,
+        aek: &mut sgx_key_128bit_t,
+        responder_identity: &mut sgx_dh_session_enclave_identity_t,
+    ) -> SgxError {
         if !rsgx_data_is_within_enclave(self) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
@@ -804,7 +795,6 @@ impl SgxDhInitiator {
     }
 
     fn dh_generate_message2(&self, msg1: &SgxDhMsg1, msg2: &mut SgxDhMsg2) -> SgxError {
-
         msg2.report = Default::default();
         msg2.cmac = Default::default();
         msg2.g_b = self.pub_key;
@@ -828,7 +818,6 @@ impl SgxDhInitiator {
     }
 
     fn lav2_generate_message2(&self, msg1: &SgxDhMsg1, msg2: &mut SgxDhMsg2) -> SgxError {
-
         msg2.report = Default::default();
         msg2.cmac = Default::default();
         msg2.g_b = self.pub_key;
@@ -852,7 +841,6 @@ impl SgxDhInitiator {
     }
 
     fn dh_verify_message3(&self, msg3: &SgxDhMsg3) -> SgxError {
-
         let add_prop_len = msg3.msg3_body.additional_prop.len() as u32;
 
         let cmac_handle = SgxCmacHandle::new();
@@ -885,7 +873,6 @@ impl SgxDhInitiator {
     }
 
     fn lav2_verify_message3(&self, msg3: &SgxDhMsg3) -> SgxError {
-
         let sha_handle = SgxShaHandle::new();
         sha_handle.init()?;
         sha_handle.update_msg(&self.peer_pub_key)?;
@@ -918,7 +905,6 @@ impl SgxDhInitiator {
     }
 
     fn set_error(&mut self, sgx_ret: sgx_status_t) -> sgx_status_t {
-
         *self = Self::default();
         self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
         match sgx_ret {
@@ -928,7 +914,6 @@ impl SgxDhInitiator {
     }
 }
 
-
 #[derive(Copy, Clone, Default)]
 struct SgxLAv2ProtoSpec {
     signature: [u8; 6],
@@ -940,12 +925,11 @@ struct SgxLAv2ProtoSpec {
 unsafe impl ContiguousMemory for SgxLAv2ProtoSpec {}
 
 impl SgxLAv2ProtoSpec {
-
     pub unsafe fn to_report_data(&self) -> sgx_report_data_t {
         mem::transmute::<SgxLAv2ProtoSpec, sgx_report_data_t>(*self)
     }
 
-    pub unsafe fn from_report_data(data: &sgx_report_data_t) -> Self {
+    pub unsafe fn from_report_data(data: &sgx_report_data_t) -> SgxLAv2ProtoSpec {
         mem::transmute::<sgx_report_data_t, SgxLAv2ProtoSpec>(*data)
     }
 
@@ -958,7 +942,6 @@ impl SgxLAv2ProtoSpec {
     }
 
     pub fn make_target_info(&self, rpt: &sgx_report_t, ti: &mut sgx_target_info_t) -> SgxError {
-
         if !self.is_valid() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
@@ -969,7 +952,6 @@ impl SgxLAv2ProtoSpec {
 
         let mut to: i32 = 0;
         for i in 1..(self.ts_count() + 1) as usize {
-
             let size: i32 = 1 << (self.target_spec[i] & 0xF);
             to += size - 1;
             to &= -size;
@@ -1013,8 +995,7 @@ const SGX_LAV2_PROTO_SPEC: SgxLAv2ProtoSpec = SgxLAv2ProtoSpec {
 };
 
 pub fn rsgx_self_target() -> SgxResult<sgx_target_info_t> {
-
     let mut target_info = sgx_target_info_t::default();
     let report = rsgx_self_report();
     SGX_LAV2_PROTO_SPEC.make_target_info(&report, &mut target_info).map(|_| target_info)
-}
\ No newline at end of file
+}
diff --git a/sgx_tdh/src/ecp.rs b/sgx_tdh/src/ecp.rs
index dbf5409..15ef460 100644
--- a/sgx_tdh/src/ecp.rs
+++ b/sgx_tdh/src/ecp.rs
@@ -18,16 +18,16 @@
 use sgx_types::*;
 use sgx_tcrypto::*;
 
-
 pub const EC_LABEL_LENGTH: usize = 3;
 pub const EC_SMK_LABEL: [u8; EC_LABEL_LENGTH] = [0x53, 0x4D, 0x4B];
 pub const EC_AEK_LABEL: [u8; EC_LABEL_LENGTH] = [0x41, 0x45, 0x4B];
 pub const EC_DERIVATION_BUFFER_SIZE: usize = 7;
 
 #[allow(clippy::trivially_copy_pass_by_ref)]
-pub fn derive_key(shared_key: &sgx_ec256_dh_shared_t,
-                  label: &[u8; EC_LABEL_LENGTH]) -> SgxResult<sgx_align_key_128bit_t> {
-
+pub fn derive_key(
+    shared_key: &sgx_ec256_dh_shared_t,
+    label: &[u8; EC_LABEL_LENGTH],
+) -> SgxResult<sgx_align_key_128bit_t> {
     let cmac_key = sgx_cmac_128bit_key_t::default();
     let mut key_derive_key = rsgx_rijndael128_cmac_msg(&cmac_key, shared_key).map_err(set_error)?;
 
@@ -58,3 +58,4 @@ fn set_error(sgx_ret: sgx_status_t) -> sgx_status_t {
         _ => sgx_status_t::SGX_ERROR_UNEXPECTED,
     }
 }
+
diff --git a/sgx_tdh/src/lib.rs b/sgx_tdh/src/lib.rs
index 6af096a..007656a 100644
--- a/sgx_tdh/src/lib.rs
+++ b/sgx_tdh/src/lib.rs
@@ -40,5 +40,3 @@ mod dh;
 pub use self::dh::*;
 
 mod ecp;
-
-
diff --git a/sgx_tkey_exchange/Cargo.toml b/sgx_tkey_exchange/Cargo.toml
index b83b0bc..57cbe72 100644
--- a/sgx_tkey_exchange/Cargo.toml
+++ b/sgx_tkey_exchange/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tkey_exchange"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tkey_exchange/src/lib.rs b/sgx_tkey_exchange/src/lib.rs
index a039fa3..e05ad9e 100644
--- a/sgx_tkey_exchange/src/lib.rs
+++ b/sgx_tkey_exchange/src/lib.rs
@@ -141,15 +141,19 @@ pub fn rsgx_ra_init(p_pub_key: &sgx_ec256_public_t, b_pse: i32) -> SgxResult<sgx
 ///
 /// Indicates that an unexpected error occurred.
 ///
-pub fn rsgx_ra_init_ex(p_pub_key: &sgx_ec256_public_t,
-                       b_pse: i32,
-                       derive_key_cb: sgx_ra_derive_secret_keys_t) -> SgxResult<sgx_ra_context_t> {
+pub fn rsgx_ra_init_ex(
+    p_pub_key: &sgx_ec256_public_t,
+    b_pse: i32,
+    derive_key_cb: sgx_ra_derive_secret_keys_t,
+) -> SgxResult<sgx_ra_context_t> {
     let mut context: sgx_ra_context_t = 0;
     let ret = unsafe {
-        sgx_ra_init_ex(p_pub_key as *const sgx_ec256_public_t,
-                       b_pse,
-                       derive_key_cb,
-                       &mut context as *mut sgx_ra_context_t)
+        sgx_ra_init_ex(
+            p_pub_key as *const sgx_ec256_public_t,
+            b_pse,
+            derive_key_cb,
+            &mut context as *mut sgx_ra_context_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(context),
@@ -246,3 +250,4 @@ pub fn rsgx_ra_close(context: sgx_ra_context_t) -> SgxError {
         _ => Err(ret),
     }
 }
+
diff --git a/sgx_tprotected_fs/Cargo.toml b/sgx_tprotected_fs/Cargo.toml
index 28d8678..10c0526 100644
--- a/sgx_tprotected_fs/Cargo.toml
+++ b/sgx_tprotected_fs/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tprotected_fs"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tprotected_fs/src/fs.rs b/sgx_tprotected_fs/src/fs.rs
index 7cbb24e..93767e4 100644
--- a/sgx_tprotected_fs/src/fs.rs
+++ b/sgx_tprotected_fs/src/fs.rs
@@ -197,7 +197,6 @@ pub struct SgxFileStream {
 }
 
 impl SgxFileStream {
-
     ///
     /// The open function creates or opens a protected file.
     ///
diff --git a/sgx_trts/Cargo.toml b/sgx_trts/Cargo.toml
index c040996..010c0cc 100644
--- a/sgx_trts/Cargo.toml
+++ b/sgx_trts/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_trts"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_trts/src/ascii.rs b/sgx_trts/src/ascii.rs
index 9afd70e..9f12c3f 100644
--- a/sgx_trts/src/ascii.rs
+++ b/sgx_trts/src/ascii.rs
@@ -34,12 +34,12 @@
 use alloc::vec::Vec;
 use alloc::string::String;
 
-pub use core::ascii::{EscapeDefault, escape_default};
+pub use core::ascii::{escape_default, EscapeDefault};
 
 /// Extension methods for ASCII-subset only operations.
 ///
 /// Be aware that operations on seemingly non-ASCII characters can sometimes
-/// have unexpected results.
+/// have unexpected results. Consider this example:
 ///
 pub trait AsciiExt {
     /// Container type for copied ASCII characters.
diff --git a/sgx_trts/src/c_str.rs b/sgx_trts/src/c_str.rs
index 914cd5a..8e55c92 100644
--- a/sgx_trts/src/c_str.rs
+++ b/sgx_trts/src/c_str.rs
@@ -27,14 +27,13 @@ use sgx_types::c_char;
 use crate::libc;
 use crate::memchr;
 use crate::ascii;
-//use error::Error;
-//use io;
 
 use core::ops;
 use core::cmp::Ordering;
 use core::mem;
 use core::ptr;
 use core::fmt::{self, Write};
+use core::num::NonZeroU8;
 use alloc::boxed::Box;
 use alloc::borrow::{Cow, Borrow, ToOwned};
 use alloc::vec::Vec;
@@ -78,7 +77,7 @@ pub struct CStr {
     //        just a raw `c_char` along with some form of marker to make
     //        this an unsized type. Essentially `sizeof(&CStr)` should be the
     //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
-    inner: [c_char]
+    inner: [c_char],
 }
 
 /// An error indicating that an interior nul byte was found.
@@ -126,22 +125,18 @@ enum FromBytesWithNulErrorKind {
 
 impl FromBytesWithNulError {
     fn interior_nul(pos: usize) -> FromBytesWithNulError {
-        FromBytesWithNulError {
-            kind: FromBytesWithNulErrorKind::InteriorNul(pos),
-        }
+        FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
     }
     fn not_nul_terminated() -> FromBytesWithNulError {
-        FromBytesWithNulError {
-            kind: FromBytesWithNulErrorKind::NotNulTerminated,
-        }
+        FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
     }
 
     pub fn __description(&self) -> &str {
         match self.kind {
-            FromBytesWithNulErrorKind::InteriorNul(..) =>
-                "data provided contains an interior nul byte",
-            FromBytesWithNulErrorKind::NotNulTerminated =>
-                "data provided is not nul terminated",
+            FromBytesWithNulErrorKind::InteriorNul(..) => {
+                "data provided contains an interior nul byte"
+            }
+            FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
         }
     }
 }
@@ -180,7 +175,7 @@ impl IntoStringError {
         "C string contained non-utf8 bytes"
     }
 
-    pub fn __cause(&self) -> &Utf8Error {
+    pub fn __source(&self) -> &Utf8Error {
         &self.error
     }
 }
@@ -202,7 +197,31 @@ impl CString {
     /// contain any 0 bytes in it.
     ///
     pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
-        Self::_new(t.into())
+        trait SpecIntoVec {
+            fn into_vec(self) -> Vec<u8>;
+        }
+        impl<T: Into<Vec<u8>>> SpecIntoVec for T {
+            default fn into_vec(self) -> Vec<u8> {
+                self.into()
+            }
+        }
+        // Specialization for avoiding reallocation.
+        impl SpecIntoVec for &'_ [u8] {
+            fn into_vec(self) -> Vec<u8> {
+                let mut v = Vec::with_capacity(self.len() + 1);
+                v.extend(self);
+                v
+            }
+        }
+        impl SpecIntoVec for &'_ str {
+            fn into_vec(self) -> Vec<u8> {
+                let mut v = Vec::with_capacity(self.len() + 1);
+                v.extend(self.as_bytes());
+                v
+            }
+        }
+
+        Self::_new(SpecIntoVec::into_vec(t))
     }
 
     fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
@@ -219,6 +238,8 @@ impl CString {
     /// is made that `v` contains no 0 bytes, and it requires an actual
     /// byte vector, not anything that can be converted to one with Into.
     ///
+    /// [`new`]: #method.new
+    ///
     pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
         v.reserve_exact(1);
         v.push(0);
@@ -232,7 +253,7 @@ impl CString {
     /// # Safety
     ///
     /// This should only ever be called with a pointer that was earlier
-    /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g. trying to take
+    /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take
     /// ownership of a string that was allocated by foreign code) is likely to lead
     /// to undefined behavior or allocator corruption.
     ///
@@ -242,6 +263,9 @@ impl CString {
     /// > make your own provisions for freeing it appropriately, likely
     /// > with the foreign code's API to do that.
     ///
+    /// [`into_raw`]: #method.into_raw
+    /// [`CStr`]: struct.CStr.html
+    ///
     pub unsafe fn from_raw(ptr: *mut c_char) -> CString {
         let len = libc::strlen(ptr) + 1; // Including the NUL byte
         let slice = slice::from_raw_parts_mut(ptr, len as usize);
@@ -256,6 +280,10 @@ impl CString {
     /// this string.
     ///
     /// Failure to call [`from_raw`] will lead to a memory leak.
+    ///
+    /// [`from_raw`]: #method.from_raw
+    ///
+    #[inline]
     pub fn into_raw(self) -> *mut c_char {
         Box::into_raw(self.into_inner()) as *mut c_char
     }
@@ -263,12 +291,14 @@ impl CString {
     /// Converts the `CString` into a [`String`] if it contains valid UTF-8 data.
     ///
     /// On failure, ownership of the original `CString` is returned.
+    ///
+    /// [`String`]: ../string/struct.String.html
+    ///
     pub fn into_string(self) -> Result<String, IntoStringError> {
-        String::from_utf8(self.into_bytes())
-            .map_err(|e| IntoStringError {
-                error: e.utf8_error(),
-                inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
-            })
+        String::from_utf8(self.into_bytes()).map_err(|e| IntoStringError {
+            error: e.utf8_error(),
+            inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
+        })
     }
 
     /// Consumes the `CString` and returns the underlying byte buffer.
@@ -276,6 +306,7 @@ impl CString {
     /// The returned buffer does **not** contain the trailing nul
     /// terminator, and it is guaranteed to not have any interior nul
     /// bytes.
+    ///
     pub fn into_bytes(self) -> Vec<u8> {
         let mut vec = self.into_inner().into_vec();
         let _nul = vec.pop();
@@ -285,6 +316,9 @@ impl CString {
 
     /// Equivalent to the [`into_bytes`] function except that the returned vector
     /// includes the trailing nul terminator.
+    ///
+    /// [`into_bytes`]: #method.into_bytes
+    ///
     pub fn into_bytes_with_nul(self) -> Vec<u8> {
         self.into_inner().into_vec()
     }
@@ -295,22 +329,31 @@ impl CString {
     /// terminator, and it is guaranteed to not have any interior nul
     /// bytes. If you need the nul terminator, use
     /// [`as_bytes_with_nul`] instead.
+    ///
+    /// [`as_bytes_with_nul`]: #method.as_bytes_with_nul
+    ///
+    #[inline]
     pub fn as_bytes(&self) -> &[u8] {
         &self.inner[..self.inner.len() - 1]
     }
 
     /// Equivalent to the [`as_bytes`] function except that the returned slice
     /// includes the trailing nul terminator.
+    #[inline]
     pub fn as_bytes_with_nul(&self) -> &[u8] {
         &self.inner
     }
 
     /// Extracts a [`CStr`] slice containing the entire string.
+    #[inline]
     pub fn as_c_str(&self) -> &CStr {
         &*self
     }
 
     /// Converts this `CString` into a boxed [`CStr`].
+    ///
+    /// [`CStr`]: struct.CStr.html
+    ///
     pub fn into_boxed_c_str(self) -> Box<CStr> {
         unsafe { Box::from_raw(Box::into_raw(self.into_inner()) as *mut CStr) }
     }
@@ -329,12 +372,14 @@ impl CString {
 }
 
 // Turns this `CString` into an empty string to prevent
-// memory unsafe code from working by accident. Inline
+// memory-unsafe code from working by accident. Inline
 // to prevent LLVM from optimizing it away in debug builds.
 impl Drop for CString {
     #[inline]
     fn drop(&mut self) {
-        unsafe { *self.inner.get_unchecked_mut(0) = 0; }
+        unsafe {
+            *self.inner.get_unchecked_mut(0) = 0;
+        }
     }
 }
 
@@ -357,6 +402,9 @@ impl From<CString> for Vec<u8> {
     /// Converts a [`CString`] into a [`Vec`]`<u8>`.
     ///
     /// The conversion consumes the [`CString`], and removes the terminating NUL byte.
+    ///
+    /// [`Vec`]: ../vec/struct.Vec.html
+    /// [`CString`]: ../ffi/struct.CString.html
     #[inline]
     fn from(s: CString) -> Vec<u8> {
         s.into_bytes()
@@ -390,7 +438,9 @@ impl Default for CString {
 
 impl Borrow<CStr> for CString {
     #[inline]
-    fn borrow(&self) -> &CStr { self }
+    fn borrow(&self) -> &CStr {
+        self
+    }
 }
 
 impl<'a> From<Cow<'a, CStr>> for CString {
@@ -410,12 +460,39 @@ impl From<&CStr> for Box<CStr> {
 impl From<Box<CStr>> for CString {
     /// Converts a [`Box`]`<CStr>` into a [`CString`] without copying or allocating.
     ///
+    /// [`Box`]: ../boxed/struct.Box.html
+    /// [`CString`]: ../ffi/struct.CString.html
     #[inline]
     fn from(s: Box<CStr>) -> CString {
         s.into_c_string()
     }
 }
 
+impl From<Vec<NonZeroU8>> for CString {
+    /// Converts a [`Vec`]`<`[`NonZeroU8`]`>` into a [`CString`] without
+    /// copying nor checking for inner null bytes.
+    ///
+    /// [`CString`]: ../ffi/struct.CString.html
+    /// [`NonZeroU8`]: ../num/struct.NonZeroU8.html
+    /// [`Vec`]: ../vec/struct.Vec.html
+    #[inline]
+    fn from(v: Vec<NonZeroU8>) -> CString {
+        unsafe {
+            // Transmute `Vec<NonZeroU8>` to `Vec<u8>`.
+            let v: Vec<u8> = {
+                // Safety:
+                //   - transmuting between `NonZeroU8` and `u8` is sound;
+                //   - `alloc::Layout<NonZeroU8> == alloc::Layout<u8>`.
+                let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
+                Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
+            };
+            // Safety: `v` cannot contain null bytes, given the type-level
+            // invariant of `NonZeroU8`.
+            CString::from_vec_unchecked(v)
+        }
+    }
+}
+
 impl Clone for Box<CStr> {
     #[inline]
     fn clone(&self) -> Self {
@@ -426,6 +503,8 @@ impl Clone for Box<CStr> {
 impl From<CString> for Box<CStr> {
     /// Converts a [`CString`] into a [`Box`]`<CStr>` without copying or allocating.
     ///
+    /// [`CString`]: ../ffi/struct.CString.html
+    /// [`Box`]: ../boxed/struct.Box.html
     #[inline]
     fn from(s: CString) -> Box<CStr> {
         s.into_boxed_c_str()
@@ -456,6 +535,8 @@ impl<'a> From<&'a CString> for Cow<'a, CStr> {
 impl From<CString> for Arc<CStr> {
     /// Converts a [`CString`] into a [`Arc`]`<CStr>` without copying or allocating.
     ///
+    /// [`CString`]: ../ffi/struct.CString.html
+    /// [`Arc`]: ../sync/struct.Arc.html
     #[inline]
     fn from(s: CString) -> Arc<CStr> {
         let arc: Arc<[u8]> = Arc::from(s.into_inner());
@@ -474,6 +555,8 @@ impl From<&CStr> for Arc<CStr> {
 impl From<CString> for Rc<CStr> {
     /// Converts a [`CString`] into a [`Rc`]`<CStr>` without copying or allocating.
     ///
+    /// [`CString`]: ../ffi/struct.CString.html
+    /// [`Rc`]: ../rc/struct.Rc.html
     #[inline]
     fn from(s: CString) -> Rc<CStr> {
         let rc: Rc<[u8]> = Rc::from(s.into_inner());
@@ -500,17 +583,25 @@ impl NulError {
     /// Returns the position of the nul byte in the slice that caused
     /// [`CString::new`] to fail.
     ///
-    pub fn nul_position(&self) -> usize { self.0 }
+    /// [`CString::new`]: struct.CString.html#method.new
+    ///
+    pub fn nul_position(&self) -> usize {
+        self.0
+    }
 
     /// Consumes this error, returning the underlying vector of bytes which
     /// generated the error in the first place.
     ///
-    pub fn into_vec(self) -> Vec<u8> { self.1 }
+    pub fn into_vec(self) -> Vec<u8> {
+        self.1
+    }
 }
 
 impl IntoStringError {
     /// Consumes this error, returning original [`CString`] which generated the
     /// error.
+    ///
+    /// [`CString`]: struct.CString.html
     pub fn into_cstring(self) -> CString {
         self.inner
     }
@@ -525,8 +616,10 @@ impl CStr {
     /// Wraps a raw C string with a safe C string wrapper.
     ///
     /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
-    /// allows inspection and interoperation of non-owned C strings. This method
-    /// is unsafe for a number of reasons:
+    /// allows inspection and interoperation of non-owned C strings. The total
+    /// size of the raw C string must be smaller than `isize::MAX` **bytes**
+    /// in memory due to calling the `slice::from_raw_parts` function.
+    /// This method is unsafe for a number of reasons:
     ///
     /// * There is no guarantee to the validity of `ptr`.
     /// * The returned lifetime is not guaranteed to be the actual lifetime of
@@ -552,8 +645,7 @@ impl CStr {
     /// wrapper after ensuring that the byte slice is nul-terminated
     /// and does not contain any interior nul bytes.
     ///
-    pub fn from_bytes_with_nul(bytes: &[u8])
-                               -> Result<&CStr, FromBytesWithNulError> {
+    pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
         let nul_pos = memchr::memchr(0, bytes);
         if let Some(nul_pos) = nul_pos {
             if nul_pos + 1 != bytes.len() {
@@ -571,7 +663,7 @@ impl CStr {
     /// performing any sanity checks. The provided slice **must** be nul-terminated
     /// and not contain any interior nul bytes.
     ///
-    //#[rustc_const_unstable(feature = "const_cstr_unchecked")]
+    #[inline]
     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
         &*(bytes as *const [u8] as *const CStr)
     }
@@ -582,6 +674,7 @@ impl CStr {
     /// to a contiguous region of memory terminated with a 0 byte to represent
     /// the end of the string.
     ///
+    #[inline]
     pub const fn as_ptr(&self) -> *const c_char {
         self.inner.as_ptr()
     }
@@ -595,6 +688,7 @@ impl CStr {
     /// > cast, but it is planned to alter its definition in the future to
     /// > perform the length calculation whenever this method is called.
     ///
+    #[inline]
     pub fn to_bytes(&self) -> &[u8] {
         let bytes = self.to_bytes_with_nul();
         &bytes[..bytes.len() - 1]
@@ -611,6 +705,7 @@ impl CStr {
     ///
     /// [`to_bytes`]: #method.to_bytes
     ///
+    #[inline]
     pub fn to_bytes_with_nul(&self) -> &[u8] {
         unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
     }
@@ -621,16 +716,11 @@ impl CStr {
     /// function will return the corresponding [`&str`] slice. Otherwise,
     /// it will return an error with details of where UTF-8 validation failed.
     ///
-    /// > **Note**: This method is currently implemented to check for validity
-    /// > after a constant-time cast, but it is planned to alter its definition
-    /// > in the future to perform the length calculation in addition to the
-    /// > UTF-8 check whenever this method is called.
-    ///
     /// [`&str`]: ../primitive.str.html
     ///
     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
-        // NB: When CStr is changed to perform the length check in .to_bytes()
-        // instead of in from_ptr(), it may be worth considering if this should
+        // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
+        // instead of in `from_ptr()`, it may be worth considering if this should
         // be rewritten to do the UTF-8 check inline with the length calculation
         // instead of doing it afterwards.
         str::from_utf8(self.to_bytes())
@@ -645,11 +735,6 @@ impl CStr {
     /// [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD] and return a
     /// [`Cow`]`::`[`Owned`]`(`[`String`]`)` with the result.
     ///
-    /// > **Note**: This method is currently implemented to check for validity
-    /// > after a constant-time cast, but it is planned to alter its definition
-    /// > in the future to perform the length calculation in addition to the
-    /// > UTF-8 check whenever this method is called.
-    ///
     /// [`Cow`]: ../borrow/enum.Cow.html
     /// [`Borrowed`]: ../borrow/enum.Cow.html#variant.Borrowed
     /// [`Owned`]: ../borrow/enum.Cow.html#variant.Owned
@@ -698,6 +783,12 @@ impl ToOwned for CStr {
     fn to_owned(&self) -> CString {
         CString { inner: self.to_bytes_with_nul().into() }
     }
+
+    fn clone_into(&self, target: &mut CString) {
+        let mut b = Vec::from(mem::take(&mut target.inner));
+        self.to_bytes_with_nul().clone_into(&mut b);
+        target.inner = b.into_boxed_slice();
+    }
 }
 
 impl From<&CStr> for CString {
diff --git a/sgx_trts/src/enclave.rs b/sgx_trts/src/enclave.rs
index aa7c5f9..acc7f1f 100644
--- a/sgx_trts/src/enclave.rs
+++ b/sgx_trts/src/enclave.rs
@@ -20,13 +20,13 @@
 //! This mod has clear interface and is easy to understand. Currently we don't
 //! have time for its documents.
 
-use sgx_types::*;
 use sgx_types::metadata::*;
+use sgx_types::*;
 
-pub const LAYOUT_ENTRY_NUM : usize = 42;
+pub const LAYOUT_ENTRY_NUM: usize = 42;
 
 #[link(name = "sgx_trts")]
-extern {
+extern "C" {
     static g_global_data: global_data_t;
     static g_cpu_feature_indicator: uint64_t;
     static g_cpu_core_num: uint32_t;
@@ -41,6 +41,7 @@ extern {
 
 #[repr(C)]
 pub struct global_data_t {
+    pub sdk_version: usize,
     pub enclave_size: usize,
     pub heap_offset: usize,
     pub heap_size: usize,
@@ -86,7 +87,7 @@ pub struct SgxGlobalData {
     rsrv_offset: usize,
     rsrv_size: usize,
     thread_policy: SgxThreadPolicy,
-    static_tcs_num: u32,  // minpool thread + utility thread
+    static_tcs_num: u32, // minpool thread + utility thread
     eremove_tcs_num: u32,
     dyn_tcs_num: u32,
     max_tcs_num: u32,
@@ -99,7 +100,6 @@ impl Default for SgxGlobalData {
 }
 
 impl SgxGlobalData {
-
     ///
     /// get global_data.
     ///
@@ -110,19 +110,19 @@ impl SgxGlobalData {
     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: 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(),
         }
     }
 
@@ -261,7 +261,6 @@ pub struct SgxThreadData {
 }
 
 impl SgxThreadData {
-
     ///
     /// get thread_data per thread.
     ///
@@ -379,7 +378,7 @@ impl SgxThreadData {
 #[derive(Copy, Clone, PartialEq, Debug)]
 pub enum SgxThreadPolicy {
     Bound,
-    Unbound
+    Unbound,
 }
 
 ///
@@ -415,7 +414,7 @@ pub fn rsgx_get_enclave_base() -> *const u8 {
 ///
 #[inline]
 pub fn rsgx_get_enclave_size() -> usize {
-    unsafe{ g_global_data.enclave_size }
+    unsafe { g_global_data.enclave_size }
 }
 
 ///
@@ -439,7 +438,7 @@ pub fn rsgx_get_heap_base() -> *const u8 {
 ///
 #[inline]
 pub fn rsgx_get_heap_offset() -> usize {
-    unsafe{ g_global_data.heap_offset }
+    unsafe { g_global_data.heap_offset }
 }
 
 ///
@@ -475,7 +474,7 @@ pub fn rsgx_get_rsrv_base() -> *const u8 {
 ///
 #[inline]
 pub fn rsgx_get_rsrv_offset() -> usize {
-    unsafe{ g_global_data.rsrv_offset }
+    unsafe { g_global_data.rsrv_offset }
 }
 
 ///
@@ -542,10 +541,20 @@ pub fn rsgx_get_tcs_num() -> (u32, u32, u32) {
     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 {
+        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])
-    {
+    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 {
@@ -589,4 +598,4 @@ pub fn rsgx_get_cpu_feature() -> u64 {
 #[inline]
 pub fn rsgx_get_cpu_core_num() -> u32 {
     unsafe { g_cpu_core_num }
-}
\ No newline at end of file
+}
diff --git a/sgx_trts/src/lib.rs b/sgx_trts/src/lib.rs
index 45dbc42..d1611bb 100644
--- a/sgx_trts/src/lib.rs
+++ b/sgx_trts/src/lib.rs
@@ -68,13 +68,13 @@
 
 #![feature(allocator_api)]
 #![feature(asm)]
-//#![feature(rustc_const_unstable)]
 #![feature(const_raw_ptr_deref)]
-//#![feature(const_cstr_unchecked)]
 #![allow(non_camel_case_types)]
 #![allow(non_upper_case_globals)]
-#![allow(overflowing_literals)]
 #![allow(non_snake_case)]
+#![feature(specialization)]
+#![feature(vec_into_raw_parts)]
+#![feature(toowned_clone_into)]
 
 #[cfg(target_env = "sgx")]
 extern crate sgx_types;
diff --git a/sgx_trts/src/memchr.rs b/sgx_trts/src/memchr.rs
index a1bdb96..edda4d3 100644
--- a/sgx_trts/src/memchr.rs
+++ b/sgx_trts/src/memchr.rs
@@ -51,22 +51,20 @@ pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
 }
 
 pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
-
     fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option<usize> {
         // GNU's memrchr() will - unlike memchr() - error if haystack is empty.
-        if haystack.is_empty() {return None}
+        if haystack.is_empty() {
+            return None;
+        }
         let p = unsafe {
             sgx_libc::memrchr(
                 haystack.as_ptr(),
                 needle,
-                haystack.len())
+                haystack.len(),
+            )
         };
-        if p.is_null() {
-            None
-        } else {
-            Some(p as usize - (haystack.as_ptr() as usize))
-        }
+        if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) }
     }
 
     memrchr_specific(needle, haystack)
-}
+}
\ No newline at end of file
diff --git a/sgx_trts/src/memeq.rs b/sgx_trts/src/memeq.rs
index f52e624..05b3372 100644
--- a/sgx_trts/src/memeq.rs
+++ b/sgx_trts/src/memeq.rs
@@ -31,7 +31,9 @@ pub trait ConsttimeMemEq<T: BytewiseEquality + ?Sized = Self> {
 }
 
 impl<T> ConsttimeMemEq<[T]> for [T]
-    where T: Eq + BytewiseEquality {
+where
+    T: Eq + BytewiseEquality,
+{
     fn consttime_memeq(&self, other: &[T]) -> bool {
         if self.len() != other.len() {
             return false;
@@ -41,31 +43,39 @@ impl<T> ConsttimeMemEq<[T]> for [T]
         }
         let size = mem::size_of_val(self);
         unsafe {
-            consttime_memequal(self.as_ptr() as *const u8,
-                               other.as_ptr() as *const u8,
-                               size) != 0
+            consttime_memequal(
+                self.as_ptr() as *const u8,
+                other.as_ptr() as *const u8,
+                size,
+            ) != 0
         }
     }
 }
 
 impl<T> ConsttimeMemEq<T> for T
-    where T: Eq + BytewiseEquality {
+where
+    T: Eq + BytewiseEquality,
+{
     fn consttime_memeq(&self, other: &T) -> bool {
         let size = mem::size_of_val(self);
         if size == 0 {
             return true;
         }
         unsafe {
-            consttime_memequal(self as *const T as *const u8,
-                               other as *const T as *const u8,
-                               size) != 0
+            consttime_memequal(
+                self as *const T as *const u8,
+                other as *const T as *const u8,
+                size,
+            ) != 0
         }
     }
 }
 
-unsafe fn consttime_memequal(b1: *const u8,
-                             b2: *const u8,
-                             l: usize) -> i32 {
+unsafe fn consttime_memequal(
+    b1: *const u8,
+    b2: *const u8,
+    l: usize,
+) -> i32 {
     let mut res: u32 = 0;
     let mut len = l;
     let p1 = slice::from_raw_parts(b1, l);
diff --git a/sgx_trts/src/oom.rs b/sgx_trts/src/oom.rs
index e09a8dc..010b262 100644
--- a/sgx_trts/src/oom.rs
+++ b/sgx_trts/src/oom.rs
@@ -18,25 +18,34 @@
 use crate::trts;
 use core::sync::atomic::{AtomicPtr, Ordering};
 use core::mem;
+use core::ptr;
 use core::alloc::AllocErr;
 
-static SGX_OOM_HANDLER: AtomicPtr<()> = AtomicPtr::new(default_oom_handler as *mut ());
+static SGX_OOM_HANDLER: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
 
 #[allow(clippy::needless_pass_by_value)]
-fn default_oom_handler( _err: AllocErr) -> ! {
+fn default_oom_handler(_err: AllocErr) -> ! {
     trts::rsgx_abort()
 }
 
 pub fn rsgx_oom(err: AllocErr) -> ! {
-    let value = SGX_OOM_HANDLER.load(Ordering::SeqCst);
-    let handler: fn(AllocErr) -> ! = unsafe { mem::transmute(value) };
-    handler(err);
+    let hook = SGX_OOM_HANDLER.load(Ordering::SeqCst);
+    let handler: fn(AllocErr) -> ! =
+        if hook.is_null() { default_oom_handler } else { unsafe { mem::transmute(hook) } };
+    handler(err)
 }
 
 /// Set a custom handler for out-of-memory conditions
 ///
 /// To avoid recursive OOM failures, it is critical that the OOM handler does
 /// not allocate any memory itself.
-pub fn set_panic_handler(handler: fn(AllocErr) -> !) {
+pub fn set_oom_handler(handler: fn(AllocErr) -> !) {
     SGX_OOM_HANDLER.store(handler as *mut (), Ordering::SeqCst);
 }
+
+/// Unregisters the current custom handler, returning it.
+///
+pub fn take_oom_handler() -> fn(AllocErr) -> ! {
+    let hook = SGX_OOM_HANDLER.swap(ptr::null_mut(), Ordering::SeqCst);
+    if hook.is_null() { default_oom_handler } else { unsafe { mem::transmute(hook) } }
+}
diff --git a/sgx_tse/Cargo.toml b/sgx_tse/Cargo.toml
index a0b2162..b37bbc7 100644
--- a/sgx_tse/Cargo.toml
+++ b/sgx_tse/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tse"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tse/src/se.rs b/sgx_tse/src/se.rs
index e10950d..8a3b7a3 100644
--- a/sgx_tse/src/se.rs
+++ b/sgx_tse/src/se.rs
@@ -77,10 +77,11 @@ use sgx_types::*;
 pub fn rsgx_create_report(target_info: &sgx_target_info_t, report_data: &sgx_report_data_t) -> SgxResult<sgx_report_t> {
     let mut report = sgx_report_t::default();
     let ret = unsafe {
-        sgx_create_report(target_info as *const sgx_target_info_t,
-                          report_data as *const sgx_report_data_t,
-                          &mut report as *mut sgx_report_t)
-
+        sgx_create_report(
+            target_info as *const sgx_target_info_t,
+            report_data as *const sgx_report_data_t,
+            &mut report as *mut sgx_report_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(report),
@@ -192,7 +193,9 @@ pub fn rsgx_verify_report(report: &sgx_report_t) -> SgxError {
 ///
 pub fn rsgx_get_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_key_128bit_t> {
     let mut key = sgx_key_128bit_t::default();
-    let ret = unsafe { sgx_get_key(key_request as *const sgx_key_request_t, &mut key as *mut sgx_key_128bit_t) };
+    let ret = unsafe {
+        sgx_get_key(key_request as *const sgx_key_request_t, &mut key as *mut sgx_key_128bit_t)
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(key),
         _ => Err(ret),
@@ -201,7 +204,9 @@ pub fn rsgx_get_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_key_128bit
 
 pub fn rsgx_get_align_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_align_key_128bit_t> {
     let mut align_key = sgx_align_key_128bit_t::default();
-    let ret = unsafe { sgx_get_key(key_request as *const sgx_key_request_t, &mut align_key.key as *mut sgx_key_128bit_t) };
+    let ret = unsafe {
+        sgx_get_key(key_request as *const sgx_key_request_t, &mut align_key.key as *mut sgx_key_128bit_t)
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_key),
         _ => Err(ret),
@@ -210,4 +215,4 @@ pub fn rsgx_get_align_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_alig
 
 pub fn rsgx_self_report() -> sgx_report_t {
     unsafe { * sgx_self_report() }
-}
\ No newline at end of file
+}
diff --git a/sgx_tseal/Cargo.toml b/sgx_tseal/Cargo.toml
index 5ac6ace..cd04b2d 100644
--- a/sgx_tseal/Cargo.toml
+++ b/sgx_tseal/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tseal"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tseal/src/aad.rs b/sgx_tseal/src/aad.rs
index 40f236b..294c07d 100644
--- a/sgx_tseal/src/aad.rs
+++ b/sgx_tseal/src/aad.rs
@@ -51,7 +51,6 @@ impl<'a, T: 'a + Clone + ?Sized> Clone for SgxMacAadata<'a, T> {
 }
 
 impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
-
     ///
     /// This function is used to authenticate the input data with AES-GMAC.
     ///
@@ -99,7 +98,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
     /// random number.
     ///
     pub fn mac_aadata(additional_text: &T) -> SgxResult<Self> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -178,11 +176,12 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
     /// Indicates a crypto library failure or the RDRAND instruction fails to generate a
     /// random number.
     ///
-    pub fn mac_aadata_ex(key_policy: u16,
-                         attribute_mask: sgx_attributes_t,
-                         misc_mask: sgx_misc_select_t,
-                         additional_text: &T) -> SgxResult<Self> {
-
+    pub fn mac_aadata_ex(
+        key_policy: u16,
+        attribute_mask: sgx_attributes_t,
+        misc_mask: sgx_misc_select_t,
+        additional_text: &T,
+    ) -> SgxResult<Self> {
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -191,10 +190,13 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
             slice::from_raw_parts(additional_text as *const _ as *const u8, mem::size_of_val(additional_text))
         };
 
-        let result = SgxInternalSealedData::mac_aadata_ex(key_policy,
-                                                          attribute_mask,
-                                                          misc_mask,
-                                                          aad_slice);
+        let result =
+            SgxInternalSealedData::mac_aadata_ex(
+                key_policy,
+                attribute_mask,
+                misc_mask,
+                aad_slice,
+            );
         result.map(|x| SgxMacAadata {inner: x, marker: PhantomData})
     }
 
@@ -243,7 +245,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
     /// random number.
     ///
     pub fn unmac_aadata(&self) -> SgxResult<Box<T>> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -255,7 +256,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
 
         self.inner.unmac_aadata().map(|x| {
             let ptr = Box::into_raw(x.additional);
-            unsafe{Box::from_raw(ptr as *mut T)}
+            unsafe { Box::from_raw(ptr as *mut T) }
         })
     }
 
@@ -263,13 +264,12 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
     /// Convert a pointer of sgx_sealed_data_t buffer to SgxMacAadata.
     ///
     pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return None;
         }
         let opt = SgxInternalSealedData::from_raw_sealed_data_t(p, len);
-        opt.map(|x| SgxMacAadata{inner: x, marker: PhantomData})
+        opt.map(|x| SgxMacAadata { inner: x, marker: PhantomData })
     }
 
     ///
@@ -306,7 +306,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
     /// This function is used to authenticate the input data with AES-GMAC.
     ///
     pub fn mac_aadata(additional_text: &[T]) -> SgxResult<Self> {
-
         let size = mem::size_of::<T>();
         let len = mem::size_of_val(additional_text);
         if size == 0 || len == 0 {
@@ -317,18 +316,19 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
         };
 
         let result = SgxInternalSealedData::mac_aadata(aad_slice);
-        result.map(|x| SgxMacAadata {inner: x, marker: PhantomData})
+        result.map(|x| SgxMacAadata { inner: x, marker: PhantomData })
     }
 
     ///
     /// This function is used to authenticate the input data with AES-GMAC. This is
     /// the expert mode version of the function mac_aadata.
     ///
-    pub fn mac_aadata_ex(key_policy: u16,
-                         attribute_mask: sgx_attributes_t,
-                         misc_mask: sgx_misc_select_t,
-                         additional_text: &[T]) -> SgxResult<Self> {
-
+    pub fn mac_aadata_ex(
+        key_policy: u16,
+        attribute_mask: sgx_attributes_t,
+        misc_mask: sgx_misc_select_t,
+        additional_text: &[T],
+    ) -> SgxResult<Self> {
         let size = mem::size_of::<T>();
         let len = mem::size_of_val(additional_text);
         if size == 0 || len == 0 {
@@ -337,10 +337,13 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
         let aad_slice: &[u8] = unsafe {
             slice::from_raw_parts(additional_text.as_ptr() as *const u8, len)
         };
-        let result = SgxInternalSealedData::mac_aadata_ex(key_policy,
-                                                          attribute_mask,
-                                                          misc_mask,
-                                                          aad_slice);
+        let result =
+            SgxInternalSealedData::mac_aadata_ex(
+                key_policy,
+                attribute_mask,
+                misc_mask,
+                aad_slice,
+            );
         result.map(|x| SgxMacAadata {inner: x, marker: PhantomData})
     }
 
@@ -348,7 +351,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
     /// This function is used to verify the authenticity of the input sealed data structure using AES-GMAC. This function verifies the MAC generated with sgx_mac_aadataorsgx_mac_aadata_ex.
     ///
     pub fn unmac_aadata(&self) -> SgxResult<Box<[T]>> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -373,7 +375,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
     /// Convert a pointer of sgx_sealed_data_t buffer to SgxMacAadata.
     ///
     pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return None;
@@ -411,7 +412,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
 }
 
 impl<'a, T: 'a + ?Sized> SgxMacAadata<'a, T> {
-
     ///
     /// Create a SgxMacAadata with default values.
     ///
diff --git a/sgx_tseal/src/internal.rs b/sgx_tseal/src/internal.rs
index 4101df9..da9af99 100644
--- a/sgx_tseal/src/internal.rs
+++ b/sgx_tseal/src/internal.rs
@@ -74,7 +74,6 @@ pub struct SgxInternalSealedData {
 }
 
 impl SgxInternalSealedData {
-
     pub fn new() -> Self {
         SgxInternalSealedData::default()
     }
@@ -95,7 +94,6 @@ impl SgxInternalSealedData {
     }
 
     pub fn calc_raw_sealed_data_size(add_mac_txt_size: u32, encrypt_txt_size: u32) -> u32 {
-
         let max = u32::max_value();
         let sealed_data_size = mem::size_of::<sgx_sealed_data_t>() as u32;
 
@@ -110,7 +108,6 @@ impl SgxInternalSealedData {
     }
 
     pub fn get_add_mac_txt_len(&self) -> u32 {
-
         let data_size = self.payload_data.additional.len();
         if data_size > self.payload_data.payload_size as usize ||
            data_size >= u32::max_value() as usize {
@@ -121,7 +118,6 @@ impl SgxInternalSealedData {
     }
 
     pub fn get_encrypt_txt_len(&self) -> u32 {
-
         let data_size = self.payload_data.encrypt.len();
         if data_size > self.payload_data.payload_size as usize ||
            data_size >= u32::max_value() as usize {
@@ -132,7 +128,6 @@ impl SgxInternalSealedData {
     }
 
     pub unsafe fn to_raw_sealed_data_t(&self, p: *mut sgx_sealed_data_t, len: u32) -> Option<*mut sgx_sealed_data_t> {
-
         if p.is_null() {
             return None;
         }
@@ -179,7 +174,6 @@ impl SgxInternalSealedData {
 
     #[allow(clippy::cast_ptr_alignment)]
     pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
-
         if p.is_null() {
             return None;
         }
@@ -217,7 +211,7 @@ impl SgxInternalSealedData {
 
         let ptr_encrypt = ptr_sealed_data.add(mem::size_of::<sgx_sealed_data_t>());
 
-        let encrypt : Vec<u8> = if encrypt_len > 0 {
+        let encrypt: Vec<u8> = if encrypt_len > 0 {
             let mut temp: Vec<u8> = Vec::with_capacity(encrypt_len as usize);
             temp.set_len(encrypt_len as usize);
             ptr::copy_nonoverlapping(ptr_encrypt as *const u8, temp.as_mut_ptr(), encrypt_len as usize);
@@ -247,7 +241,6 @@ impl SgxInternalSealedData {
     }
 
     pub fn seal_data(additional_text: &[u8], encrypt_text: &[u8]) -> SgxResult<Self> {
-
         //let attribute_mask = sgx_attributes_t{flags: SGX_FLAGS_RESERVED | SGX_FLAGS_INITTED | SGX_FLAGS_DEBUG, xfrm: 0};
         /* intel sgx sdk 1.8 */
         let attribute_mask = sgx_attributes_t{flags: TSEAL_DEFAULT_FLAGSMASK, xfrm: 0};
@@ -258,19 +251,22 @@ impl SgxInternalSealedData {
             key_policy = SGX_KEYPOLICY_MRSIGNER | KEY_POLICY_KSS;
         }
 
-        Self::seal_data_ex(key_policy,
-                           attribute_mask,
-                           TSEAL_DEFAULT_MISCMASK,
-                           additional_text,
-                           encrypt_text)
+        Self::seal_data_ex(
+            key_policy,
+            attribute_mask,
+            TSEAL_DEFAULT_MISCMASK,
+            additional_text,
+            encrypt_text,
+        )
     }
 
-    pub fn seal_data_ex(key_policy: u16,
-                        attribute_mask: sgx_attributes_t,
-                        misc_mask: sgx_misc_select_t,
-                        additional_text: &[u8],
-                        encrypt_text: &[u8]) -> SgxResult<Self> {
-
+    pub fn seal_data_ex(
+        key_policy: u16,
+        attribute_mask: sgx_attributes_t,
+        misc_mask: sgx_misc_select_t,
+        additional_text: &[u8],
+        encrypt_text: &[u8],
+    ) -> SgxResult<Self> {
         let additional_len = additional_text.len();
         let encrypt_len = encrypt_text.len();
 
@@ -298,9 +294,9 @@ impl SgxInternalSealedData {
         }
 
         if additional_len > 0 &&
-               !rsgx_slice_is_within_enclave(additional_text) &&
-               !rsgx_slice_is_outside_enclave(additional_text) {
-                return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+           !rsgx_slice_is_within_enclave(additional_text) &&
+           !rsgx_slice_is_outside_enclave(additional_text) {
+            return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
         //let target_info = sgx_target_info_t::default();
@@ -317,21 +313,23 @@ impl SgxInternalSealedData {
             return Err(error.unwrap_err());
         }
 
-        let key_request = sgx_key_request_t{key_name: SGX_KEYSELECT_SEAL,
-                                            key_policy,
-                                            isv_svn: report.body.isv_svn,
-                                            reserved1: 0_u16,
-                                            cpu_svn: report.body.cpu_svn,
-                                            attribute_mask,
-                                            key_id,
-                                            misc_mask,
-                                            config_svn: report.body.config_svn,
-                                            reserved2: [0_u8; SGX_KEY_REQUEST_RESERVED2_BYTES]};
+        let key_request = sgx_key_request_t {
+            key_name: SGX_KEYSELECT_SEAL,
+            key_policy,
+            isv_svn: report.body.isv_svn,
+            reserved1: 0_u16,
+            cpu_svn: report.body.cpu_svn,
+            attribute_mask,
+            key_id,
+            misc_mask,
+            config_svn: report.body.config_svn,
+            reserved2: [0_u8; SGX_KEY_REQUEST_RESERVED2_BYTES],
+        };
 
         let payload_iv = [0_u8; SGX_SEAL_IV_SIZE];
         let mut result = Self::seal_data_iv(additional_text, encrypt_text, &payload_iv, &key_request);
 
-        if let Ok(ref mut sealed_data) = result { sealed_data.key_request = key_request};
+        if let Ok(ref mut sealed_data) = result { sealed_data.key_request = key_request };
 
         report = sgx_report_t::default();
         key_id = sgx_key_id_t::default();
@@ -340,7 +338,6 @@ impl SgxInternalSealedData {
     }
 
     pub fn unseal_data(&self) -> SgxResult<SgxInternalUnsealedData> {
-
         let additional_len = self.get_add_mac_txt_len();
         let encrypt_len = self.get_encrypt_txt_len();
 
@@ -363,15 +360,14 @@ impl SgxInternalSealedData {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         if additional_len > 0 &&
-            !rsgx_slice_is_within_enclave(self.get_additional_txt()) {
-                return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+           !rsgx_slice_is_within_enclave(self.get_additional_txt()) {
+            return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
         self.unseal_data_helper()
     }
 
     pub fn mac_aadata(additional_text: &[u8]) -> SgxResult<Self> {
-
         let attribute_mask = sgx_attributes_t{flags: TSEAL_DEFAULT_FLAGSMASK, xfrm: 0};
         let mut key_policy: u16 = SGX_KEYPOLICY_MRSIGNER;
         let report = rsgx_self_report();
@@ -380,17 +376,20 @@ impl SgxInternalSealedData {
             key_policy = SGX_KEYPOLICY_MRSIGNER | KEY_POLICY_KSS;
         }
 
-        Self::mac_aadata_ex(key_policy,
-                            attribute_mask,
-                            TSEAL_DEFAULT_MISCMASK,
-                            additional_text)
+        Self::mac_aadata_ex(
+            key_policy,
+            attribute_mask,
+            TSEAL_DEFAULT_MISCMASK,
+            additional_text,
+        )
     }
 
-    pub fn mac_aadata_ex(key_policy: u16,
-                         attribute_mask: sgx_attributes_t,
-                         misc_mask: sgx_misc_select_t,
-                         additional_text: &[u8]) -> SgxResult<Self> {
-
+    pub fn mac_aadata_ex(
+        key_policy: u16,
+        attribute_mask: sgx_attributes_t,
+        misc_mask: sgx_misc_select_t,
+        additional_text: &[u8],
+    ) -> SgxResult<Self> {
         let additional_len = additional_text.len();
         if additional_len >= u32::max_value() as usize {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -430,20 +429,22 @@ impl SgxInternalSealedData {
             return Err(error.unwrap_err());
         }
 
-        let key_request = sgx_key_request_t{key_name: SGX_KEYSELECT_SEAL,
-                                            key_policy,
-                                            isv_svn: report.body.isv_svn,
-                                            reserved1: 0_u16,
-                                            cpu_svn: report.body.cpu_svn,
-                                            attribute_mask,
-                                            key_id,
-                                            misc_mask,
-                                            config_svn: report.body.config_svn,
-                                            reserved2: [0_u8; SGX_KEY_REQUEST_RESERVED2_BYTES]};
+        let key_request = sgx_key_request_t {
+            key_name: SGX_KEYSELECT_SEAL,
+            key_policy,
+            isv_svn: report.body.isv_svn,
+            reserved1: 0_u16,
+            cpu_svn: report.body.cpu_svn,
+            attribute_mask,
+            key_id,
+            misc_mask,
+            config_svn: report.body.config_svn,
+            reserved2: [0_u8; SGX_KEY_REQUEST_RESERVED2_BYTES],
+        };
 
         let payload_iv = [0_u8; SGX_SEAL_IV_SIZE];
         let mut result = Self::seal_data_iv(additional_text, &[0_u8; 0], &payload_iv, &key_request);
-        if let Ok(ref mut sealed_data) = result { sealed_data.key_request = key_request};
+        if let Ok(ref mut sealed_data) = result { sealed_data.key_request = key_request };
 
         report = sgx_report_t::default();
         key_id = sgx_key_id_t::default();
@@ -452,7 +453,6 @@ impl SgxInternalSealedData {
     }
 
     pub fn unmac_aadata(&self) -> SgxResult<SgxInternalUnsealedData> {
-
         let additional_len = self.get_add_mac_txt_len();
         let encrypt_len = self.get_encrypt_txt_len();
 
@@ -482,11 +482,12 @@ impl SgxInternalSealedData {
         self.unseal_data_helper()
     }
 
-    fn seal_data_iv(additional_text: &[u8],
-                    encrypt_text: &[u8],
-                    payload_iv: &[u8],
-                    key_request: &sgx_key_request_t) -> SgxResult<Self>  {
-
+    fn seal_data_iv(
+        additional_text: &[u8],
+        encrypt_text: &[u8],
+        payload_iv: &[u8],
+        key_request: &sgx_key_request_t,
+    ) -> SgxResult<Self> {
         let mut seal_key = rsgx_get_align_key(key_request).map_err(|ret| {
             if ret != sgx_status_t::SGX_ERROR_OUT_OF_MEMORY {
                 sgx_status_t::SGX_ERROR_UNEXPECTED
@@ -498,12 +499,14 @@ impl SgxInternalSealedData {
         let mut sealed_data = SgxInternalSealedData::default();
         sealed_data.payload_data.encrypt = vec![0_u8; encrypt_text.len()].into_boxed_slice();
 
-        let error = rsgx_rijndael128GCM_encrypt(&seal_key.key,
-                                                encrypt_text,
-                                                payload_iv,
-                                                &additional_text,
-                                                &mut sealed_data.payload_data.encrypt,
-                                                &mut sealed_data.payload_data.payload_tag);
+        let error = rsgx_rijndael128GCM_encrypt(
+            &seal_key.key,
+            encrypt_text,
+            payload_iv,
+            &additional_text,
+            &mut sealed_data.payload_data.encrypt,
+            &mut sealed_data.payload_data.payload_tag,
+        );
         if error.is_err() {
             seal_key.key = sgx_key_128bit_t::default();
             return Err(error.unwrap_err());
@@ -520,7 +523,6 @@ impl SgxInternalSealedData {
     }
 
     fn unseal_data_helper(&self) -> SgxResult<SgxInternalUnsealedData> {
-
         let mut seal_key = rsgx_get_align_key(self.get_key_request()).map_err(|ret| {
             if (ret == sgx_status_t::SGX_ERROR_INVALID_CPUSVN) ||
                (ret == sgx_status_t::SGX_ERROR_INVALID_ISVSVN) ||
@@ -543,12 +545,14 @@ impl SgxInternalSealedData {
         let mut unsealed_data: SgxInternalUnsealedData = SgxInternalUnsealedData::default();
         unsealed_data.decrypt = vec![0_u8; self.payload_data.encrypt.len()].into_boxed_slice();
 
-        let error = rsgx_rijndael128GCM_decrypt(&seal_key.key,
-                                                self.get_encrypt_txt(),
-                                                &payload_iv,
-                                                self.get_additional_txt(),
-                                                self.get_payload_tag(),
-                                                &mut unsealed_data.decrypt);
+        let error = rsgx_rijndael128GCM_decrypt(
+            &seal_key.key,
+            self.get_encrypt_txt(),
+            &payload_iv,
+            self.get_additional_txt(),
+            self.get_payload_tag(),
+            &mut unsealed_data.decrypt,
+        );
         if error.is_err() {
             seal_key.key = sgx_key_128bit_t::default();
             return Err(error.unwrap_err());
diff --git a/sgx_tseal/src/seal.rs b/sgx_tseal/src/seal.rs
index c96d888..b898286 100644
--- a/sgx_tseal/src/seal.rs
+++ b/sgx_tseal/src/seal.rs
@@ -123,7 +123,6 @@ impl<'a, T: 'a + Clone + ?Sized> Clone for SgxSealedData<'a, T> {
 
 /// The encrypt_text to seal is T, and T must have Copy and ContiguousMemory trait.
 impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
-
     ///
     /// This function is used to AES-GCM encrypt the input data. Two input data sets
     /// are provided: one is the data to be encrypted; the second is optional additional data
@@ -182,7 +181,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
     /// random number.
     ///
     pub fn seal_data(additional_text: &[u8], encrypt_text: &'a T) -> SgxResult<Self> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -273,12 +271,13 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
     /// Indicates a crypto library failure or the RDRAND instruction fails to generate a
     /// random number.
     ///
-    pub fn seal_data_ex(key_policy: u16,
-                        attribute_mask: sgx_attributes_t,
-                        misc_mask: sgx_misc_select_t,
-                        additional_text: &[u8],
-                        encrypt_text: &'a T) -> SgxResult<Self> {
-
+    pub fn seal_data_ex(
+        key_policy: u16,
+        attribute_mask: sgx_attributes_t,
+        misc_mask: sgx_misc_select_t,
+        additional_text: &[u8],
+        encrypt_text: &'a T,
+    ) -> SgxResult<Self> {
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -286,11 +285,14 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
         let encrypt_slice: &[u8] = unsafe {
             slice::from_raw_parts(encrypt_text as *const _ as *const u8, mem::size_of_val(encrypt_text))
         };
-        let result = SgxInternalSealedData::seal_data_ex(key_policy,
-                                                         attribute_mask,
-                                                         misc_mask,
-                                                         additional_text,
-                                                         encrypt_slice);
+        let result =
+            SgxInternalSealedData::seal_data_ex(
+                key_policy,
+                attribute_mask,
+                misc_mask,
+                additional_text,
+                encrypt_slice,
+            );
         result.map(|x| {
             SgxSealedData {
                 inner: x,
@@ -348,7 +350,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
     /// random number.
     ///
     pub fn unseal_data(&self) -> SgxResult<SgxUnsealedData<'a, T>> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -396,7 +397,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
     /// Maybe the size of T is zero.
     ///
     pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return None;
@@ -439,7 +439,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
 
 /// The encrypt_text to seal is [T], and T must have Copy and ContiguousMemory trait.
 impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
-
     ///
     /// This function is used to AES-GCM encrypt the input data. Two input data sets
     /// are provided: one is the data to be encrypted; the second is optional additional data
@@ -498,7 +497,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
     /// random number.
     ///
     pub fn seal_data(additional_text: &[u8], encrypt_text: &'a [T]) -> SgxResult<Self> {
-
         let size = mem::size_of::<T>();
         let len = mem::size_of_val(encrypt_text);
         if size == 0 || len == 0 {
@@ -591,12 +589,13 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
     /// Indicates a crypto library failure or the RDRAND instruction fails to generate a
     /// random number.
     ///
-    pub fn seal_data_ex(key_policy: u16,
-                        attribute_mask: sgx_attributes_t,
-                        misc_mask: sgx_misc_select_t,
-                        additional_text: &[u8],
-                        encrypt_text: &'a [T]) -> SgxResult<Self> {
-
+    pub fn seal_data_ex(
+        key_policy: u16,
+        attribute_mask: sgx_attributes_t,
+        misc_mask: sgx_misc_select_t,
+        additional_text: &[u8],
+        encrypt_text: &'a [T],
+    ) -> SgxResult<Self> {
         let size = mem::size_of::<T>();
         let len = mem::size_of_val(encrypt_text);
         if size == 0 || len == 0 {
@@ -606,11 +605,14 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
             slice::from_raw_parts(encrypt_text.as_ptr() as *const u8, len)
         };
 
-        let result = SgxInternalSealedData::seal_data_ex(key_policy,
-                                                         attribute_mask,
-                                                         misc_mask,
-                                                         additional_text,
-                                                         encrypt_slice);
+        let result =
+            SgxInternalSealedData::seal_data_ex(
+                key_policy,
+                attribute_mask,
+                misc_mask,
+                additional_text,
+                encrypt_slice,
+            );
         result.map(|x| {
             SgxSealedData {
                 inner: x,
@@ -668,7 +670,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
     /// random number.
     ///
     pub fn unseal_data(&self) -> SgxResult<SgxUnsealedData<'a, [T]>> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -721,16 +722,16 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
     /// Maybe the size of T is zero.
     ///
     pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
-
         let size = mem::size_of::<T>();
         if size == 0 {
             return None;
         }
         let opt = SgxInternalSealedData::from_raw_sealed_data_t(p, len);
         opt.map(|x| {
-            SgxSealedData{
+            SgxSealedData {
                 inner: x,
-                marker: PhantomData}
+                marker: PhantomData,
+            }
         })
     }
 
@@ -763,7 +764,6 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
 }
 
 impl<'a, T: 'a + ?Sized> SgxSealedData<'a, T> {
-
     ///
     /// Create a SgxSealedData with default values.
     ///
diff --git a/sgx_tstd/Cargo.toml b/sgx_tstd/Cargo.toml
index a7da273..1951e95 100644
--- a/sgx_tstd/Cargo.toml
+++ b/sgx_tstd/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tstd"
-version = "1.1.1"
+version = "1.1.2"
 authors = ["The Teaclave Authors"]
 build = "build.rs"
 repository = "https://github.com/apache/teaclave-sgx-sdk"
@@ -33,5 +33,8 @@ sgx_backtrace_sys = { path = "../sgx_backtrace_sys" }
 sgx_demangle = { path = "../sgx_demangle" }
 sgx_unwind = { path = "../sgx_unwind" }
 
-[dependencies]
-hashbrown = { package = "hashbrown_tstd", path = "./hashbrown", default-features = false, features = ['rustc-dep-of-std'] }
+[dependencies.hashbrown]
+package = "hashbrown_tstd"
+path = "./hashbrown"
+default-features = false
+features = ['rustc-dep-of-std']
diff --git a/sgx_tstd/hashbrown/Cargo.toml b/sgx_tstd/hashbrown/Cargo.toml
index d6be9b6..43a18e9 100644
--- a/sgx_tstd/hashbrown/Cargo.toml
+++ b/sgx_tstd/hashbrown/Cargo.toml
@@ -23,27 +23,15 @@ keywords = ["hash", "no_std", "hashmap", "swisstable"]
 categories = ["data-structures", "no-std"]
 license = "Apache-2.0/MIT"
 repository = "https://github.com/rust-lang/hashbrown"
+
 [package.metadata.docs.rs]
 features = ["nightly", "rayon", "serde", "raw"]
+
 [dependencies.ahash]
 version = "0.3.2"
 optional = true
 default-features = false
 
-#[dependencies.alloc]
-#version = "1.0.0"
-#optional = true
-#package = "rustc-std-workspace-alloc"
-#
-#[dependencies.compiler_builtins]
-#version = "0.1.2"
-#optional = true
-#
-#[dependencies.core]
-#version = "1.0.0"
-#optional = true
-#package = "rustc-std-workspace-core"
-
 [dependencies.rayon]
 version = "1.0"
 optional = true
@@ -52,6 +40,7 @@ optional = true
 version = "1.0.25"
 optional = true
 default-features = false
+
 [dev-dependencies.doc-comment]
 version = "0.3.1"
 
@@ -70,6 +59,7 @@ version = "=1.0"
 
 [dev-dependencies.serde_test]
 version = "1.0"
+
 [build-dependencies.autocfg]
 version = "1"
 
diff --git a/sgx_tstd/src/alloc.rs b/sgx_tstd/src/alloc.rs
index 55ea7d6..29a84f0 100644
--- a/sgx_tstd/src/alloc.rs
+++ b/sgx_tstd/src/alloc.rs
@@ -54,11 +54,7 @@ pub fn set_alloc_error_hook(hook: fn(Layout)) {
 /// If no custom hook is registered, the default hook will be returned.
 pub fn take_alloc_error_hook() -> fn(Layout) {
     let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
-    if hook.is_null() {
-        default_alloc_error_hook
-    } else {
-        unsafe { mem::transmute(hook) }
-    }
+    if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
 }
 
 fn default_alloc_error_hook(layout: Layout) {
@@ -69,49 +65,50 @@ fn default_alloc_error_hook(layout: Layout) {
 #[alloc_error_handler]
 pub fn rust_oom(layout: Layout) -> ! {
     let hook = HOOK.load(Ordering::SeqCst);
-    let hook: fn(Layout) = if hook.is_null() {
-        default_alloc_error_hook
-    } else {
-        unsafe { mem::transmute(hook) }
-    };
+    let hook: fn(Layout) =
+        if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
     hook(layout);
-    rtabort!("memory allocation failed");
+    unsafe { crate::sys::abort_internal() }
 }
 
 #[doc(hidden)]
 #[allow(unused_attributes)]
 pub mod __default_lib_allocator {
-    use super::{System, Layout, GlobalAlloc};
-    // for symbol names src/librustc/middle/allocator.rs
+    use super::{GlobalAlloc, Layout, System};
+    // These magic symbol names are used as a fallback for implementing the
+    // `__rust_alloc` etc symbols (see `src/liballoc/alloc.rs`) when there is
+    // no `#[global_allocator]` attribute.
+
+    // for symbol names src/librustc_ast/expand/allocator.rs
     // for signatures src/librustc_allocator/lib.rs
 
     // linkage directives are provided as part of the current compiler allocator
     // ABI
 
     #[rustc_std_internal_symbol]
-    pub unsafe extern fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
+    pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 {
         let layout = Layout::from_size_align_unchecked(size, align);
         System.alloc(layout)
     }
 
     #[rustc_std_internal_symbol]
-    pub unsafe extern fn __rdl_dealloc(ptr: *mut u8,
-                                       size: usize,
-                                       align: usize) {
+    pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) {
         System.dealloc(ptr, Layout::from_size_align_unchecked(size, align))
     }
 
     #[rustc_std_internal_symbol]
-    pub unsafe extern fn __rdl_realloc(ptr: *mut u8,
-                                       old_size: usize,
-                                       align: usize,
-                                       new_size: usize) -> *mut u8 {
+    pub unsafe extern "C" fn __rdl_realloc(
+        ptr: *mut u8,
+        old_size: usize,
+        align: usize,
+        new_size: usize,
+    ) -> *mut u8 {
         let old_layout = Layout::from_size_align_unchecked(old_size, align);
         System.realloc(ptr, old_layout, new_size)
     }
 
     #[rustc_std_internal_symbol]
-    pub unsafe extern fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
+    pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 {
         let layout = Layout::from_size_align_unchecked(size, align);
         System.alloc_zeroed(layout)
     }
diff --git a/sgx_tstd/src/backtrace.rs b/sgx_tstd/src/backtrace.rs
index 4246a47..8c2bb04 100644
--- a/sgx_tstd/src/backtrace.rs
+++ b/sgx_tstd/src/backtrace.rs
@@ -15,16 +15,370 @@
 // specific language governing permissions and limitations
 // under the License..
 
-/// A wrapper mod for sys_common::backtrace, providing `enable_backtrace`
-/// interface.
+//! Support for capturing a stack backtrace of an OS thread
+//!
+//! This module contains the support necessary to capture a stack backtrace of a
+//! running OS thread from the OS thread itself. The `Backtrace` type supports
+//! capturing a stack trace via the `Backtrace::capture` and
+//! `Backtrace::force_capture` functions.
+//!
+//! A backtrace is typically quite handy to attach to errors (e.g. types
+//! implementing `std::error::Error`) to get a causal chain of where an error
+//! was generated.
... 27098 lines suppressed ...


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org