Merge pull request #267 from volcano0dr/master

initial support intel sgx sdk 2.11 and dcap 1.8
diff --git a/edl/intel/sgx_dcap_tvl.edl b/edl/intel/sgx_dcap_tvl.edl
new file mode 100644
index 0000000..7c5c0d8
--- /dev/null
+++ b/edl/intel/sgx_dcap_tvl.edl
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2011-2020 Intel Corporation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   * Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *   * Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in
+ *     the documentation and/or other materials provided with the
+ *     distribution.
+ *   * Neither the name of Intel Corporation nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+enclave {
+
+    include "sgx_qve_header.h"
+    include "sgx_ql_quote.h"
+
+
+    trusted {
+
+    /**
+     * Verify QvE Report and Identity
+     *
+     * @param p_quote[IN] - Pointer to SGX Quote.
+     * @param quote_size[IN] - Size of the buffer pointed to by p_quote (in bytes).
+     * @param p_qve_report_info[IN] - The output of API "sgx_qv_verify_quote", it should contain QvE report and nonce
+     * @param expiration_check_date[IN] - This is the date to verify QvE report data, you should use same value for this API and "sgx_qv_verify_quote"
+     * @param collateral_expiration_status[IN] - The output of API "sgx_qv_verify_quote" about quote verification collateral's expiration status
+     * @param quote_verification_result[IN] - The output of API "sgx_qv_verify_quote" about quote verification result
+     * @param p_supplemental_data[IN] - The output of API "sgx_qv_verify_quote", the pointer to supplemental data
+     * @param supplemental_data_size[IN] - Size of the buffer pointed to by p_quote (in bytes)
+     * @param qve_isvsvn_threshold [IN] - The threshold of QvE ISVSVN, the ISVSVN of QvE used to verify quote must be greater or equal to this threshold. You can get latest QvE ISVSVN in QvE Identity (JSON) from Intel PCS.
+     *
+     * @return Status code of the operation, one of:
+     *   - SGX_QL_SUCCESS
+     *   - SGX_QL_ERROR_INVALID_PARAMETER
+     *   - SGX_QL_ERROR_REPORT           // Error when verifying QvE report
+     *   - SGX_QL_ERROR_UNEXPECTED       // Error when comparing QvE report data
+     *   - SGX_QL_QVEIDENTITY_MISMATCH   // Error when comparing QvE identity
+     *   - SGX_QL_QVE_OUT_OF_DATE        // QvE ISVSVN is smaller than input QvE ISV SVN threshold
+     **/
+
+        public quote3_error_t sgx_tvl_verify_qve_report_and_identity(
+            [in, size=quote_size] const uint8_t *p_quote,
+            uint32_t quote_size,
+            [in, count=1] const sgx_ql_qe_report_info_t *p_qve_report_info,
+            time_t expiration_check_date,
+            uint32_t collateral_expiration_status,
+            sgx_ql_qv_result_t quote_verification_result,
+            [in, size=supplemental_data_size] const uint8_t *p_supplemental_data,
+            uint32_t supplemental_data_size,
+            sgx_isv_svn_t qve_isvsvn_threshold);
+    };
+};
diff --git a/mesalock-rt/libprotobuf.so.9 b/mesalock-rt/libprotobuf.so.9
old mode 100644
new mode 100755
Binary files differ
diff --git a/mesalock-rt/libsgx_uae_service.so b/mesalock-rt/libsgx_uae_service.so
old mode 100644
new mode 100755
Binary files differ
diff --git a/mesalock-rt/libsgx_urts.so b/mesalock-rt/libsgx_urts.so
old mode 100644
new mode 100755
Binary files differ
diff --git a/mesalock-rt/libstdc++.so.6 b/mesalock-rt/libstdc++.so.6
old mode 100644
new mode 100755
Binary files differ
diff --git a/mesalock-rt/libz.so.1 b/mesalock-rt/libz.so.1
old mode 100644
new mode 100755
Binary files differ
diff --git a/samplecode/backtrace/app/app.c b/samplecode/backtrace/app/app.c
index a2af74b..0725051 100644
--- a/samplecode/backtrace/app/app.c
+++ b/samplecode/backtrace/app/app.c
@@ -156,8 +156,6 @@
 {
     sgx_status_t sgx_ret = SGX_SUCCESS;
     sgx_status_t enclave_ret = SGX_SUCCESS;
-    uint32_t sealed_log_size = 1024;
-    uint8_t sealed_log[1024] = {0};
 
     (void)(argc);
     (void)(argv);
@@ -173,9 +171,9 @@
     size_t len = strlen(str);
 
     sgx_ret = say_something(global_eid,
-	                        &enclave_ret,
-							(const uint8_t *) str,
-							len);
+                            &enclave_ret,
+                            (const uint8_t *) str,
+                            len);
 
     if(sgx_ret != SGX_SUCCESS) {
         print_error_message(sgx_ret);
diff --git a/samplecode/db-proxy/db-proxy/Makefile b/samplecode/db-proxy/db-proxy/Makefile
index 72da97f..ffc2cb3 100644
--- a/samplecode/db-proxy/db-proxy/Makefile
+++ b/samplecode/db-proxy/db-proxy/Makefile
@@ -149,7 +149,6 @@
 enclave:
 	$(MAKE) -C ./enclave/
 
-
 .PHONY: clean
 clean:
 	@rm -f $(App_Name) $(RustEnclave_Name) $(Signed_RustEnclave_Name) enclave/*_t.* app/*_u.* lib/*.a
diff --git a/samplecode/hello-regex/app/app.c b/samplecode/hello-regex/app/app.c
index bbc5710..5647a76 100644
--- a/samplecode/hello-regex/app/app.c
+++ b/samplecode/hello-regex/app/app.c
@@ -156,8 +156,6 @@
 {
     sgx_status_t sgx_ret = SGX_SUCCESS;
     sgx_status_t enclave_ret = SGX_SUCCESS;
-    uint32_t sealed_log_size = 1024;
-    uint8_t sealed_log[1024] = {0};
 
     (void)(argc);
     (void)(argv);
diff --git a/samplecode/hello-rust/enclave/src/lib.rs b/samplecode/hello-rust/enclave/src/lib.rs
index f661955..345c00c 100644
--- a/samplecode/hello-rust/enclave/src/lib.rs
+++ b/samplecode/hello-rust/enclave/src/lib.rs
@@ -22,20 +22,15 @@
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
 
 extern crate sgx_types;
-extern crate sgx_trts;
 #[cfg(not(target_env = "sgx"))]
 #[macro_use]
 extern crate sgx_tstd as std;
 
 use sgx_types::*;
-use sgx_types::metadata::*;
-use sgx_trts::enclave;
-//use sgx_trts::{is_x86_feature_detected, is_cpu_feature_supported};
 use std::string::String;
 use std::vec::Vec;
 use std::io::{self, Write};
 use std::slice;
-use std::backtrace::{self, PrintFormat};
 
 #[no_mangle]
 pub extern "C" fn say_something(some_string: *const u8, some_len: usize) -> sgx_status_t {
@@ -65,66 +60,5 @@
     // Ocall to normal world for output
     println!("{}", &hello_string);
 
-    let _ = backtrace::enable_backtrace("enclave.signed.so", PrintFormat::Full);
-
-    let gd = enclave::SgxGlobalData::new();
-    println!("gd: {} {} {} {} ", gd.get_static_tcs_num(), gd.get_eremove_tcs_num(), gd.get_dyn_tcs_num(), gd.get_tcs_max_num());
-    let (static_num, eremove_num, dyn_num) = get_thread_num();
-    println!("static: {} eremove: {} dyn: {}", static_num, eremove_num, dyn_num);
-
-    unsafe {
-        println!("EDMM: {}, feature: {}", EDMM_supported, g_cpu_feature_indicator);
-    }
-    if is_x86_feature_detected!("sgx") {
-        println!("supported sgx");
-    }
-
     sgx_status_t::SGX_SUCCESS
 }
-
-#[link(name = "sgx_trts")]
-extern {
-    static g_cpu_feature_indicator: uint64_t;
-    static EDMM_supported: c_int;
-}
-
-
-fn get_thread_num() -> (u32, u32, u32) {
-    let gd = unsafe {
-        let p = enclave::rsgx_get_global_data();
-        &*p
-    };
-
-    let mut static_thread_num: u32 = 0;
-    let mut eremove_thread_num: u32 = 0;
-    let mut dyn_thread_num: u32 = 0;
-    let layout_table = &gd.layout_table[0..gd.layout_entry_num as usize];
-    unsafe { traversal_layout(&mut static_thread_num, &mut dyn_thread_num, &mut eremove_thread_num, layout_table); }
-
-    unsafe fn traversal_layout(static_num: &mut u32, dyn_num: &mut u32, eremove_num: &mut u32, layout_table: &[layout_t])
-    {
-        for (i, layout) in layout_table.iter().enumerate() {
-            if !is_group_id!(layout.group.id as u32) {
-                if (layout.entry.attributes & PAGE_ATTR_EADD) != 0 {
-                    if (layout.entry.content_offset != 0) && (layout.entry.si_flags == SI_FLAGS_TCS) {
-                        if (layout.entry.attributes & PAGE_ATTR_EREMOVE) == 0 {
-                            *static_num += 1;
-                        } else {
-                            *eremove_num += 1;
-                        }
-                    }
-                }
-                if (layout.entry.attributes & PAGE_ATTR_POST_ADD) != 0 {
-                    if layout.entry.id == LAYOUT_ID_TCS_DYN as u16 {
-                        *dyn_num += 1;
-                    }
-                }
-            } else {
-                for _ in 0..layout.group.load_times {
-                    traversal_layout(static_num, dyn_num, eremove_num, &layout_table[i - layout.group.entry_count as usize..i])
-                }
-            }
-        }
-    }
-    (static_thread_num, eremove_thread_num, dyn_thread_num)
-}
\ No newline at end of file
diff --git a/samplecode/helloworld/app/app.c b/samplecode/helloworld/app/app.c
index a2af74b..0725051 100644
--- a/samplecode/helloworld/app/app.c
+++ b/samplecode/helloworld/app/app.c
@@ -156,8 +156,6 @@
 {
     sgx_status_t sgx_ret = SGX_SUCCESS;
     sgx_status_t enclave_ret = SGX_SUCCESS;
-    uint32_t sealed_log_size = 1024;
-    uint8_t sealed_log[1024] = {0};
 
     (void)(argc);
     (void)(argv);
@@ -173,9 +171,9 @@
     size_t len = strlen(str);
 
     sgx_ret = say_something(global_eid,
-	                        &enclave_ret,
-							(const uint8_t *) str,
-							len);
+                            &enclave_ret,
+                            (const uint8_t *) str,
+                            len);
 
     if(sgx_ret != SGX_SUCCESS) {
         print_error_message(sgx_ret);
diff --git a/samplecode/http_req/Makefile b/samplecode/http_req/Makefile
index b444c2e..fee080a 100644
--- a/samplecode/http_req/Makefile
+++ b/samplecode/http_req/Makefile
@@ -135,7 +135,6 @@
 enclave:
 	$(MAKE) -C ./enclave/
 
-
 .PHONY: clean
 clean:
 	@rm -f $(App_Name) $(RustEnclave_Name) $(Signed_RustEnclave_Name) enclave/*_t.* app/*_u.* lib/*.a *.c *.h *.p *.a
diff --git a/samplecode/http_req/run.bash b/samplecode/http_req/run.bash
old mode 100755
new mode 100644
diff --git a/samplecode/hugemem/app/app.c b/samplecode/hugemem/app/app.c
index 82aa7cc..3d4bfba 100644
--- a/samplecode/hugemem/app/app.c
+++ b/samplecode/hugemem/app/app.c
@@ -156,8 +156,6 @@
 {
     sgx_status_t sgx_ret = SGX_SUCCESS;
     sgx_status_t enclave_ret = SGX_SUCCESS;
-    uint32_t sealed_log_size = 1024;
-    uint8_t sealed_log[1024] = {0};
 
     (void)(argc);
     (void)(argv);
@@ -173,9 +171,9 @@
     size_t len = strlen(str);
 
     sgx_ret = say_something(global_eid,
-	                        &enclave_ret,
-							(const uint8_t *) str,
-							len);
+                            &enclave_ret,
+                            (const uint8_t *) str,
+                            len);
 
     if(sgx_ret != SGX_SUCCESS) {
         print_error_message(sgx_ret);
diff --git a/samplecode/mio/client-java/mvnw b/samplecode/mio/client-java/mvnw
old mode 100755
new mode 100644
diff --git a/samplecode/pcl/pcl-seal/Makefile b/samplecode/pcl/pcl-seal/Makefile
index 581424c..5f4a44e 100644
--- a/samplecode/pcl/pcl-seal/Makefile
+++ b/samplecode/pcl/pcl-seal/Makefile
@@ -169,7 +169,6 @@
 enclave:
 	$(MAKE) -C ./enclave/
 
-
 .PHONY: clean
 clean:
 	@rm -f $(App_Name) $(RustEnclave_Name) $(Signed_RustEnclave_Name) $(PayloadEnclave_Name) enclave/*_t.* app/*_u.* lib/*.a enclave/Payload.edl bin/prov_key.bin
diff --git a/samplecode/psi/SMCClient/sample_libcrypto/libsample_libcrypto.so b/samplecode/psi/SMCClient/sample_libcrypto/libsample_libcrypto.so
old mode 100644
new mode 100755
Binary files differ
diff --git a/samplecode/secretsharing/app/app.c b/samplecode/secretsharing/app/app.c
index a2af74b..0725051 100644
--- a/samplecode/secretsharing/app/app.c
+++ b/samplecode/secretsharing/app/app.c
@@ -156,8 +156,6 @@
 {
     sgx_status_t sgx_ret = SGX_SUCCESS;
     sgx_status_t enclave_ret = SGX_SUCCESS;
-    uint32_t sealed_log_size = 1024;
-    uint8_t sealed_log[1024] = {0};
 
     (void)(argc);
     (void)(argv);
@@ -173,9 +171,9 @@
     size_t len = strlen(str);
 
     sgx_ret = say_something(global_eid,
-	                        &enclave_ret,
-							(const uint8_t *) str,
-							len);
+                            &enclave_ret,
+                            (const uint8_t *) str,
+                            len);
 
     if(sgx_ret != SGX_SUCCESS) {
         print_error_message(sgx_ret);
diff --git a/samplecode/serialize/app/app.c b/samplecode/serialize/app/app.c
index 6bd355c..08466dc 100644
--- a/samplecode/serialize/app/app.c
+++ b/samplecode/serialize/app/app.c
@@ -155,8 +155,6 @@
 int SGX_CDECL main(int argc, char *argv[])
 {
     sgx_status_t sgx_ret = SGX_SUCCESS;
-    uint32_t sealed_log_size = 1024;
-    uint8_t sealed_log[1024] = {0};
 
     (void)(argc);
     (void)(argv);
diff --git a/samplecode/sgx-cov/enclave/enclave-cov-rustc b/samplecode/sgx-cov/enclave/enclave-cov-rustc
old mode 100755
new mode 100644
diff --git a/samplecode/sgx-cov/enclave/llvm-gcov b/samplecode/sgx-cov/enclave/llvm-gcov
old mode 100755
new mode 100644
diff --git a/samplecode/thread/app/App.cpp b/samplecode/thread/app/App.cpp
index 0f76408..24bc46d 100644
--- a/samplecode/thread/app/App.cpp
+++ b/samplecode/thread/app/App.cpp
@@ -157,7 +157,6 @@
     (void)(argc);
     (void)(argv);
 
-
     /* Initialize the enclave */
     if(initialize_enclave() < 0){
         printf("Enter a character before exit ...\n");
diff --git a/samplecode/tls/tlsclient/app/src/main.rs b/samplecode/tls/tlsclient/app/src/main.rs
index c15188b..f4a4e88 100644
--- a/samplecode/tls/tlsclient/app/src/main.rs
+++ b/samplecode/tls/tlsclient/app/src/main.rs
@@ -29,7 +29,7 @@
 use std::ffi::CString;
 use std::net::SocketAddr;
 use std::str;
-use std::io::{self, Read, Write};
+use std::io::{self, Write};
 
 const BUFFER_SIZE: usize = 1024;
 
diff --git a/samplecode/tr-mpc/tr-mpc-server/Makefile b/samplecode/tr-mpc/tr-mpc-server/Makefile
index 836e1e6..463d238 100644
--- a/samplecode/tr-mpc/tr-mpc-server/Makefile
+++ b/samplecode/tr-mpc/tr-mpc-server/Makefile
@@ -150,7 +150,6 @@
 enclave:
 	$(MAKE) -C ./enclave/
 
-
 .PHONY: clean
 clean:
 	@rm -f $(App_Name) $(RustEnclave_Name) $(Signed_RustEnclave_Name) enclave/*_t.* app/*_u.* lib/*.a
diff --git a/samplecode/ue-ra/ue-ra-client-java/mvnw b/samplecode/ue-ra/ue-ra-client-java/mvnw
old mode 100755
new mode 100644
diff --git a/samplecode/ue-ra/ue-ra-server/Makefile b/samplecode/ue-ra/ue-ra-server/Makefile
index 4c8956a..02e8a78 100644
--- a/samplecode/ue-ra/ue-ra-server/Makefile
+++ b/samplecode/ue-ra/ue-ra-server/Makefile
@@ -150,7 +150,6 @@
 enclave:
 	$(MAKE) -C ./enclave/
 
-
 .PHONY: clean
 clean:
 	@rm -f $(App_Name) $(RustEnclave_Name) $(Signed_RustEnclave_Name) enclave/*_t.* app/*_u.* lib/*.a
diff --git a/samplecode/unit-test/enclave/src/test_mpsc.rs b/samplecode/unit-test/enclave/src/test_mpsc.rs
index 6e09f04..afb836f 100644
--- a/samplecode/unit-test/enclave/src/test_mpsc.rs
+++ b/samplecode/unit-test/enclave/src/test_mpsc.rs
@@ -450,7 +450,7 @@
 pub fn test_mpsc_very_long_recv_timeout_wont_panic() {
     let (tx, rx) = channel::<()>();
     let join_handle = thread::spawn(move || {
-        rx.recv_timeout(Duration::from_secs(u64::max_value()))
+        rx.recv_timeout(Duration::from_secs(u64::MAX))
     });
     thread::sleep(Duration::from_secs(1));
     assert!(tx.send(()).is_ok());
diff --git a/samplecode/unit-test/enclave/src/test_rand.rs b/samplecode/unit-test/enclave/src/test_rand.rs
index 65bd268..c748642 100644
--- a/samplecode/unit-test/enclave/src/test_rand.rs
+++ b/samplecode/unit-test/enclave/src/test_rand.rs
@@ -53,7 +53,7 @@
             $(
                let v: &[($ty, $ty)] = &[(0, 10),
                                         (10, 127),
-                                        ($ty::min_value(), $ty::max_value())];
+                                        ($ty::min_value(), $ty::MAX)];
                for &(low, high) in v {
                     let mut sampler: Range<$ty> = Range::new(low, high);
                     for _ in 0..1000 {
diff --git a/samplecode/unit-test/enclave/src/test_serialize.rs b/samplecode/unit-test/enclave/src/test_serialize.rs
old mode 100755
new mode 100644
diff --git a/sgx_align_struct_attribute/src/align.rs b/sgx_align_struct_attribute/src/align.rs
index 7e5ac1b..e023831 100644
--- a/sgx_align_struct_attribute/src/align.rs
+++ b/sgx_align_struct_attribute/src/align.rs
@@ -15,12 +15,15 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use crate::layout::{self, AlignReq};
 use proc_macro2::{Ident, Punct, Span};
 use quote::quote;
-use syn::parse::{Parse, Result, ParseStream};
-use syn::{punctuated::Punctuated, Meta, Lit, Error, parse_quote, Token, Expr, Type, DeriveInput, Fields, LitInt};
 use std::alloc::Layout;
-use crate::layout::{self, AlignReq};
+use syn::parse::{Parse, ParseStream, Result};
+use syn::{
+    parse_quote, punctuated::Punctuated, DeriveInput, Error, Expr, Fields, Lit, LitInt, Meta,
+    Token, Type,
+};
 
 struct KeyValue {
     pub ident: Ident,
@@ -33,11 +36,15 @@
         let ident = input.parse::<Ident>()?;
         let punct = input.parse::<Punct>()?;
         let value = input.parse::<Expr>()?;
-        Ok(KeyValue{ident, punct, value})
+        Ok(KeyValue {
+            ident,
+            punct,
+            value,
+        })
     }
 }
 
-pub struct AlignArgs  {
+pub struct AlignArgs {
     vars: Vec<KeyValue>,
 }
 
@@ -51,8 +58,12 @@
 }
 
 impl AlignArgs {
-    pub fn get_layout (&self) -> Result<Layout> {
-        let align_iter = self.vars.iter().filter(|v| v.ident.to_string() == "align").next();
+    pub fn get_layout(&self) -> Result<Layout> {
+        let align_iter = self
+            .vars
+            .iter()
+            .filter(|v| v.ident.to_string() == "align")
+            .next();
         let align: usize = if let Some(align_value) = align_iter {
             self.parse_align(&align_value.value)?
         } else {
@@ -62,7 +73,11 @@
             ));
         };
 
-        let size_iter = self.vars.iter().filter(|v| v.ident.to_string() == "size").next();
+        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 {
@@ -72,10 +87,7 @@
             ));
         };
         Layout::from_size_align(size, align)
-            .map_err(|_e| Error::new(
-                Span::call_site(),
-                "Layout illegal",
-            ))
+            .map_err(|_e| Error::new(Span::call_site(), "Layout illegal"))
     }
 
     fn parse_align(&self, align_expr: &Expr) -> Result<usize> {
@@ -128,18 +140,15 @@
     name: Option<&'a Ident>,
 }
 
-impl<'a>FiledExt<'a> {
+impl<'a> FiledExt<'a> {
     pub fn new(ty: &'a Type, name: Option<&'a Ident>) -> Self {
-        FiledExt {
-            ty,
-            name
-        }
+        FiledExt { ty, name }
     }
 
     pub fn as_origin_named_field(&self) -> proc_macro2::TokenStream {
         let ty = &self.ty;
         let name = self.name.as_ref().unwrap();
-        quote!{
+        quote! {
             #name: #ty,
         }
     }
@@ -150,14 +159,15 @@
         AlignStruct {
             input,
             layout,
-            align_layout: unsafe{Layout::from_size_align_unchecked(0, 0)},
+            align_layout: unsafe { Layout::from_size_align_unchecked(0, 0) },
         }
     }
 
     pub fn build(&mut self) -> proc_macro2::TokenStream {
-        if !(self.is_contains_specified_attr("C") 
-        && !self.is_contains_specified_attr("align")
-        && !self.is_contains_specified_attr("packed")) {
+        if !(self.is_contains_specified_attr("C")
+            && !self.is_contains_specified_attr("align")
+            && !self.is_contains_specified_attr("packed"))
+        {
             panic!("Structure attribute must require repr C ");
         }
 
@@ -168,12 +178,12 @@
         let generics = &self.input.generics;
         let fields = &self.get_origin_fields();
         let align_attr = &self.generate_align_attr();
-        quote!{
+        quote! {
             #attrs
             #align_attr
             #vis struct #name#generics {
             #pad_item,
-            #fields   
+            #fields
             }
         }
     }
@@ -185,20 +195,22 @@
             let meta = attr.parse_meta();
             if ident.map_or(false, |v| v.to_string() == "repr") && meta.is_ok() {
                 if let Some(Meta::List(ref m)) = meta.ok() {
-                    if  m.nested.len() > 0 {
-                        erxcept_attr = m.nested
-                        .iter()
-                        .filter(|x| {
-                            let mut find = false;
-                            if let syn::NestedMeta::Meta(ref s) = x {
-                                if let syn::Meta::Path(p) = s {
-                                    find = p.get_ident().map_or(false, |v| v.to_string() == atrr);
+                    if m.nested.len() > 0 {
+                        erxcept_attr = m
+                            .nested
+                            .iter()
+                            .filter(|x| {
+                                let mut find = false;
+                                if let syn::NestedMeta::Meta(ref s) = x {
+                                    if let syn::Meta::Path(p) = s {
+                                        find =
+                                            p.get_ident().map_or(false, |v| v.to_string() == atrr);
+                                    }
                                 }
-                            }    
-                            find
-                        })
-                        .next()
-                        .is_some();
+                                find
+                            })
+                            .next()
+                            .is_some();
                     }
                 }
             }
@@ -208,7 +220,7 @@
 
     fn get_attrs(&self) -> proc_macro2::TokenStream {
         let attrs = &self.input.attrs;
-        quote!{
+        quote! {
             #(#attrs)*
         }
     }
@@ -216,19 +228,23 @@
     fn generate_align_attr(&self) -> proc_macro2::TokenStream {
         let align = self.align_layout.align();
         let litint = LitInt::new(&format!("{}", align).to_string(), Span::call_site());
-        quote!{
+        quote! {
            #[repr(align(#litint))]
         }
     }
 
-    fn get_origin_fields(&self)  -> proc_macro2::TokenStream {
+    fn get_origin_fields(&self) -> proc_macro2::TokenStream {
         if let syn::Data::Struct(ref data) = self.input.data {
             if let Fields::Named(ref fields) = data.fields {
-                let fields :Vec<_> = fields.named.iter().map(|f| FiledExt::new(&f.ty, f.ident.as_ref())).collect();
-                    let item = fields.iter().map(|x| x.as_origin_named_field());
-                    quote!{
-                        #(#item)*
-                    }
+                let fields: Vec<_> = fields
+                    .named
+                    .iter()
+                    .map(|f| FiledExt::new(&f.ty, f.ident.as_ref()))
+                    .collect();
+                let item = fields.iter().map(|x| x.as_origin_named_field());
+                quote! {
+                    #(#item)*
+                }
             } else {
                 panic!("Structure fields must have names");
             }
@@ -241,9 +257,9 @@
         let align_req: &[AlignReq] = &[AlignReq {
             offset: 0,
             len: self.layout.size(),
-            },
-        ];
-        let align_layout = layout::pad_align_to(self.layout, align_req).expect("Align layout illegal");
+        }];
+        let align_layout =
+            layout::pad_align_to(self.layout, align_req).expect("Align layout illegal");
         self.align_layout = align_layout;
         let pad = align_layout.size() - align_layout.align() - self.layout.size();
         let ty: syn::Type = parse_quote!([u8; #pad]);
diff --git a/sgx_align_struct_attribute/src/layout.rs b/sgx_align_struct_attribute/src/layout.rs
index ec9b5ca..68150c4 100644
--- a/sgx_align_struct_attribute/src/layout.rs
+++ b/sgx_align_struct_attribute/src/layout.rs
@@ -16,11 +16,11 @@
 // under the License..
 
 use std::alloc::Layout;
-use std::ptr;
+use std::ffi::c_void;
 use std::fmt;
 use std::mem;
+use std::ptr;
 use std::slice;
-use std::ffi::c_void;
 
 #[derive(Clone, Copy, Default)]
 pub struct AlignReq {
@@ -49,7 +49,7 @@
 pub fn pad_align_to(layout: Layout, align_req: &[AlignReq]) -> Result<Layout, AlignLayoutErr> {
     let pad = padding_needed_for(layout, align_req)?;
     let align = align_needed_for(layout, pad)?;
-    Layout::from_size_align(pad + align + layout.size(), align).map_err(|_|AlignLayoutErr)
+    Layout::from_size_align(pad + align + layout.size(), align).map_err(|_| AlignLayoutErr)
 }
 
 fn padding_needed_for(layout: Layout, align_req: &[AlignReq]) -> Result<usize, AlignLayoutErr> {
@@ -78,8 +78,10 @@
 }
 
 fn check_layout(layout: &Layout) -> bool {
-    if layout.size() == 0 || !layout.align().is_power_of_two() ||
-        layout.size() > usize::max_value() - (layout.align() - 1) {
+    if layout.size() == 0
+        || !layout.align().is_power_of_two()
+        || layout.size() > usize::MAX - (layout.align() - 1)
+    {
         false
     } else {
         true
@@ -102,14 +104,18 @@
 
     for req in align_req {
         if check_overflow(req.offset, req.len) || (req.offset + req.len) > size {
-            unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+            unsafe {
+                libc::free(bmp.as_mut_ptr() as *mut c_void);
+            }
             return false;
         } else {
             for i in 0..req.len {
                 let offset = req.offset + i;
                 if (bmp[offset / 8] & 1 << (offset % 8)) != 0 {
                     // overlap in req data
-                    unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+                    unsafe {
+                        libc::free(bmp.as_mut_ptr() as *mut c_void);
+                    }
                     return false;
                 }
                 let tmp: u8 = (1 << (offset % 8)) as u8;
@@ -121,7 +127,7 @@
 }
 
 fn gen_alignmask(al: usize, a: usize, m: u64) -> i64 {
-    if a  > al {
+    if a > al {
         gen_alignmask(al, (a >> 1) as usize, m | (m >> (a >> 1)))
     } else {
         m as i64
@@ -129,13 +135,13 @@
 }
 
 #[inline]
-fn __rol(v: u64, c: usize, m: usize) -> u64  {
+fn __rol(v: u64, c: usize, m: usize) -> u64 {
     (v << (c & m)) | (v >> (((0 - c as isize) as usize) & m))
 }
 
 #[inline]
 fn rol(v: i64, c: usize) -> i64 {
-    __rol(v as u64 , c, mem::size_of::<i64>() * 8 - 1) as i64
+    __rol(v as u64, c, mem::size_of::<i64>() * 8 - 1) as i64
 }
 
 fn ror(v: i64, c: usize) -> i64 {
@@ -157,8 +163,13 @@
         -2
     } else {
         count_lzb(
-            !(ror(bmp | ror(bmp, 1) | ror(bmp, 2) | ror(bmp, 3), 5) | ror(bmp, 1)) &
-            gen_alignmask(al, mem::size_of::<u64>() * 8, 1_u64 << (mem::size_of::<u64>() * 8 - 1)))
+            !(ror(bmp | ror(bmp, 1) | ror(bmp, 2) | ror(bmp, 3), 5) | ror(bmp, 1))
+                & gen_alignmask(
+                    al,
+                    mem::size_of::<u64>() * 8,
+                    1_u64 << (mem::size_of::<u64>() * 8 - 1),
+                ),
+        )
     }
 }
 
@@ -171,7 +182,7 @@
 }
 
 fn calc_algn(al: usize, size: usize) -> usize {
-    if al > 64  {
+    if al > 64 {
         al
     } else {
         __calc_algn(size, mem::size_of::<u64>() * 8)
@@ -196,4 +207,4 @@
         pub fn malloc(size: usize) -> *mut c_void;
         pub fn free(p: *mut c_void);
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_align_struct_attribute/src/lib.rs b/sgx_align_struct_attribute/src/lib.rs
index 5a48c34..36a28a8 100644
--- a/sgx_align_struct_attribute/src/lib.rs
+++ b/sgx_align_struct_attribute/src/lib.rs
@@ -16,17 +16,20 @@
 // under the License..
 
 extern crate proc_macro;
-use syn::{parse_macro_input, DeriveInput};
 use align::{AlignArgs, AlignStruct};
+use syn::{parse_macro_input, DeriveInput};
 
 mod align;
 mod layout;
 
 #[proc_macro_attribute]
-pub fn sgx_align(args: proc_macro::TokenStream, input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+pub fn sgx_align(
+    args: proc_macro::TokenStream,
+    input: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
     let args = parse_macro_input!(args as AlignArgs);
     let layout = args.get_layout().expect("Attribute args error");
-    let input  = parse_macro_input!(input as DeriveInput);
+    let input = parse_macro_input!(input as DeriveInput);
     let mut alignstruct = AlignStruct::new(layout, input);
     let expanded = alignstruct.build();
     proc_macro::TokenStream::from(expanded)
diff --git a/sgx_alloc/src/alignalloc.rs b/sgx_alloc/src/alignalloc.rs
index 0b1e16e..f96aaa5 100644
--- a/sgx_alloc/src/alignalloc.rs
+++ b/sgx_alloc/src/alignalloc.rs
@@ -18,10 +18,10 @@
 //! # align alloc crate for Rust SGX SDK
 //!
 
-use core::alloc::Layout;
-use core::ptr::NonNull;
-use core::fmt;
 pub use self::platform::*;
+use core::alloc::Layout;
+use core::fmt;
+use core::ptr::NonNull;
 
 #[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
 pub struct AlignReq {
@@ -43,23 +43,40 @@
     }
 
     #[inline]
-    pub unsafe fn alloc_with_req(&mut self, layout: Layout, align_req: &[AlignReq]) -> Result<NonNull<u8>, AlighAllocErr> {
+    pub unsafe fn alloc_with_req(
+        &mut self,
+        layout: Layout,
+        align_req: &[AlignReq],
+    ) -> Result<NonNull<u8>, AlighAllocErr> {
         NonNull::new(platform::alloc_with_req(layout, align_req)).ok_or(AlighAllocErr)
     }
 
     #[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)
     }
 
     #[inline]
-    pub unsafe fn alloc_with_pad_align(&mut self, layout: Layout, align_layout: Layout) -> Result<NonNull<u8>, AlighAllocErr> {
+    pub unsafe fn alloc_with_pad_align(
+        &mut self,
+        layout: Layout,
+        align_layout: Layout,
+    ) -> Result<NonNull<u8>, AlighAllocErr> {
         NonNull::new(platform::alloc_with_pad_align(layout, align_layout)).ok_or(AlighAllocErr)
     }
 
     #[inline]
-    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)
+    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)
     }
 
     #[inline]
@@ -68,7 +85,11 @@
     }
 
     #[inline]
-    pub fn pad_align_to(&self, layout: Layout, align_req: &[AlignReq]) -> Result<Layout, AlignLayoutErr> {
+    pub fn pad_align_to(
+        &self,
+        layout: Layout,
+        align_req: &[AlignReq],
+    ) -> Result<Layout, AlignLayoutErr> {
         platform::pad_align_to(layout, align_req)
     }
 }
@@ -94,15 +115,18 @@
 mod platform {
     use super::AlignLayoutErr;
     use super::AlignReq;
-    use core::ffi::c_void;
-    use core::ptr;
-    use core::mem;
-    use core::slice;
     use core::alloc::Layout;
+    use core::ffi::c_void;
+    use core::mem;
+    use core::ptr;
+    use core::slice;
 
     #[inline]
     pub unsafe fn alloc(layout: Layout) -> *mut u8 {
-        let req: [AlignReq; 1] = [AlignReq{ offset: 0, len: layout.size() }];
+        let req: [AlignReq; 1] = [AlignReq {
+            offset: 0,
+            len: layout.size(),
+        }];
         let align_req = &req[..];
         alloc_with_req(layout, align_req)
     }
@@ -111,14 +135,15 @@
         if !check_layout(&layout) {
             return ptr::null_mut();
         }
-        let align_layout = match
-            if align_req.len() == 0 {
-                let req: [AlignReq; 1] = [AlignReq{ offset: 0, len: layout.size() }];
-                pad_align_to(layout, &req[..])
-            } else {
-                pad_align_to(layout, align_req)
-            }
-        {
+        let align_layout = match if align_req.len() == 0 {
+            let req: [AlignReq; 1] = [AlignReq {
+                offset: 0,
+                len: layout.size(),
+            }];
+            pad_align_to(layout, &req[..])
+        } else {
+            pad_align_to(layout, align_req)
+        } {
             Ok(l) => l,
             Err(_) => return ptr::null_mut(),
         };
@@ -132,7 +157,10 @@
 
     #[inline]
     pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
-        let req: [AlignReq; 1] = [AlignReq{ offset: 0, len: layout.size() }];
+        let req: [AlignReq; 1] = [AlignReq {
+            offset: 0,
+            len: layout.size(),
+        }];
         let align_req = &req[..];
         alloc_with_req_zeroed(layout, align_req)
     }
@@ -141,14 +169,15 @@
         if !check_layout(&layout) {
             return ptr::null_mut();
         }
-        let align_layout = match
-            if align_req.len() == 0 {
-                let req: [AlignReq; 1] = [AlignReq{ offset: 0, len: layout.size() }];
-                pad_align_to(layout, &req[..])
-            } else {
-                pad_align_to(layout, align_req)
-            }
-        {
+        let align_layout = match if align_req.len() == 0 {
+            let req: [AlignReq; 1] = [AlignReq {
+                offset: 0,
+                len: layout.size(),
+            }];
+            pad_align_to(layout, &req[..])
+        } else {
+            pad_align_to(layout, align_req)
+        } {
             Ok(l) => l,
             Err(_) => return ptr::null_mut(),
         };
@@ -160,7 +189,11 @@
         alloc_with_pad_align_in(true, layout, align_layout)
     }
 
-    unsafe fn alloc_with_pad_align_in(zeroed: bool, layout: Layout, align_layout: Layout) -> *mut u8 {
+    unsafe fn alloc_with_pad_align_in(
+        zeroed: bool,
+        layout: Layout,
+        align_layout: Layout,
+    ) -> *mut u8 {
         if !check_layout(&layout) {
             return ptr::null_mut();
         }
@@ -197,7 +230,7 @@
     pub fn pad_align_to(layout: Layout, align_req: &[AlignReq]) -> Result<Layout, AlignLayoutErr> {
         let pad = padding_needed_for(layout, align_req)?;
         let align = align_needed_for(layout, pad)?;
-        Layout::from_size_align(pad + align + layout.size(), align).map_err(|_|AlignLayoutErr)
+        Layout::from_size_align(pad + align + layout.size(), align).map_err(|_| AlignLayoutErr)
     }
 
     fn padding_needed_for(layout: Layout, align_req: &[AlignReq]) -> Result<usize, AlignLayoutErr> {
@@ -231,8 +264,10 @@
     }
 
     fn check_layout(layout: &Layout) -> bool {
-        if layout.size() == 0 || !layout.align().is_power_of_two() ||
-           layout.size() > usize::max_value() - (layout.align() - 1) {
+        if layout.size() == 0
+            || !layout.align().is_power_of_two()
+            || layout.size() > usize::MAX - (layout.align() - 1)
+        {
             false
         } else {
             true
@@ -255,14 +290,18 @@
 
         for req in align_req {
             if check_overflow(req.offset, req.len) || (req.offset + req.len) > size {
-                unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+                unsafe {
+                    libc::free(bmp.as_mut_ptr() as *mut c_void);
+                }
                 return false;
             } else {
                 for i in 0..req.len {
                     let offset = req.offset + i;
                     if (bmp[offset / 8] & 1 << (offset % 8)) != 0 {
                         // overlap in req data
-                        unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+                        unsafe {
+                            libc::free(bmp.as_mut_ptr() as *mut c_void);
+                        }
                         return false;
                     }
                     let tmp: u8 = (1 << (offset % 8)) as u8;
@@ -274,7 +313,7 @@
     }
 
     fn gen_alignmask(al: usize, a: usize, m: u64) -> i64 {
-        if a  > al {
+        if a > al {
             gen_alignmask(al, (a >> 1) as usize, m | (m >> (a >> 1)))
         } else {
             m as i64
@@ -282,13 +321,13 @@
     }
 
     #[inline]
-    fn __rol(v: u64, c: usize, m: usize) -> u64  {
+    fn __rol(v: u64, c: usize, m: usize) -> u64 {
         (v << (c & m)) | (v >> (((0 - c as isize) as usize) & m))
     }
 
     #[inline]
     fn rol(v: i64, c: usize) -> i64 {
-        __rol(v as u64 , c, mem::size_of::<i64>() * 8 - 1) as i64
+        __rol(v as u64, c, mem::size_of::<i64>() * 8 - 1) as i64
     }
 
     fn ror(v: i64, c: usize) -> i64 {
@@ -310,8 +349,13 @@
             -2
         } else {
             count_lzb(
-                !(ror(bmp | ror(bmp, 1) | ror(bmp, 2) | ror(bmp, 3), 5) | ror(bmp, 1)) &
-                gen_alignmask(al, mem::size_of::<u64>() * 8, 1_u64 << (mem::size_of::<u64>() * 8 - 1)))
+                !(ror(bmp | ror(bmp, 1) | ror(bmp, 2) | ror(bmp, 3), 5) | ror(bmp, 1))
+                    & gen_alignmask(
+                        al,
+                        mem::size_of::<u64>() * 8,
+                        1_u64 << (mem::size_of::<u64>() * 8 - 1),
+                    ),
+            )
         }
     }
 
@@ -324,7 +368,7 @@
     }
 
     fn calc_algn(al: usize, size: usize) -> usize {
-        if al > 64  {
+        if al > 64 {
             al
         } else {
             __calc_algn(size, mem::size_of::<u64>() * 8)
@@ -352,4 +396,3 @@
         }
     }
 }
-
diff --git a/sgx_alloc/src/alignbox.rs b/sgx_alloc/src/alignbox.rs
index dede7d6..566d85a 100644
--- a/sgx_alloc/src/alignbox.rs
+++ b/sgx_alloc/src/alignbox.rs
@@ -18,16 +18,16 @@
 //! # align box crate for Rust SGX SDK
 //!
 
-use core::ptr::{Unique, NonNull};
-use core::ops::{DerefMut, Deref};
-use core::mem;
-use core::ptr;
-use core::fmt;
-use core::borrow;
-use core::alloc::Layout;
-use alloc::alloc::handle_alloc_error;
 use super::alignalloc::AlignAlloc;
 pub use super::alignalloc::AlignReq;
+use alloc::alloc::handle_alloc_error;
+use core::alloc::Layout;
+use core::borrow;
+use core::fmt;
+use core::mem;
+use core::ops::{Deref, DerefMut};
+use core::ptr;
+use core::ptr::{NonNull, Unique};
 
 pub struct AlignBox<T> {
     ptr: Unique<T>,
@@ -48,13 +48,13 @@
     type Target = T;
 
     fn deref(&self) -> &T {
-        unsafe{self.ptr.as_ref()}
+        unsafe { self.ptr.as_ref() }
     }
 }
 
 impl<T> DerefMut for AlignBox<T> {
     fn deref_mut(&mut self) -> &mut T {
-       unsafe{self.ptr.as_mut()}
+        unsafe { self.ptr.as_mut() }
     }
 }
 
@@ -101,17 +101,21 @@
     #[rustfmt::skip]
     #[inline]
     fn clone(&self) -> AlignBox<T> {
-        let ptr = match unsafe{AlignAlloc.alloc_with_pad_align_zeroed(self.origin_layout, self.align_layout)} {
+        let ptr = match unsafe {
+            AlignAlloc.alloc_with_pad_align_zeroed(self.origin_layout, self.align_layout)
+        } {
             Ok(p) => p,
             Err(_) => handle_alloc_error(self.align_layout),
         };
         unsafe {
-            ptr::copy_nonoverlapping(&(**self).clone() as *const _ as *const u8,
-                                     ptr.as_ptr(), 
-                                     self.origin_layout.size());
+            ptr::copy_nonoverlapping(
+                &(**self).clone() as *const _ as *const u8,
+                ptr.as_ptr(),
+                self.origin_layout.size(),
+            );
         }
         AlignBox {
-            ptr: ptr.cast().into(),
+            ptr: Unique::new(ptr.cast::<T>().as_ptr()).unwrap(),
             align_layout: self.align_layout,
             origin_layout: self.origin_layout,
         }
@@ -121,18 +125,20 @@
     fn clone_from(&mut self, source: &AlignBox<T>) {
         if source.align_layout.size() != self.align_layout.size() {
             let ptr = match unsafe {
-                AlignAlloc.alloc_with_pad_align_zeroed(source.origin_layout, source.align_layout) 
+                AlignAlloc.alloc_with_pad_align_zeroed(source.origin_layout, source.align_layout)
             } {
                 Ok(p) => p,
                 Err(_) => handle_alloc_error(source.align_layout),
             };
             unsafe {
-                ptr::copy_nonoverlapping(&(**source).clone() as *const _ as *const u8,
-                                         ptr.as_ptr(),
-                                         source.origin_layout.size());
+                ptr::copy_nonoverlapping(
+                    &(**source).clone() as *const _ as *const u8,
+                    ptr.as_ptr(),
+                    source.origin_layout.size(),
+                );
                 self.dealloc_buffer();
             }
-            self.ptr = ptr.cast().into();
+            self.ptr = Unique::new(ptr.cast::<T>().as_ptr()).unwrap();
         } else {
             (**self).clone_from(&(**source));
         }
@@ -168,12 +174,18 @@
     }
 
     fn new_with_align_in(align: usize) -> Option<AlignBox<T>> {
-        let v: [AlignReq; 1] = [AlignReq{ offset:0, len:mem::size_of::<T>() }];
+        let v: [AlignReq; 1] = [AlignReq {
+            offset: 0,
+            len: mem::size_of::<T>(),
+        }];
         AlignBox::allocate_in(true, align, &v)
     }
 
     fn new_in() -> Option<AlignBox<T>> {
-        let v: [AlignReq; 1] = [AlignReq{ offset: 0, len:mem::size_of::<T>() }];
+        let v: [AlignReq; 1] = [AlignReq {
+            offset: 0,
+            len: mem::size_of::<T>(),
+        }];
         AlignBox::allocate_in(true, mem::align_of::<T>(), &v)
     }
 
@@ -186,25 +198,25 @@
             Ok(n) => n,
             Err(_) => return None,
         };
-    
+
         let align_layout = match AlignAlloc.pad_align_to(layout, align_req) {
             Ok(n) => n,
             Err(_) => return None,
         };
-       
+
         // handles ZSTs and `cap = 0` alike
         let result = if zeroed {
-            unsafe{ AlignAlloc.alloc_with_req_zeroed(layout, align_req) }
+            unsafe { AlignAlloc.alloc_with_req_zeroed(layout, align_req) }
         } else {
-            unsafe{ AlignAlloc.alloc_with_req(layout, align_req) }
+            unsafe { AlignAlloc.alloc_with_req(layout, align_req) }
         };
         let ptr = match result {
-            Ok(r) => r.cast(),
+            Ok(p) => p,
             Err(_) => handle_alloc_error(align_layout),
         };
 
-        Some(AlignBox{
-            ptr: ptr.into(),
+        Some(AlignBox {
+            ptr: Unique::new(ptr.cast::<T>().as_ptr()).unwrap(),
             align_layout: align_layout,
             origin_layout: layout,
         })
@@ -215,7 +227,7 @@
     pub fn new() -> Option<AlignBox<T>> {
         Self::new_in()
     }
-     pub fn new_with_align(align: usize) -> Option<AlignBox<T>> {
+    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<AlignBox<T>> {
@@ -250,11 +262,15 @@
             t
         }
     }
-    pub fn heap_init_with_req<F>(initialize: F, align: usize, data: &[AlignReq]) -> Option<AlignBox<T>>
+    pub fn heap_init_with_req<F>(
+        initialize: F,
+        align: usize,
+        data: &[AlignReq],
+    ) -> Option<AlignBox<T>>
     where
         F: Fn(&mut T),
     {
-      unsafe {
+        unsafe {
             let mut t = Self::new_with_req(align, data);
             match t {
                 Some(ref mut b) => initialize(b.ptr.as_mut()),
@@ -264,4 +280,3 @@
         }
     }
 }
-
diff --git a/sgx_alloc/src/lib.rs b/sgx_alloc/src/lib.rs
index ddf8fb6..32d7165 100644
--- a/sgx_alloc/src/lib.rs
+++ b/sgx_alloc/src/lib.rs
@@ -23,11 +23,8 @@
 //! 2018-06-22 Add liballoc components here
 
 #![no_std]
-
 #![allow(non_camel_case_types)]
-
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
-
 #![feature(alloc_layout_extra)]
 #![feature(ptr_internals)]
 #![feature(dropck_eyepatch)]
diff --git a/sgx_alloc/src/rsrvmem.rs b/sgx_alloc/src/rsrvmem.rs
index 15e9f7b..7248637 100644
--- a/sgx_alloc/src/rsrvmem.rs
+++ b/sgx_alloc/src/rsrvmem.rs
@@ -15,9 +15,9 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use core::ptr::NonNull;
-use core::fmt;
 pub use self::platform::*;
+use core::fmt;
+use core::ptr::NonNull;
 
 pub struct RsrvMemAlloc;
 
@@ -30,8 +30,8 @@
 }
 
 impl RsrvMemAlloc {
-    #[inline]
-    /// Allocate a range of EPC memory from the reserved memory area with RW permission
+    
+    /// Allocate a range of EPC memory from the reserved memory area
     ///
     /// # Parameters
     ///
@@ -43,10 +43,32 @@
     ///
     /// Starting address of the new allocated memory area on success;
     ///
+    #[inline]
     pub unsafe fn alloc(&mut self, count: u32) -> Result<NonNull<u8>, RsrvMemAllocErr> {
         NonNull::new(platform::alloc(count)).ok_or(RsrvMemAllocErr)
     }
 
+    /// Allocate a range of EPC memory with a fixed address from the reserved memory area
+    ///
+    /// # Parameters
+    ///
+    /// **addr**
+    /// 
+    /// The desired starting address to allocate the reserved memory. Should be page aligned.
+    /// 
+    /// **count**
+    ///
+    /// Count of pages to allocate region
+    ///
+    /// # Return value
+    ///
+    /// Starting address of the new allocated memory area on success;
+    ///
+    #[inline]
+    pub unsafe fn alloc_with_addr(&mut self, addr: NonNull<u8>, count: u32) -> Result<NonNull<u8>, RsrvMemAllocErr> {
+        NonNull::new(platform::alloc_with_addr(addr.as_ptr(), count)).ok_or(RsrvMemAllocErr)
+    }
+
     #[inline]
     pub unsafe fn alloc_zeroed(&mut self, count: u32) -> Result<NonNull<u8>, RsrvMemAllocErr> {
         NonNull::new(platform::alloc_zeroed(count)).ok_or(RsrvMemAllocErr)
@@ -88,7 +110,12 @@
     /// The target memory protection.
     ///
     #[inline]
-    pub unsafe fn protect(&self, addr: NonNull<u8>, count: u32, prot: ProtectAttr) -> Result<(), RsrvMemAllocErr> {
+    pub unsafe fn protect(
+        &self,
+        addr: NonNull<u8>,
+        count: u32,
+        prot: ProtectAttr,
+    ) -> Result<(), RsrvMemAllocErr> {
         platform::protect(addr.as_ptr(), count, prot)
     }
 }
@@ -103,15 +130,15 @@
 }
 
 mod platform {
-    use super::RsrvMemAllocErr;
     use super::ProtectAttr;
+    use super::RsrvMemAllocErr;
     use core::ffi::c_void;
     use core::ptr;
 
-    const SGX_PROT_READ:  u32 = 0x1;
+    const SGX_PROT_READ: u32 = 0x1;
     const SGX_PROT_WRITE: u32 = 0x2;
-    const SGX_PROT_EXEC:  u32 = 0x4;
-    const SE_PAGE_SIZE:   usize =  0x1000;
+    const SGX_PROT_EXEC: u32 = 0x4;
+    const SE_PAGE_SIZE: usize = 0x1000;
 
     type size_t = usize;
     type int32_t = i32;
@@ -119,15 +146,25 @@
 
     extern "C" {
         pub fn sgx_alloc_rsrv_mem(length: size_t) -> *mut c_void;
+        pub fn sgx_alloc_rsrv_mem_ex(desired_addr: *const c_void, 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;  
+        pub fn sgx_tprotect_rsrv_mem(
+            addr: *const c_void,
+            length: size_t,
+            prot: i32,
+        ) -> sgx_status_t;
     }
 
     #[inline]
     pub unsafe fn alloc(count: u32) -> *mut u8 {
         sgx_alloc_rsrv_mem(count as usize * SE_PAGE_SIZE) as *mut u8
     }
-    
+
+    #[inline]
+    pub unsafe fn alloc_with_addr(addr: *mut u8, count: u32) -> *mut u8 {
+        sgx_alloc_rsrv_mem_ex(addr as *const c_void, count as usize * SE_PAGE_SIZE) as *mut u8
+    }
+
     #[inline]
     pub unsafe fn alloc_zeroed(count: u32) -> *mut u8 {
         let raw = alloc(count);
@@ -139,8 +176,7 @@
 
     #[inline]
     pub unsafe fn dealloc(addr: *mut u8, count: u32) -> Result<(), RsrvMemAllocErr> {
-        if sgx_free_rsrv_mem(addr as *const c_void,
-                             count as usize * SE_PAGE_SIZE) == 0 {
+        if sgx_free_rsrv_mem(addr as *const c_void, count as usize * SE_PAGE_SIZE) == 0 {
             Ok(())
         } else {
             Err(RsrvMemAllocErr)
@@ -148,19 +184,26 @@
     }
 
     #[inline]
-    pub unsafe fn protect(addr: *mut u8, count: u32, prot: ProtectAttr) -> Result<(), RsrvMemAllocErr> {
+    pub unsafe fn protect(
+        addr: *mut u8,
+        count: u32,
+        prot: ProtectAttr,
+    ) -> Result<(), RsrvMemAllocErr> {
         let attr = match prot {
-            ProtectAttr::Read => { SGX_PROT_READ } ,
-            ProtectAttr::ReadWrite => { SGX_PROT_READ | SGX_PROT_WRITE },
-            ProtectAttr::ReadExec => {SGX_PROT_READ | SGX_PROT_EXEC },
-            ProtectAttr::ReadWriteExec => { SGX_PROT_READ | SGX_PROT_WRITE | SGX_PROT_EXEC },
+            ProtectAttr::Read => SGX_PROT_READ,
+            ProtectAttr::ReadWrite => SGX_PROT_READ | SGX_PROT_WRITE,
+            ProtectAttr::ReadExec => SGX_PROT_READ | SGX_PROT_EXEC,
+            ProtectAttr::ReadWriteExec => SGX_PROT_READ | SGX_PROT_WRITE | SGX_PROT_EXEC,
         };
-        if sgx_tprotect_rsrv_mem(addr as *const c_void,
-                                 count as usize * SE_PAGE_SIZE,
-                                 attr as i32) == 0 {
+        if sgx_tprotect_rsrv_mem(
+            addr as *const c_void,
+            count as usize * SE_PAGE_SIZE,
+            attr as i32,
+        ) == 0
+        {
             Ok(())
         } else {
-            Err(RsrvMemAllocErr) 
+            Err(RsrvMemAllocErr)
         }
     }
 }
diff --git a/sgx_alloc/src/system.rs b/sgx_alloc/src/system.rs
index 771fe72..5a5e688 100644
--- a/sgx_alloc/src/system.rs
+++ b/sgx_alloc/src/system.rs
@@ -23,13 +23,7 @@
 //! 2018-06-22 Add liballoc components here
 
 use core::alloc::{
-    AllocInit,
-    AllocRef,
-    AllocErr,
-    GlobalAlloc,
-    Layout,
-    MemoryBlock,
-    ReallocPlacement
+    AllocErr, AllocInit, AllocRef, GlobalAlloc, Layout, MemoryBlock, ReallocPlacement,
 };
 use core::intrinsics;
 use core::ptr::NonNull;
@@ -53,7 +47,10 @@
         unsafe {
             let size = layout.size();
             if size == 0 {
-                Ok(MemoryBlock { ptr: layout.dangling(), size: 0 })
+                Ok(MemoryBlock {
+                    ptr: layout.dangling(),
+                    size: 0,
+                })
             } else {
                 let raw_ptr = match init {
                     AllocInit::Uninitialized => GlobalAlloc::alloc(self, layout),
@@ -101,8 +98,10 @@
                 // `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 };
+                let memory = MemoryBlock {
+                    ptr: NonNull::new(ptr).ok_or(AllocErr)?,
+                    size: new_size,
+                };
                 init.init_offset(memory, size);
                 Ok(memory)
             }
@@ -131,13 +130,19 @@
             ReallocPlacement::InPlace => Err(AllocErr),
             ReallocPlacement::MayMove if new_size == 0 => {
                 self.dealloc(ptr, layout);
-                Ok(MemoryBlock { ptr: layout.dangling(), size: 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 })
+                Ok(MemoryBlock {
+                    ptr: NonNull::new(ptr).ok_or(AllocErr)?,
+                    size: new_size,
+                })
             }
         }
     }
@@ -171,10 +176,10 @@
 
 mod platform {
     use super::*;
-    use libc;
+    use core::alloc::{GlobalAlloc, Layout};
     use core::ffi::c_void;
     use core::ptr;
-    use core::alloc::{GlobalAlloc, Layout};
+    use libc;
 
     unsafe impl GlobalAlloc for System {
         #[inline]
@@ -187,9 +192,7 @@
         }
 
         #[inline]
-        unsafe fn alloc_zeroed(&self, layout: Layout)
-            -> *mut u8
-        {
+        unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
             if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
                 libc::calloc(layout.size(), 1) as *mut u8
             } else {
@@ -207,10 +210,7 @@
         }
 
         #[inline]
-        unsafe fn realloc(&self,
-                          ptr: *mut u8,
-                          layout: Layout,
-                          new_size: usize) -> *mut u8 {
+        unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
             if layout.align() <= MIN_ALIGN && layout.align() <= new_size {
                 libc::realloc(ptr as *mut c_void, new_size) as *mut u8
             } else {
diff --git a/sgx_backtrace_sys/build.rs b/sgx_backtrace_sys/build.rs
index 6a2dd32..d24b25a 100644
--- a/sgx_backtrace_sys/build.rs
+++ b/sgx_backtrace_sys/build.rs
@@ -26,6 +26,10 @@
 }
 
 fn build_libbacktrace(_target: &str) -> Result<(), ()> {
+    let sdk_dir = env::var("SGX_SDK")
+                    .unwrap_or_else(|_| "/opt/intel/sgxsdk".to_string());
+    let sdk_include = format!("{}/{}", sdk_dir, "include");
+
     let native = native_lib_boilerplate(
                     "sgx_backtrace_sys/libbacktrace",
                     "libbacktrace",
@@ -44,6 +48,7 @@
         .flag("-fvisibility=hidden")
         .include("./libbacktrace")
         .include(&native.out_dir)
+        .include(&sdk_include)
         .out_dir(&native.out_dir)
         .warnings(false)
         .file("./libbacktrace/mmap.c")
diff --git a/sgx_backtrace_sys/libbacktrace/mmap.c b/sgx_backtrace_sys/libbacktrace/mmap.c
index 9287c45..c4c64ec 100644
--- a/sgx_backtrace_sys/libbacktrace/mmap.c
+++ b/sgx_backtrace_sys/libbacktrace/mmap.c
@@ -43,6 +43,7 @@
 #include "backtrace_t.h"
 #include "internal.h"
 
+#include "sgx_trts.h"
 /* Memory allocation on systems that provide anonymous mmap.  This
    permits the backtrace functions to be invoked from a signal
    handler, assuming that mmap is async-signal safe.  */
@@ -185,6 +186,11 @@
             return ret;
         }
 
+        if (!sgx_is_outside_enclave(page, asksize)) {
+            error_callback(data, "mmap result error", error);
+            return 0;
+        }
+
         //page = mmap (NULL, asksize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
         if (page == MAP_FAILED) {
             if (error_callback) {
diff --git a/sgx_backtrace_sys/libbacktrace/mmapio.c b/sgx_backtrace_sys/libbacktrace/mmapio.c
index ff5eb79..dce4e99 100644
--- a/sgx_backtrace_sys/libbacktrace/mmapio.c
+++ b/sgx_backtrace_sys/libbacktrace/mmapio.c
@@ -41,6 +41,8 @@
 #include "backtrace_t.h"
 #include "internal.h"
 
+#include "sgx_trts.h"
+
 #ifndef PROT_READ
 #define PROT_READ 0x1
 #endif
@@ -94,6 +96,11 @@
         return 0;
     }
 
+    if (!sgx_is_outside_enclave(map, size)) {
+        error_callback(data, "mmap result error", error);
+        return 0;
+    }
+
     //map = mmap (NULL, size, PROT_READ, MAP_PRIVATE, descriptor, pageoff);
     if (map == MAP_FAILED) {
         error_callback(data, "mmap", error);
diff --git a/sgx_cov/lib.rs b/sgx_cov/lib.rs
index b08e98a..34b7dd0 100644
--- a/sgx_cov/lib.rs
+++ b/sgx_cov/lib.rs
@@ -16,7 +16,10 @@
 // under the License..
 
 #![cfg_attr(not(target_env = "sgx"), no_std)]
-#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))]
+#![cfg_attr(
+    all(target_env = "sgx", target_vendor = "mesalock"),
+    feature(rustc_private)
+)]
 
 #[cfg(not(target_env = "sgx"))]
 #[macro_use]
diff --git a/sgx_edl/edl/intel/sgx_dcap_tvl.edl b/sgx_edl/edl/intel/sgx_dcap_tvl.edl
new file mode 100644
index 0000000..7c5c0d8
--- /dev/null
+++ b/sgx_edl/edl/intel/sgx_dcap_tvl.edl
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2011-2020 Intel Corporation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   * Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *   * Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in
+ *     the documentation and/or other materials provided with the
+ *     distribution.
+ *   * Neither the name of Intel Corporation nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+enclave {
+
+    include "sgx_qve_header.h"
+    include "sgx_ql_quote.h"
+
+
+    trusted {
+
+    /**
+     * Verify QvE Report and Identity
+     *
+     * @param p_quote[IN] - Pointer to SGX Quote.
+     * @param quote_size[IN] - Size of the buffer pointed to by p_quote (in bytes).
+     * @param p_qve_report_info[IN] - The output of API "sgx_qv_verify_quote", it should contain QvE report and nonce
+     * @param expiration_check_date[IN] - This is the date to verify QvE report data, you should use same value for this API and "sgx_qv_verify_quote"
+     * @param collateral_expiration_status[IN] - The output of API "sgx_qv_verify_quote" about quote verification collateral's expiration status
+     * @param quote_verification_result[IN] - The output of API "sgx_qv_verify_quote" about quote verification result
+     * @param p_supplemental_data[IN] - The output of API "sgx_qv_verify_quote", the pointer to supplemental data
+     * @param supplemental_data_size[IN] - Size of the buffer pointed to by p_quote (in bytes)
+     * @param qve_isvsvn_threshold [IN] - The threshold of QvE ISVSVN, the ISVSVN of QvE used to verify quote must be greater or equal to this threshold. You can get latest QvE ISVSVN in QvE Identity (JSON) from Intel PCS.
+     *
+     * @return Status code of the operation, one of:
+     *   - SGX_QL_SUCCESS
+     *   - SGX_QL_ERROR_INVALID_PARAMETER
+     *   - SGX_QL_ERROR_REPORT           // Error when verifying QvE report
+     *   - SGX_QL_ERROR_UNEXPECTED       // Error when comparing QvE report data
+     *   - SGX_QL_QVEIDENTITY_MISMATCH   // Error when comparing QvE identity
+     *   - SGX_QL_QVE_OUT_OF_DATE        // QvE ISVSVN is smaller than input QvE ISV SVN threshold
+     **/
+
+        public quote3_error_t sgx_tvl_verify_qve_report_and_identity(
+            [in, size=quote_size] const uint8_t *p_quote,
+            uint32_t quote_size,
+            [in, count=1] const sgx_ql_qe_report_info_t *p_qve_report_info,
+            time_t expiration_check_date,
+            uint32_t collateral_expiration_status,
+            sgx_ql_qv_result_t quote_verification_result,
+            [in, size=supplemental_data_size] const uint8_t *p_supplemental_data,
+            uint32_t supplemental_data_size,
+            sgx_isv_svn_t qve_isvsvn_threshold);
+    };
+};
diff --git a/sgx_libc/src/android/aarch64/mod.rs b/sgx_libc/src/android/aarch64/mod.rs
index 1db1324..46950e2 100644
--- a/sgx_libc/src/android/aarch64/mod.rs
+++ b/sgx_libc/src/android/aarch64/mod.rs
@@ -13,4 +13,4 @@
 // "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..
\ No newline at end of file
+// under the License..
diff --git a/sgx_libc/src/linux/mod.rs b/sgx_libc/src/linux/mod.rs
index b8cdd89..f05c8e9 100644
--- a/sgx_libc/src/linux/mod.rs
+++ b/sgx_libc/src/linux/mod.rs
@@ -22,4 +22,4 @@
     } else {
 
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_libc/src/macros.rs b/sgx_libc/src/macros.rs
index d946f7a..e105de9 100644
--- a/sgx_libc/src/macros.rs
+++ b/sgx_libc/src/macros.rs
@@ -160,4 +160,4 @@
             __align: [],
         };
     )*)
-}
\ No newline at end of file
+}
diff --git a/sgx_serialize_derive/src/decode.rs b/sgx_serialize_derive/src/decode.rs
index 3e94ac4..c2ec7b1 100644
--- a/sgx_serialize_derive/src/decode.rs
+++ b/sgx_serialize_derive/src/decode.rs
@@ -92,7 +92,7 @@
     cont: &Container,
     variants: &[Variant]
 ) -> Fragment {
-    assert!(variants.len() as u64 <= u32::max_value() as u64);
+    assert!(variants.len() as u64 <= u32::MAX as u64);
 
     let name: syn::Ident = cont.ident.clone().into();
     let name_arg = fromat_ident(&name);
diff --git a/sgx_serialize_derive/src/encode.rs b/sgx_serialize_derive/src/encode.rs
index d3697a0..268c2d9 100644
--- a/sgx_serialize_derive/src/encode.rs
+++ b/sgx_serialize_derive/src/encode.rs
@@ -93,7 +93,7 @@
     params: &Parameters,
     variants: &[Variant]
 ) -> Fragment {
-    assert!(variants.len() as u64 <= u32::max_value() as u64);
+    assert!(variants.len() as u64 <= u32::MAX as u64);
 
     let self_var = &params.self_var;
 
diff --git a/sgx_signal/LICENSE b/sgx_signal/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/sgx_signal/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed 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.
diff --git a/sgx_signal/Readme.md b/sgx_signal/Readme.md
new file mode 100644
index 0000000..ba97d9b
--- /dev/null
+++ b/sgx_signal/Readme.md
@@ -0,0 +1,3 @@
+# Note
+
+Please visit our [homepage](https://github.com/apache/teaclave-sgx-sdk) for usage. Thanks!
diff --git a/sgx_signal/src/exception.rs b/sgx_signal/src/exception.rs
index f1a38b9..9b3f512 100644
--- a/sgx_signal/src/exception.rs
+++ b/sgx_signal/src/exception.rs
@@ -15,21 +15,21 @@
 // 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
+    exception_handle, rsgx_register_exception_handler, rsgx_unregister_exception_handler,
 };
+use sgx_types::SE_WORDSIZE;
+use sgx_types::{sgx_exception_info_t, sgx_exception_vector_t};
+use sgx_types::{EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH};
+use std::collections::LinkedList;
+use std::num::NonZeroU64;
+use std::ops::Drop;
+use std::sync::{Arc, Once, SgxRwLock, SgxThreadMutex, ONCE_INIT};
+use std::u64;
 
+#[repr(u32)]
+#[derive(Copy, Clone, PartialEq, Eq)]
 pub enum ContinueType {
     Search,
     Execution,
@@ -76,10 +76,7 @@
 impl HandlerNode {
     // add code here
     pub fn new(id: HandlerId, handler: Arc<ExceptionHandler>) -> Self {
-        HandlerNode {
-            id,
-            handler,
-        }
+        HandlerNode { id, handler }
     }
     pub fn get_handler_id(&self) -> HandlerId {
         self.id
@@ -113,12 +110,12 @@
     }
 }
 
-extern "C" fn native_exception_handler(info : *mut sgx_exception_info_t) -> int32_t {
+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::Search => {}
                 ContinueType::Execution => return EXCEPTION_CONTINUE_EXECUTION,
             }
         }
@@ -126,16 +123,15 @@
     unsafe { panic_handler(info).into() }
 }
 
-unsafe extern "C" fn panic_handler(info : *mut sgx_exception_info_t) -> ContinueType {
+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;
+        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;
@@ -187,7 +183,7 @@
     }
 }
 
-fn register_exception_impl<F>(is_first_handler: bool, handler: F) -> Option<HandlerId>
+fn register_exception_impl<F>(first: bool, handler: F) -> Option<HandlerId>
 where
     F: Fn(&mut sgx_exception_info_t) -> ContinueType + Sync + Send + 'static,
 {
@@ -195,7 +191,7 @@
 
     if let Ok(ref mut handlers) = globals.manager.exception_handler.write() {
         let handler_id = HandlerId::new();
-        if is_first_handler {
+        if first {
             handlers.push_front(HandlerNode::new(handler_id, Arc::from(handler)));
         } else {
             handlers.push_back(HandlerNode::new(handler_id, Arc::from(handler)));
@@ -252,11 +248,10 @@
 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()
+        handlers
+            .drain_filter(|n| n.get_handler_id() == id)
+            .next()
+            .is_some()
     } else {
         false
     }
diff --git a/sgx_signal/src/lib.rs b/sgx_signal/src/lib.rs
index 8cf5c8a..8d0c88d 100644
--- a/sgx_signal/src/lib.rs
+++ b/sgx_signal/src/lib.rs
@@ -16,17 +16,19 @@
 // under the License..
 
 #![cfg_attr(not(target_env = "sgx"), no_std)]
-#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), 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;
 
-extern crate sgx_types;
-extern crate sgx_trts;
 extern crate sgx_libc;
+extern crate sgx_trts;
+extern crate sgx_types;
 
 pub mod signal;
 pub use self::signal::*;
diff --git a/sgx_signal/src/manager.rs b/sgx_signal/src/manager.rs
index 811a51d..81a9008 100644
--- a/sgx_signal/src/manager.rs
+++ b/sgx_signal/src/manager.rs
@@ -14,19 +14,19 @@
 // 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 sgx_libc::{c_int, c_void};
+use sgx_libc::{
+    sigaction, sigaddset, sigdelset, sigemptyset, sigfillset, siginfo_t, sigismember, sigset_t,
+};
+use sgx_libc::{NSIG, SA_SIGINFO, SIGRTMAX};
 use std::cell::Cell;
+use std::collections::{BTreeMap, HashMap, HashSet};
 use std::mem;
 use std::num::NonZeroU64;
+use std::sync::Arc;
+#[allow(deprecated)]
+use std::sync::{SgxMutex, SgxThreadMutex};
 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()) }
 
@@ -34,7 +34,6 @@
 pub struct SigNum(i32);
 
 impl SigNum {
-    // add code here
     pub fn from_raw(signo: i32) -> Option<SigNum> {
         if signo <= 0 || signo >= NSIG {
             None
@@ -47,13 +46,14 @@
         SigNum(signo)
     }
 
-    pub fn raw(&self) -> i32 { self.0 }
+    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();
@@ -62,9 +62,12 @@
         };
         SigSet(set)
     }
+
     #[allow(dead_code)]
     pub fn empty(&mut self) {
-        unsafe { sigemptyset(&mut self.0 as *mut sigset_t); }
+        unsafe {
+            sigemptyset(&mut self.0 as *mut sigset_t);
+        }
     }
 
     pub fn add(&mut self, signo: SigNum) -> bool {
@@ -76,7 +79,9 @@
     }
 
     pub fn fill(&mut self) {
-        unsafe { sigfillset(&mut self.0 as *mut sigset_t); }
+        unsafe {
+            sigfillset(&mut self.0 as *mut sigset_t);
+        }
     }
 
     pub fn is_member(&self, signo: SigNum) -> bool {
@@ -106,7 +111,7 @@
 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)};
+        let signo = unsafe { SigNum::from_raw_uncheck(num) };
         if set.is_member(signo) {
             old_mask.add(signo);
         }
@@ -127,12 +132,12 @@
 
 #[inline]
 pub fn get_block_mask() -> SigSet {
-    SIGNAL_MASK.with(|s|s.get())
+    SIGNAL_MASK.with(|s| s.get())
 }
 
 #[inline]
 pub fn set_block_mask(set: SigSet) {
-    SIGNAL_MASK.with(|s|s.set(set));
+    SIGNAL_MASK.with(|s| s.set(set));
 }
 
 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
@@ -190,7 +195,6 @@
 }
 
 impl SignalManager {
-    // add code here
     pub fn new() -> Self {
         SignalManager {
             action_set: SgxMutex::new(HashMap::new()),
@@ -200,52 +204,41 @@
 
     pub fn set_action(&self, signo: SigNum, act: &sigaction) {
         self.action_set
-        .lock()
-        .unwrap()
-        .insert(signo, ActionSlot::new(act));
+            .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 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);
+            self.action_set.lock().unwrap().insert(signo, slot);
             id
         } else {
             self.action_set
                 .lock()
                 .unwrap()
                 .get_mut(&signo)
-                .map(|slot|slot.set(action)).unwrap()
+                .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) {
+        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) {
+    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
@@ -253,32 +246,19 @@
     }
 
     pub fn clear_action(&self, signo: SigNum) -> bool {
-        self.action_set
-            .lock()
-            .unwrap()
-            .remove(&signo)
-            .is_some()
+        self.action_set.lock().unwrap().remove(&signo).is_some()
     }
 
     pub fn is_action_empty(&self) -> bool {
-        self.action_set
-            .lock()
-            .unwrap()
-            .is_empty()
+        self.action_set.lock().unwrap().is_empty()
     }
 
     pub fn set_reset_on_handle(&self, signo: SigNum) {
-        self.reset_set
-            .lock()
-            .unwrap()
-            .insert(signo);
+        self.reset_set.lock().unwrap().insert(signo);
     }
 
     pub fn is_reset_on_handle(&self, signo: SigNum) -> bool {
-        self.reset_set
-            .lock()
-            .unwrap()
-            .contains(&signo)
+        self.reset_set.lock().unwrap().contains(&signo)
     }
 
     pub unsafe fn handler(&self, signum: i32, info: *const siginfo_t, context: *const c_void) {
@@ -304,10 +284,12 @@
         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());
+            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());
+            let fn_sa_handler =
+                mem::transmute::<*const (), FnSaHandler>(act.sa_sigaction as *const ());
             fn_sa_handler(signo.raw());
         }
 
diff --git a/sgx_signal/src/signal.rs b/sgx_signal/src/signal.rs
index 3ebdd5e..9af87a2 100644
--- a/sgx_signal/src/signal.rs
+++ b/sgx_signal/src/signal.rs
@@ -15,31 +15,24 @@
 // 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 crate::manager::{self, ActionId, SigNum, SigSet, SignalManager};
+use sgx_libc::ocall::{raise, sigaction, sigprocmask};
 use sgx_libc::set_errno;
+use sgx_libc::{sigaction, sigemptyset, sighandler_t, siginfo_t, sigset_t};
 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
+    SA_RESETHAND, SIGBUS, SIGFPE, SIGILL, SIGKILL, SIGSEGV, SIGSTOP, SIGTRAP, SIG_BLOCK, SIG_DFL,
+    SIG_ERR, SIG_SETMASK, SIG_UNBLOCK,
 };
-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};
+use sgx_types::{c_int, c_void, sgx_enclave_id_t, sgx_status_t, SysResult};
+use std::enclave::get_enclave_id;
+use std::io::Error;
+use std::mem;
+use std::rt::*;
+use std::sync::{Arc, Once, SgxMutex};
 
 pub const FORBIDDEN: &[c_int] = FORBIDDEN_IMPL;
-const FORBIDDEN_IMPL: &[c_int] = &[SIGKILL,
-                                   SIGSTOP,
-                                   SIGILL,
-                                   SIGFPE,
-                                   SIGSEGV,
-                                   SIGBUS,
-                                   SIGTRAP];
+const FORBIDDEN_IMPL: &[c_int] = &[SIGKILL, SIGSTOP, SIGILL, SIGFPE, SIGSEGV, SIGBUS, SIGTRAP];
 
 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
 pub struct SignalId {
@@ -48,8 +41,8 @@
 }
 
 struct GlobalData {
-   signal_manager: SignalManager,
-   signal_action_lock: SgxMutex<()>,
+    signal_manager: SignalManager,
+    signal_action_lock: SgxMutex<()>,
 }
 
 static mut GLOBAL_DATA: Option<GlobalData> = None;
@@ -60,7 +53,6 @@
 }
 
 impl GlobalData {
-    // add code here
     fn get() -> &'static Self {
         unsafe { GLOBAL_DATA.as_ref().unwrap() }
     }
@@ -72,14 +64,13 @@
                 signal_action_lock: SgxMutex::new(()),
             });
 
-            let _r = at_exit(|| Self::clear() );
+            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()) };
         }
     }
@@ -98,12 +89,13 @@
     unsafe {
         let signo = SigNum::from_raw_uncheck(si_info.si_signo);
         if mask.is_member(signo) {
-           -1
+            -1
         } else {
             global.signal_manager.handler(
                 si_info.si_signo,
                 info as *const siginfo_t,
-                0 as *const c_void);
+                0 as *const c_void,
+            );
             0
         }
     }
@@ -240,7 +232,7 @@
     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  {
+    if rsgx_sigaction(signum, &act, &mut oldact) != 0 {
         // Errno is set by sigaction.
         return SIG_ERR;
     }
@@ -270,13 +262,7 @@
     // 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,
-        )
-    };
+    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
@@ -319,7 +305,9 @@
     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));
+        return Err(Error::from_sgx_error(
+            sgx_status_t::SGX_ERROR_INVALID_ENCLAVE_ID,
+        ));
     }
 
     let signo = match SigNum::from_raw(signal) {
@@ -333,21 +321,12 @@
     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 {
+    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)
-    )
+        })
+        .map_err(|err| Error::from_raw_os_error(err))
 }
 
 pub fn unregister(id: SignalId) -> bool {
@@ -362,5 +341,5 @@
 }
 
 pub fn raise_signal(signal: c_int) -> bool {
-   rsgx_raise(signal) == 0
+    rsgx_raise(signal) == 0
 }
diff --git a/sgx_tcrypto/src/crypto.rs b/sgx_tcrypto/src/crypto.rs
index a34b583..2a9e84c 100644
--- a/sgx_tcrypto/src/crypto.rs
+++ b/sgx_tcrypto/src/crypto.rs
@@ -18,12 +18,12 @@
 //!
 //! Cryptographic Functions
 //!
-use sgx_types::*;
-use sgx_types::marker::ContiguousMemory;
-use core::ops::{Drop, DerefMut};
-use core::ptr;
-use core::mem;
 use core::cell::{Cell, RefCell};
+use core::mem;
+use core::ops::{DerefMut, Drop};
+use core::ptr;
+use sgx_types::marker::ContiguousMemory;
+use sgx_types::*;
 
 ///
 /// The rsgx_sha256_msg function performs a standard SHA256 hash over the input data buffer.
@@ -74,12 +74,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha256_hash_t::default();
-    let ret = unsafe { sgx_sha256_msg(src as *const _ as *const u8, size as u32, &mut hash as *mut sgx_sha256_hash_t) };
+    let ret = unsafe {
+        sgx_sha256_msg(
+            src as *const _ as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha256_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -97,12 +103,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha256_hash_t::default();
-    let ret = unsafe { sgx_sha256_msg(src.as_ptr() as *const u8, size as u32, &mut hash as *mut sgx_sha256_hash_t) };
+    let ret = unsafe {
+        sgx_sha256_msg(
+            src.as_ptr() as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha256_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -110,9 +122,7 @@
 }
 
 fn rsgx_sha256_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-    unsafe {
-        sgx_sha256_init(sha_handle as *mut sgx_sha_state_handle_t)
-    }
+    unsafe { sgx_sha256_init(sha_handle as *mut sgx_sha_state_handle_t) }
 }
 
 fn rsgx_sha256_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -123,13 +133,11 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    unsafe {
-        sgx_sha256_update(src as *const _ as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha256_update(src as *const _ as *const u8, size as u32, sha_handle) }
 }
 
 fn rsgx_sha256_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -140,20 +148,21 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_sha256_update(src.as_ptr() as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha256_update(src.as_ptr() as *const u8, size as u32, sha_handle) }
 }
 
-fn rsgx_sha256_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha256_hash_t) -> sgx_status_t {
+fn rsgx_sha256_get_hash(
+    sha_handle: sgx_sha_state_handle_t,
+    hash: &mut sgx_sha256_hash_t,
+) -> sgx_status_t {
     unsafe { sgx_sha256_get_hash(sha_handle, hash as *mut sgx_sha256_hash_t) }
 }
 
 fn rsgx_sha256_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-     unsafe { sgx_sha256_close(sha_handle) }
+    unsafe { sgx_sha256_close(sha_handle) }
 }
 
 pub fn rsgx_sha1_msg<T>(src: &T) -> SgxResult<sgx_sha1_hash_t>
@@ -164,12 +173,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha1_hash_t::default();
-    let ret = unsafe { sgx_sha1_msg(src as *const _ as *const u8, size as u32, &mut hash as *mut sgx_sha1_hash_t) };
+    let ret = unsafe {
+        sgx_sha1_msg(
+            src as *const _ as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha1_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -184,12 +199,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha1_hash_t::default();
-    let ret = unsafe { sgx_sha1_msg(src.as_ptr() as *const u8, size as u32, &mut hash as *mut sgx_sha1_hash_t) };
+    let ret = unsafe {
+        sgx_sha1_msg(
+            src.as_ptr() as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha1_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -197,9 +218,7 @@
 }
 
 fn rsgx_sha1_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-    unsafe {
-        sgx_sha1_init(sha_handle as *mut sgx_sha_state_handle_t)
-    }
+    unsafe { sgx_sha1_init(sha_handle as *mut sgx_sha_state_handle_t) }
 }
 
 fn rsgx_sha1_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -210,13 +229,11 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    unsafe {
-        sgx_sha1_update(src as *const _ as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha1_update(src as *const _ as *const u8, size as u32, sha_handle) }
 }
 
 fn rsgx_sha1_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -227,20 +244,21 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_sha1_update(src.as_ptr() as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha1_update(src.as_ptr() as *const u8, size as u32, sha_handle) }
 }
 
-fn rsgx_sha1_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha1_hash_t) -> sgx_status_t {
+fn rsgx_sha1_get_hash(
+    sha_handle: sgx_sha_state_handle_t,
+    hash: &mut sgx_sha1_hash_t,
+) -> sgx_status_t {
     unsafe { sgx_sha1_get_hash(sha_handle, hash as *mut sgx_sha1_hash_t) }
 }
 
 fn rsgx_sha1_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-     unsafe { sgx_sha1_close(sha_handle) }
+    unsafe { sgx_sha1_close(sha_handle) }
 }
 
 ///
@@ -255,12 +273,11 @@
 }
 
 impl SgxShaHandle {
-
     ///
     /// Constructs a new, empty SgxShaHandle.
     ///
     pub fn new() -> SgxShaHandle {
-        SgxShaHandle{
+        SgxShaHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_sha_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -479,7 +496,6 @@
 }
 
 impl Drop for SgxShaHandle {
-
     ///
     /// drop cleans up and deallocates the SHA256 state that was allocated in function init.
     ///
@@ -495,7 +511,7 @@
 
 impl SgxSha1Handle {
     pub fn new() -> SgxSha1Handle {
-        SgxSha1Handle{
+        SgxSha1Handle {
             handle: RefCell::new(ptr::null_mut() as sgx_sha_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -591,7 +607,6 @@
 }
 
 impl Drop for SgxSha1Handle {
-
     ///
     /// drop cleans up and deallocates the SHA256 state that was allocated in function init.
     ///
@@ -682,7 +697,7 @@
     mac: &mut sgx_aes_gcm_128bit_tag_t,
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let iv_len = iv.len();
@@ -690,11 +705,11 @@
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let aad_len = aad.len();
-    if aad_len > u32::max_value() as usize {
+    if aad_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -702,7 +717,11 @@
     }
 
     let ret = unsafe {
-        let p_aad = if aad_len != 0 { aad.as_ptr() } else { ptr::null() };
+        let p_aad = if aad_len != 0 {
+            aad.as_ptr()
+        } else {
+            ptr::null()
+        };
 
         let (p_src, p_dst) = if src_len != 0 {
             (src.as_ptr(), dst.as_mut_ptr())
@@ -813,7 +832,7 @@
     dst: &mut [u8],
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let iv_len = iv.len();
@@ -821,11 +840,11 @@
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let aad_len = aad.len();
-    if aad_len > u32::max_value() as usize {
+    if aad_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -833,7 +852,11 @@
     }
 
     let ret = unsafe {
-        let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
+        let p_aad = if !aad.is_empty() {
+            aad.as_ptr()
+        } else {
+            ptr::null()
+        };
 
         let (p_src, p_dst) = if src_len != 0 {
             (src.as_ptr(), dst.as_mut_ptr())
@@ -903,7 +926,10 @@
 ///
 /// 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>
+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,
 {
@@ -911,7 +937,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -930,7 +956,10 @@
     }
 }
 
-pub fn rsgx_rijndael128_align_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> SgxResult<sgx_align_mac_128bit_t>
+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,
 {
@@ -938,7 +967,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -960,7 +989,10 @@
 ///
 /// 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>
+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,
 {
@@ -968,7 +1000,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -987,7 +1019,10 @@
     }
 }
 
-pub fn rsgx_rijndael128_align_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) -> SgxResult<sgx_align_mac_128bit_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,
 {
@@ -995,7 +1030,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -1014,7 +1049,10 @@
     }
 }
 
-fn rsgx_cmac128_init(key: &sgx_cmac_128bit_key_t, cmac_handle: &mut sgx_cmac_state_handle_t) -> sgx_status_t {
+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,
@@ -1031,12 +1069,10 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_cmac128_update(src as *const _ as *const u8, size as u32, cmac_handle)
-    }
+    unsafe { sgx_cmac128_update(src as *const _ as *const u8, size as u32, cmac_handle) }
 }
 
 fn rsgx_cmac128_update_slice<T>(src: &[T], cmac_handle: sgx_cmac_state_handle_t) -> sgx_status_t
@@ -1047,15 +1083,22 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_cmac128_update(src.as_ptr() as *const _ as *const u8, size as u32, cmac_handle)
+        sgx_cmac128_update(
+            src.as_ptr() as *const _ as *const u8,
+            size as u32,
+            cmac_handle,
+        )
     }
 }
 
-fn rsgx_cmac128_final(cmac_handle: sgx_cmac_state_handle_t, hash: &mut sgx_cmac_128bit_tag_t) -> sgx_status_t {
+fn rsgx_cmac128_final(
+    cmac_handle: sgx_cmac_state_handle_t,
+    hash: &mut sgx_cmac_128bit_tag_t,
+) -> sgx_status_t {
     unsafe { sgx_cmac128_final(cmac_handle, hash as *mut sgx_cmac_128bit_tag_t) }
 }
 
@@ -1328,11 +1371,14 @@
     /// drop cleans up and deallocates the CMAC algorithm context state that was allocated in function init.
     ///
     fn drop(&mut self) {
-       let _ = self.close();
+        let _ = self.close();
     }
 }
 
-pub fn rsgx_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResult<sgx_hmac_256bit_tag_t>
+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,
 {
@@ -1340,7 +1386,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -1361,7 +1407,10 @@
     }
 }
 
-pub fn rsgx_align_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResult<sgx_align_mac_256bit_t>
+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,
 {
@@ -1369,7 +1418,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -1390,7 +1439,10 @@
     }
 }
 
-pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxResult<sgx_hmac_256bit_tag_t>
+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,
 {
@@ -1398,7 +1450,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -1419,7 +1471,10 @@
     }
 }
 
-pub fn rsgx_align_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxResult<sgx_align_mac_256bit_t>
+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,
 {
@@ -1427,7 +1482,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -1448,7 +1503,10 @@
     }
 }
 
-fn rsgx_hmac256_init(key: &sgx_hmac_256bit_key_t, hmac_handle: &mut sgx_hmac_state_handle_t) -> sgx_status_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,
@@ -1466,12 +1524,10 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_hmac256_update(src as *const _ as *const u8, size as i32, hmac_handle)
-    }
+    unsafe { sgx_hmac256_update(src as *const _ as *const u8, size as i32, hmac_handle) }
 }
 
 fn rsgx_hmac256_update_slice<T>(src: &[T], hmac_handle: sgx_hmac_state_handle_t) -> sgx_status_t
@@ -1482,15 +1538,22 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_hmac256_update(src.as_ptr() as *const _ as *const u8, size as i32, hmac_handle)
+        sgx_hmac256_update(
+            src.as_ptr() as *const _ as *const u8,
+            size as i32,
+            hmac_handle,
+        )
     }
 }
 
-fn rsgx_hmac256_final(hmac_handle: sgx_hmac_state_handle_t, hash: &mut sgx_hmac_256bit_tag_t) -> sgx_status_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,
@@ -1511,7 +1574,7 @@
 
 impl SgxHmacHandle {
     pub fn new() -> SgxHmacHandle {
-        SgxHmacHandle{
+        SgxHmacHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_hmac_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -1621,7 +1684,7 @@
 
 impl Drop for SgxHmacHandle {
     fn drop(&mut self) {
-       let _ = self.close();
+        let _ = self.close();
     }
 }
 
@@ -1694,14 +1757,14 @@
     dst: &mut [u8],
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if src_len < 1 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -1790,14 +1853,14 @@
     dst: &mut [u8],
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if src_len < 1 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -1842,8 +1905,18 @@
     }
 }
 
-fn rsgx_ecc256_check_point(point: &sgx_ec256_public_t, ecc_handle: sgx_ecc_state_handle_t, valid: &mut i32) -> sgx_status_t {
-    unsafe { sgx_ecc256_check_point(point as *const sgx_ec256_public_t, ecc_handle, valid as *mut i32) }
+fn rsgx_ecc256_check_point(
+    point: &sgx_ec256_public_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+    valid: &mut i32,
+) -> sgx_status_t {
+    unsafe {
+        sgx_ecc256_check_point(
+            point as *const sgx_ec256_public_t,
+            ecc_handle,
+            valid as *mut i32,
+        )
+    }
 }
 
 fn rsgx_ecc256_compute_shared_dhkey(
@@ -1854,8 +1927,8 @@
 ) -> 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,
+            private_b as *const sgx_ec256_private_t,
+            public_ga as *const sgx_ec256_public_t,
             shared_key as *mut sgx_ec256_dh_shared_t,
             ecc_handle,
         )
@@ -1893,16 +1966,18 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
     unsafe {
-        sgx_ecdsa_sign(data 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)
+        sgx_ecdsa_sign(
+            data as *const _ as *const u8,
+            size as u32,
+            private as *const sgx_ec256_private_t,
+            signature as *mut sgx_ec256_signature_t,
+            ecc_handle,
+        )
     }
 }
 
@@ -1919,15 +1994,15 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
     unsafe {
         sgx_ecdsa_sign(
-            data.as_ptr() as *const _  as *const u8,
+            data.as_ptr() as *const _ as *const u8,
             size as u32,
-            private as *const _ as *mut sgx_ec256_private_t,
+            private as *const sgx_ec256_private_t,
             signature as *mut sgx_ec256_signature_t,
             ecc_handle,
         )
@@ -1948,7 +2023,7 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -1958,15 +2033,18 @@
             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,
+            signature as *const sgx_ec256_signature_t,
             &mut verify as *mut u8,
-            ecc_handle);
+            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
     }
@@ -1986,7 +2064,7 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -1996,7 +2074,7 @@
             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,
+            signature as *const sgx_ec256_signature_t,
             &mut verify as *mut u8,
             ecc_handle,
         );
@@ -2005,7 +2083,9 @@
                 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
     }
@@ -2023,7 +2103,7 @@
         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,
+            signature as *const sgx_ec256_signature_t,
             &mut verify as *mut u8,
             ecc_handle,
         );
@@ -2032,13 +2112,14 @@
                 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
     }
 }
 
-
 ///
 /// ECC GF(p) context state.
 ///
@@ -2046,7 +2127,7 @@
 /// elliptic curve cryptosystem standard functions. The algorithm stores the intermediate results
 /// of calculations performed using this context.
 ///
-pub struct SgxEccHandle{
+pub struct SgxEccHandle {
     handle: RefCell<sgx_ecc_state_handle_t>,
     initflag: Cell<bool>,
 }
@@ -2203,7 +2284,9 @@
         }
     }
 
-    pub fn create_align_key_pair(&self) -> SgxResult<(sgx_align_ec256_private_t, sgx_ec256_public_t)> {
+    pub fn create_align_key_pair(
+        &self,
+    ) -> SgxResult<(sgx_align_ec256_private_t, sgx_ec256_public_t)> {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2374,26 +2457,44 @@
     ///
     /// The key creation process failed due to an internal cryptography library failure.
     ///
-    pub fn compute_shared_dhkey(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_ec256_dh_shared_t> {
+    pub fn compute_shared_dhkey(
+        &self,
+        private_b: &sgx_ec256_private_t,
+        public_ga: &sgx_ec256_public_t,
+    ) -> SgxResult<sgx_ec256_dh_shared_t> {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
 
         let mut shared_key = sgx_ec256_dh_shared_t::default();
-        let ret = rsgx_ecc256_compute_shared_dhkey(private_b, public_ga, &mut shared_key, *self.handle.borrow());
+        let ret = rsgx_ecc256_compute_shared_dhkey(
+            private_b,
+            public_ga,
+            &mut shared_key,
+            *self.handle.borrow(),
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => Ok(shared_key),
             _ => Err(ret),
         }
     }
 
-    pub fn compute_align_shared_dhkey(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_align_ec256_dh_shared_t> {
+    pub fn compute_align_shared_dhkey(
+        &self,
+        private_b: &sgx_ec256_private_t,
+        public_ga: &sgx_ec256_public_t,
+    ) -> SgxResult<sgx_align_ec256_dh_shared_t> {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
 
         let mut shared_key = sgx_align_ec256_dh_shared_t::default();
-        let ret = rsgx_ecc256_compute_shared_dhkey(private_b, public_ga, &mut shared_key.key, *self.handle.borrow());
+        let ret = rsgx_ecc256_compute_shared_dhkey(
+            private_b,
+            public_ga,
+            &mut shared_key.key,
+            *self.handle.borrow(),
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => Ok(shared_key),
             _ => Err(ret),
@@ -2475,7 +2576,11 @@
     ///
     /// 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>
+    pub fn ecdsa_sign_msg<T>(
+        &self,
+        data: &T,
+        private: &sgx_ec256_private_t,
+    ) -> SgxResult<sgx_ec256_signature_t>
     where
         T: Copy + ContiguousMemory,
     {
@@ -2494,7 +2599,11 @@
     ///
     /// 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>
+    pub fn ecdsa_sign_slice<T>(
+        &self,
+        data: &[T],
+        private: &sgx_ec256_private_t,
+    ) -> SgxResult<sgx_ec256_signature_t>
     where
         T: Copy + ContiguousMemory,
     {
@@ -2584,14 +2693,13 @@
         }
 
         let mut result = sgx_generic_ecresult_t::default();
-        let ret = rsgx_ecdsa_verify_msg(data, public, signature, &mut result, *self.handle.borrow());
+        let ret =
+            rsgx_ecdsa_verify_msg(data, public, signature, &mut result, *self.handle.borrow());
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                match result {
-                    sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
-                    _ => Ok(false),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match result {
+                sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2613,14 +2721,13 @@
         }
 
         let mut result = sgx_generic_ecresult_t::default();
-        let ret = rsgx_ecdsa_verify_slice(data, public, signature, &mut result, *self.handle.borrow());
+        let ret =
+            rsgx_ecdsa_verify_slice(data, public, signature, &mut result, *self.handle.borrow());
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                match result {
-                    sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
-                    _ => Ok(false),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match result {
+                sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2636,14 +2743,13 @@
         }
 
         let mut result = sgx_generic_ecresult_t::default();
-        let ret = rsgx_ecdsa_verify_hash(hash, public, signature, &mut result, *self.handle.borrow());
+        let ret =
+            rsgx_ecdsa_verify_hash(hash, public, signature, &mut result, *self.handle.borrow());
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                match result {
-                    sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
-                    _ => Ok(false),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match result {
+                sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2752,7 +2858,10 @@
 ///
 /// 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>
+pub fn rsgx_rsa3072_sign_msg<T>(
+    data: &T,
+    key: &sgx_rsa3072_key_t,
+) -> SgxResult<sgx_rsa3072_signature_t>
 where
     T: Copy + ContiguousMemory,
 {
@@ -2760,7 +2869,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2782,7 +2891,10 @@
 ///
 /// 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>
+pub fn rsgx_rsa3072_sign_slice<T>(
+    data: &[T],
+    key: &sgx_rsa3072_key_t,
+) -> SgxResult<sgx_rsa3072_signature_t>
 where
     T: Copy + ContiguousMemory,
 {
@@ -2790,7 +2902,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2873,7 +2985,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2887,12 +2999,10 @@
             &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),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match verify {
+                sgx_rsa_result_t::SGX_RSA_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2913,7 +3023,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2927,12 +3037,10 @@
             &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),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match verify {
+                sgx_rsa_result_t::SGX_RSA_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2954,28 +3062,28 @@
     if (n_byte_size <= 0) || (e_byte_size <= 0) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (n.is_empty()) || (n.len() > i32::max_value() as usize) {
+    if (n.is_empty()) || (n.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (d.is_empty()) || (d.len() > i32::max_value() as usize) {
+    if (d.is_empty()) || (d.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (p.is_empty()) || (p.len() > i32::max_value() as usize) {
+    if (p.is_empty()) || (p.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (q.is_empty()) || (q.len() > i32::max_value() as usize) {
+    if (q.is_empty()) || (q.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (dmp1.is_empty()) || (dmp1.len() > i32::max_value() as usize) {
+    if (dmp1.is_empty()) || (dmp1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (dmq1.is_empty()) || (dmq1.len() > i32::max_value() as usize) {
+    if (dmq1.is_empty()) || (dmq1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (iqmp.is_empty()) || (iqmp.len() > i32::max_value() as usize) {
+    if (iqmp.is_empty()) || (iqmp.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -3013,22 +3121,22 @@
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (p.is_empty()) || (p.len() > i32::max_value() as usize) {
+    if (p.is_empty()) || (p.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (q.is_empty()) || (q.len() > i32::max_value() as usize) {
+    if (q.is_empty()) || (q.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (dmp1.is_empty()) || (dmp1.len() > i32::max_value() as usize) {
+    if (dmp1.is_empty()) || (dmp1.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (dmq1.is_empty()) || (dmq1.len() > i32::max_value() as usize) {
+    if (dmq1.is_empty()) || (dmq1.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (iqmp.is_empty()) || (iqmp.len() > i32::max_value() as usize) {
+    if (iqmp.is_empty()) || (iqmp.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -3059,13 +3167,13 @@
     if (n_size <= 0) || (e_size <= 0) || (d_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (n.is_empty()) || (n.len() > i32::max_value() as usize) {
+    if (n.is_empty()) || (n.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (d.is_empty()) || (d.len() > i32::max_value() as usize) {
+    if (d.is_empty()) || (d.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -3092,10 +3200,10 @@
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (n.is_empty()) || (n.len() > i32::max_value() as usize) {
+    if (n.is_empty()) || (n.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -3119,9 +3227,7 @@
     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)
-    }
+    unsafe { sgx_free_rsa_key(rsa_key, key_type, mod_size, exp_size) }
 }
 
 fn rsgx_rsa_priv_decrypt_sha256(
@@ -3133,7 +3239,7 @@
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if * out_len != 0 && out_data.len() != * out_len {
+    if *out_len != 0 && out_data.len() != *out_len {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -3162,7 +3268,7 @@
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if * out_len != 0 && out_data.len() != * out_len {
+    if *out_len != 0 && out_data.len() != *out_len {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -3294,12 +3400,7 @@
             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(()),
             _ => Err(ret),
@@ -3365,24 +3466,13 @@
         }
     }
 
-    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);
@@ -3404,12 +3494,7 @@
             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(()),
             _ => Err(ret),
@@ -3498,13 +3583,13 @@
     sgx_nistp256_r_m1: &[u8],
     out_key: &mut [u8],
 ) -> SgxError {
-    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (out_key.is_empty()) || (out_key.len() > i32::max_value() as usize) {
+    if (out_key.is_empty()) || (out_key.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -3540,11 +3625,14 @@
     }
 }
 
-pub fn rsgx_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxResult<sgx_ec256_private_t> {
-    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+pub fn rsgx_ecc256_priv_key(
+    hash_drg: &[u8],
+    sgx_nistp256_r_m1: &[u8],
+) -> SgxResult<sgx_ec256_private_t> {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -3565,11 +3653,14 @@
     }
 }
 
-pub fn rsgx_align_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxResult<sgx_align_ec256_private_t> {
-    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+pub fn rsgx_align_ecc256_priv_key(
+    hash_drg: &[u8],
+    sgx_nistp256_r_m1: &[u8],
+) -> SgxResult<sgx_align_ec256_private_t> {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -3615,12 +3706,16 @@
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let aad_len = aad.len();
-    if aad_len > u32::max_value() as usize {
+    if aad_len > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
     unsafe {
-        let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
+        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(),
@@ -3638,14 +3733,14 @@
     aes_gcm_state: sgx_aes_state_handle_t,
 ) -> sgx_status_t {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if src_len == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if dst_len == 0 || dst_len < src_len {
@@ -3667,7 +3762,10 @@
     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)
+        sgx_aes_gcm128_enc_get_mac(
+            mac as *mut sgx_aes_gcm_128bit_tag_t as *mut u8,
+            aes_gcm_state,
+        )
     }
 }
 
@@ -3682,7 +3780,7 @@
 
 impl SgxAesHandle {
     pub fn new() -> SgxAesHandle {
-        SgxAesHandle{
+        SgxAesHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_aes_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -3766,7 +3864,6 @@
 
 impl Drop for SgxAesHandle {
     fn drop(&mut self) {
-       let _ = self.close();
+        let _ = self.close();
     }
 }
-
diff --git a/sgx_tcrypto/src/lib.rs b/sgx_tcrypto/src/lib.rs
index de8514f..241d115 100644
--- a/sgx_tcrypto/src/lib.rs
+++ b/sgx_tcrypto/src/lib.rs
@@ -22,9 +22,7 @@
 //!
 
 #![no_std]
-
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
-
 #![allow(non_camel_case_types)]
 #![allow(non_snake_case)]
 #![allow(clippy::too_many_arguments)]
diff --git a/sgx_tdh/src/dh.rs b/sgx_tdh/src/dh.rs
index b324cc6..bcc7e2a 100644
--- a/sgx_tdh/src/dh.rs
+++ b/sgx_tdh/src/dh.rs
@@ -19,18 +19,18 @@
 //!
 //! These functions allow an ISV to establish secure session between two enclaves using the EC DH Key exchange protocol.
 //!
-use sgx_types::*;
-use sgx_types::marker::ContiguousMemory;
-use sgx_trts::trts::*;
-use sgx_trts::memeq::ConsttimeMemEq;
-use sgx_tcrypto::*;
-use sgx_tse::*;
 use crate::ecp::*;
-use core::mem;
-use core::ptr;
+use alloc::boxed::Box;
 use alloc::slice;
 use alloc::vec::Vec;
-use alloc::boxed::Box;
+use core::mem;
+use core::ptr;
+use sgx_tcrypto::*;
+use sgx_trts::memeq::ConsttimeMemEq;
+use sgx_trts::trts::*;
+use sgx_tse::*;
+use sgx_types::marker::ContiguousMemory;
+use sgx_types::*;
 
 const AES_CMAC_KDF_ID: [u8; 2] = [1, 0];
 
@@ -67,7 +67,7 @@
     /// The size of sgx_dh_msg3_t needed.
     ///
     pub fn calc_raw_sealed_data_size(&self) -> u32 {
-        let max = u32::max_value();
+        let max = u32::MAX;
         let dh_msg3_size = mem::size_of::<sgx_dh_msg3_t>();
         let additional_prop_len = self.msg3_body.additional_prop.len();
 
@@ -101,7 +101,11 @@
     ///
     /// 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> {
+    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;
         }
@@ -111,7 +115,7 @@
 
         let additional_prop_len = self.msg3_body.additional_prop.len();
         let dh_msg3_size = mem::size_of::<sgx_dh_msg3_t>();
-        if additional_prop_len > u32::max_value() as usize - dh_msg3_size {
+        if additional_prop_len > u32::MAX as usize - dh_msg3_size {
             return None;
         }
         if len < (dh_msg3_size + additional_prop_len) as u32 {
@@ -164,7 +168,7 @@
         let raw_msg3 = &*p;
         let additional_prop_len = raw_msg3.msg3_body.additional_prop_length;
         let dh_msg3_size = mem::size_of::<sgx_dh_msg3_t>() as u32;
-        if additional_prop_len > u32::max_value() - dh_msg3_size {
+        if additional_prop_len > u32::MAX - dh_msg3_size {
             return None;
         }
         if len < dh_msg3_size + additional_prop_len {
@@ -178,7 +182,11 @@
         if additional_prop_len > 0 {
             let mut additional_prop: Vec<u8> = vec![0_u8; additional_prop_len as usize];
             let ptr_additional_prop = p.offset(1) as *const u8;
-            ptr::copy_nonoverlapping(ptr_additional_prop, additional_prop.as_mut_ptr(), additional_prop_len as usize);
+            ptr::copy_nonoverlapping(
+                ptr_additional_prop,
+                additional_prop.as_mut_ptr(),
+                additional_prop_len as usize,
+            );
             dh_msg3.msg3_body.additional_prop = additional_prop.into_boxed_slice();
         }
         Some(dh_msg3)
@@ -208,11 +216,11 @@
 impl Default for SgxDhResponder {
     fn default() -> SgxDhResponder {
         SgxDhResponder {
-           state: SgxDhSessionState::SGX_DH_SESSION_STATE_RESET,
-           prv_key: sgx_align_ec256_private_t::default(),
-           pub_key: sgx_ec256_public_t::default(),
-           smk_aek: sgx_align_key_128bit_t::default(),
-           shared_key: sgx_align_ec256_dh_shared_t::default(),
+            state: SgxDhSessionState::SGX_DH_SESSION_STATE_RESET,
+            prv_key: sgx_align_ec256_private_t::default(),
+            pub_key: sgx_ec256_public_t::default(),
+            smk_aek: sgx_align_key_128bit_t::default(),
+            shared_key: sgx_align_ec256_dh_shared_t::default(),
         }
     }
 }
@@ -370,17 +378,23 @@
         if !rsgx_data_is_within_enclave(self) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if !rsgx_data_is_within_enclave(msg2) ||
-           !rsgx_data_is_within_enclave(aek) ||
-           !rsgx_data_is_within_enclave(initiator_identity) ||
-           !rsgx_raw_is_within_enclave(msg3 as *const _ as *const u8, mem::size_of::<SgxDhMsg3>()) {
+        if !rsgx_data_is_within_enclave(msg2)
+            || !rsgx_data_is_within_enclave(aek)
+            || !rsgx_data_is_within_enclave(initiator_identity)
+            || !rsgx_raw_is_within_enclave(
+                msg3 as *const _ as *const u8,
+                mem::size_of::<SgxDhMsg3>(),
+            )
+        {
             *self = Self::default();
             self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if msg3.msg3_body.additional_prop.len() > 0 &&
-              (!(rsgx_slice_is_within_enclave(&msg3.msg3_body.additional_prop)) ||
-               (msg3.msg3_body.additional_prop.len() > (u32::max_value() as usize) - mem::size_of::<sgx_dh_msg3_t>())) {
+        if msg3.msg3_body.additional_prop.len() > 0
+            && (!(rsgx_slice_is_within_enclave(&msg3.msg3_body.additional_prop))
+                || (msg3.msg3_body.additional_prop.len()
+                    > (u32::MAX as usize) - mem::size_of::<sgx_dh_msg3_t>()))
+        {
             *self = Self::default();
             self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -394,14 +408,19 @@
 
         let ecc_state = SgxEccHandle::new();
         ecc_state.open().map_err(|ret| self.set_error(ret))?;
-        self.shared_key = ecc_state.compute_align_shared_dhkey(&self.prv_key.key, &msg2.g_b).map_err(|ret| self.set_error(ret))?;
+        self.shared_key = ecc_state
+            .compute_align_shared_dhkey(&self.prv_key.key, &msg2.g_b)
+            .map_err(|ret| self.set_error(ret))?;
 
-        self.smk_aek = derive_key(&self.shared_key.key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
+        self.smk_aek =
+            derive_key(&self.shared_key.key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
 
         #[cfg(feature = "use_lav2")]
-        self.lav2_verify_message2(msg2).map_err(|ret| self.set_error(ret))?;
+        self.lav2_verify_message2(msg2)
+            .map_err(|ret| self.set_error(ret))?;
         #[cfg(not(feature = "use_lav2"))]
-        self.dh_verify_message2(msg2).map_err(|ret| self.set_error(ret))?;
+        self.dh_verify_message2(msg2)
+            .map_err(|ret| self.set_error(ret))?;
 
         initiator_identity.isv_svn = msg2.report.body.isv_svn;
         initiator_identity.isv_prod_id = msg2.report.body.isv_prod_id;
@@ -410,11 +429,14 @@
         initiator_identity.mr_enclave = msg2.report.body.mr_enclave;
 
         #[cfg(feature = "use_lav2")]
-        self.lav2_generate_message3(msg2, msg3).map_err(|ret| self.set_error(ret))?;
+        self.lav2_generate_message3(msg2, msg3)
+            .map_err(|ret| self.set_error(ret))?;
         #[cfg(not(feature = "use_lav2"))]
-        self.dh_generate_message3(msg2, msg3).map_err(|ret| self.set_error(ret))?;
+        self.dh_generate_message3(msg2, msg3)
+            .map_err(|ret| self.set_error(ret))?;
 
-        let align_aek = derive_key(&self.shared_key.key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
+        let align_aek =
+            derive_key(&self.shared_key.key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
         *aek = align_aek.key;
         *self = Self::default();
         self.state = SgxDhSessionState::SGX_DH_SESSION_ACTIVE;
@@ -445,7 +467,8 @@
     }
 
     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 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];
 
         if !kdf_id.eq(&AES_CMAC_KDF_ID) {
@@ -490,8 +513,11 @@
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
 
-        let proto_spec = unsafe { SgxLAv2ProtoSpec::from_report_data(&msg2.report.body.report_data) };
-        if (!proto_spec.signature.eq(&SGX_LAV2_PROTO_SPEC.signature)) || (proto_spec.ver != SGX_LAV2_PROTO_SPEC.ver) {
+        let proto_spec =
+            unsafe { SgxLAv2ProtoSpec::from_report_data(&msg2.report.body.report_data) };
+        if (!proto_spec.signature.eq(&SGX_LAV2_PROTO_SPEC.signature))
+            || (proto_spec.ver != SGX_LAV2_PROTO_SPEC.ver)
+        {
             return Err(sgx_status_t::SGX_ERROR_UNEXPECTED);
         }
 
@@ -533,7 +559,8 @@
         msg3.cmac = Default::default();
         msg3.msg3_body.report = Default::default();
 
-        let proto_spec = unsafe { SgxLAv2ProtoSpec::from_report_data(&msg2.report.body.report_data) };
+        let proto_spec =
+            unsafe { SgxLAv2ProtoSpec::from_report_data(&msg2.report.body.report_data) };
         let mut target = sgx_target_info_t::default();
         let mut report_data = sgx_report_data_t::default();
         let report = msg2.report;
@@ -583,11 +610,11 @@
 impl Default for SgxDhInitiator {
     fn default() -> SgxDhInitiator {
         SgxDhInitiator {
-           state: SgxDhSessionState::SGX_DH_SESSION_INITIATOR_WAIT_M1,
-           smk_aek: sgx_align_key_128bit_t::default(),
-           pub_key: sgx_ec256_public_t::default(),
-           peer_pub_key: sgx_ec256_public_t::default(),
-           shared_key: sgx_align_ec256_dh_shared_t::default(),
+            state: SgxDhSessionState::SGX_DH_SESSION_INITIATOR_WAIT_M1,
+            smk_aek: sgx_align_key_128bit_t::default(),
+            pub_key: sgx_ec256_public_t::default(),
+            peer_pub_key: sgx_ec256_public_t::default(),
+            shared_key: sgx_align_ec256_dh_shared_t::default(),
         }
     }
 }
@@ -650,8 +677,7 @@
         if !rsgx_data_is_within_enclave(self) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if !rsgx_data_is_within_enclave(msg1) ||
-           !rsgx_data_is_within_enclave(msg2) {
+        if !rsgx_data_is_within_enclave(msg1) || !rsgx_data_is_within_enclave(msg2) {
             *self = Self::default();
             self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -665,17 +691,24 @@
 
         let ecc_state = SgxEccHandle::new();
         ecc_state.open().map_err(|ret| self.set_error(ret))?;
-        let (mut prv_key, pub_key) = ecc_state.create_align_key_pair().map_err(|ret| self.set_error(ret))?;
-        self.shared_key = ecc_state.compute_align_shared_dhkey(&prv_key.key, &msg1.g_a).map_err(|ret| self.set_error(ret))?;
+        let (mut prv_key, pub_key) = ecc_state
+            .create_align_key_pair()
+            .map_err(|ret| self.set_error(ret))?;
+        self.shared_key = ecc_state
+            .compute_align_shared_dhkey(&prv_key.key, &msg1.g_a)
+            .map_err(|ret| self.set_error(ret))?;
 
         prv_key = sgx_align_ec256_private_t::default();
         self.pub_key = pub_key;
-        self.smk_aek = derive_key(&self.shared_key.key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
+        self.smk_aek =
+            derive_key(&self.shared_key.key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
 
         #[cfg(feature = "use_lav2")]
-        self.lav2_generate_message2(msg1, msg2).map_err(|ret| self.set_error(ret))?;
+        self.lav2_generate_message2(msg1, msg2)
+            .map_err(|ret| self.set_error(ret))?;
         #[cfg(not(feature = "use_lav2"))]
-        self.dh_generate_message2(msg1, msg2).map_err(|ret| self.set_error(ret))?;
+        self.dh_generate_message2(msg1, msg2)
+            .map_err(|ret| self.set_error(ret))?;
 
         self.peer_pub_key = msg1.g_a;
         self.state = SgxDhSessionState::SGX_DH_SESSION_INITIATOR_WAIT_M3;
@@ -751,19 +784,22 @@
         if !rsgx_data_is_within_enclave(self) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if !rsgx_raw_is_within_enclave(msg3 as *const _ as *const u8, mem::size_of::<SgxDhMsg3>()) ||
-           !rsgx_data_is_within_enclave(aek) ||
-           !rsgx_data_is_within_enclave(responder_identity) {
+        if !rsgx_raw_is_within_enclave(msg3 as *const _ as *const u8, mem::size_of::<SgxDhMsg3>())
+            || !rsgx_data_is_within_enclave(aek)
+            || !rsgx_data_is_within_enclave(responder_identity)
+        {
             *self = Self::default();
             self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if msg3.msg3_body.additional_prop.len() > 0 &&
-               (!rsgx_slice_is_within_enclave(&msg3.msg3_body.additional_prop) ||
-               (msg3.msg3_body.additional_prop.len() > (u32::max_value() as usize) - mem::size_of::<sgx_dh_msg3_t>())) {
-                *self = Self::default();
-                self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
-                return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        if msg3.msg3_body.additional_prop.len() > 0
+            && (!rsgx_slice_is_within_enclave(&msg3.msg3_body.additional_prop)
+                || (msg3.msg3_body.additional_prop.len()
+                    > (u32::MAX as usize) - mem::size_of::<sgx_dh_msg3_t>()))
+        {
+            *self = Self::default();
+            self.state = SgxDhSessionState::SGX_DH_SESSION_STATE_ERROR;
+            return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
         if self.state != SgxDhSessionState::SGX_DH_SESSION_INITIATOR_WAIT_M3 {
@@ -777,7 +813,8 @@
         #[cfg(not(feature = "use_lav2"))]
         self.dh_verify_message3(msg3).map_err(|ret| self.set_error(ret))?;
 
-        let align_aek = derive_key(&self.shared_key.key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
+        let align_aek =
+            derive_key(&self.shared_key.key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
         *aek = align_aek.key;
 
         *self = Self::default();
@@ -807,7 +844,8 @@
 
         let mut report_data = sgx_report_data_t::default();
         report_data.d[..SGX_SHA256_HASH_SIZE].copy_from_slice(&msg_hash);
-        report_data.d[SGX_SHA256_HASH_SIZE..SGX_SHA256_HASH_SIZE + 2].copy_from_slice(&AES_CMAC_KDF_ID);
+        report_data.d[SGX_SHA256_HASH_SIZE..SGX_SHA256_HASH_SIZE + 2]
+            .copy_from_slice(&AES_CMAC_KDF_ID);
 
         let target = msg1.target;
         msg2.report = rsgx_create_report(&target, &report_data)?;
@@ -834,7 +872,9 @@
 
         msg2.report = rsgx_create_report(&target, &report_data)?;
         // Replace report_data with proto_spec
-        unsafe {msg2.report.body.report_data = SGX_LAV2_PROTO_SPEC.to_report_data();}
+        unsafe {
+            msg2.report.body.report_data = SGX_LAV2_PROTO_SPEC.to_report_data();
+        }
         msg2.cmac = rsgx_rijndael128_cmac_msg(&self.smk_aek.key, &msg2.g_b)?;
 
         Ok(())
@@ -955,7 +995,7 @@
             let size: i32 = 1 << (self.target_spec[i] & 0xF);
             to += size - 1;
             to &= -size;
-            if (to + size) as usize > mem::size_of::<sgx_target_info_t>()  {
+            if (to + size) as usize > mem::size_of::<sgx_target_info_t>() {
                 return Err(sgx_status_t::SGX_ERROR_UNEXPECTED);
             }
 
@@ -965,7 +1005,11 @@
                     return Err(sgx_status_t::SGX_ERROR_UNEXPECTED);
                 }
                 unsafe {
-                    ptr::copy_nonoverlapping(f.offset(from as isize), d.offset(to as isize), size as usize);
+                    ptr::copy_nonoverlapping(
+                        f.offset(from as isize),
+                        d.offset(to as isize),
+                        size as usize,
+                    );
                 }
             } else {
                 if from == -1 {
@@ -984,18 +1028,22 @@
     signature: [0x53, 0x47, 0x58, 0x20, 0x4C, 0x41], // "SGX LA"
     ver: 2,
     rev: 0,
-    target_spec: [0x0600, // target_spec count & revision
-                  0x0405, // MRENCLAVE
-                  0x0304, // ATTRIBUTES
-                  0x0140, // CET_ATTRIBUTES
-                  0x1041, // CONFIGSVN
-                  0x0102, // MISCSELECT
-                  0x0C06, // CONFIGID
-                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+    target_spec: [
+        0x0600, // target_spec count & revision
+        0x0405, // MRENCLAVE
+        0x0304, // ATTRIBUTES
+        0x0140, // CET_ATTRIBUTES
+        0x1041, // CONFIGSVN
+        0x0102, // MISCSELECT
+        0x0C06, // CONFIGID
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    ],
 };
 
 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)
+    SGX_LAV2_PROTO_SPEC
+        .make_target_info(&report, &mut target_info)
+        .map(|_| target_info)
 }
diff --git a/sgx_tdh/src/ecp.rs b/sgx_tdh/src/ecp.rs
index 15ef460..0363220 100644
--- a/sgx_tdh/src/ecp.rs
+++ b/sgx_tdh/src/ecp.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::*;
 use sgx_tcrypto::*;
+use sgx_types::*;
 
 pub const EC_LABEL_LENGTH: usize = 3;
 pub const EC_SMK_LABEL: [u8; EC_LABEL_LENGTH] = [0x53, 0x4D, 0x4B];
@@ -58,4 +58,3 @@
         _ => sgx_status_t::SGX_ERROR_UNEXPECTED,
     }
 }
-
diff --git a/sgx_tdh/src/lib.rs b/sgx_tdh/src/lib.rs
index 007656a..94b96e4 100644
--- a/sgx_tdh/src/lib.rs
+++ b/sgx_tdh/src/lib.rs
@@ -21,9 +21,7 @@
 //!
 
 #![no_std]
-
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
-
 #![allow(non_camel_case_types)]
 #![allow(unused_assignments)]
 #![allow(dead_code)]
@@ -31,10 +29,10 @@
 #[macro_use]
 extern crate alloc;
 
-extern crate sgx_types;
-extern crate sgx_trts;
 extern crate sgx_tcrypto;
+extern crate sgx_trts;
 extern crate sgx_tse;
+extern crate sgx_types;
 
 mod dh;
 pub use self::dh::*;
diff --git a/sgx_tkey_exchange/src/lib.rs b/sgx_tkey_exchange/src/lib.rs
index e05ad9e..e62482d 100644
--- a/sgx_tkey_exchange/src/lib.rs
+++ b/sgx_tkey_exchange/src/lib.rs
@@ -77,9 +77,11 @@
 pub fn rsgx_ra_init(p_pub_key: &sgx_ec256_public_t, b_pse: i32) -> SgxResult<sgx_ra_context_t> {
     let mut context: sgx_ra_context_t = 0;
     let ret = unsafe {
-        sgx_ra_init(p_pub_key as *const sgx_ec256_public_t,
-                    b_pse,
-                    &mut context as *mut sgx_ra_context_t)
+        sgx_ra_init(
+            p_pub_key as *const sgx_ec256_public_t,
+            b_pse,
+            &mut context as *mut sgx_ra_context_t,
+        )
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(context),
@@ -203,11 +205,12 @@
 /// Indicates this API is invoked in incorrect order, it can be called only after a success session has been established.
 /// In other words, sgx_ra_proc_msg2 should have been called and no error returned.
 ///
-pub fn rsgx_ra_get_keys(context: sgx_ra_context_t, keytype: sgx_ra_key_type_t) -> SgxResult<sgx_ra_key_128_t> {
+pub fn rsgx_ra_get_keys(
+    context: sgx_ra_context_t,
+    keytype: sgx_ra_key_type_t,
+) -> SgxResult<sgx_ra_key_128_t> {
     let mut key = sgx_ra_key_128_t::default();
-    let ret = unsafe {
-        sgx_ra_get_keys(context, keytype, &mut key as *mut sgx_ra_key_128_t)
-    };
+    let ret = unsafe { sgx_ra_get_keys(context, keytype, &mut key as *mut sgx_ra_key_128_t) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(key),
         _ => Err(ret),
@@ -250,4 +253,3 @@
         _ => Err(ret),
     }
 }
-
diff --git a/sgx_tprotected_fs/src/fs.rs b/sgx_tprotected_fs/src/fs.rs
index 93767e4..241a7d7 100644
--- a/sgx_tprotected_fs/src/fs.rs
+++ b/sgx_tprotected_fs/src/fs.rs
@@ -16,18 +16,22 @@
 // under the License..
 
 //! # Intel Protected File System API
-use sgx_types::*;
-use sgx_trts::libc::{self, c_void};
-use sgx_trts::error::errno;
-use sgx_trts::c_str::CStr;
 use core::cmp;
+use sgx_trts::c_str::CStr;
+use sgx_trts::error::errno;
+use sgx_trts::libc::{self, c_void};
+use sgx_types::*;
 
 fn max_len() -> usize {
-    u32::max_value() as usize
+    u32::MAX as usize
 }
 
 unsafe fn rsgx_fopen(filename: &CStr, mode: &CStr, key: &sgx_key_128bit_t) -> SysResult<SGX_FILE> {
-    let file = sgx_fopen(filename.as_ptr(), mode.as_ptr(), key as *const sgx_key_128bit_t);
+    let file = sgx_fopen(
+        filename.as_ptr(),
+        mode.as_ptr(),
+        key as *const sgx_key_128bit_t,
+    );
     if file.is_null() {
         Err(errno())
     } else {
@@ -193,7 +197,7 @@
 }
 
 pub struct SgxFileStream {
-    stream: SGX_FILE
+    stream: SGX_FILE,
 }
 
 impl SgxFileStream {
@@ -234,9 +238,7 @@
     /// in the Protected FS API, otherwise, error code is returned.
     ///
     pub fn open(filename: &CStr, mode: &CStr, key: &sgx_key_128bit_t) -> SysResult<SgxFileStream> {
-        unsafe {
-            rsgx_fopen(filename, mode, key).map(|f| SgxFileStream{ stream: f})
-        }
+        unsafe { rsgx_fopen(filename, mode, key).map(|f| SgxFileStream { stream: f }) }
     }
 
     ///
@@ -270,9 +272,7 @@
     /// in the Protected FS API, otherwise, error code is returned.
     ///
     pub fn open_auto_key(filename: &CStr, mode: &CStr) -> SysResult<SgxFileStream> {
-        unsafe {
-            rsgx_fopen_auto_key(filename, mode).map(|f| SgxFileStream{ stream: f})
-        }
+        unsafe { rsgx_fopen_auto_key(filename, mode).map(|f| SgxFileStream { stream: f }) }
     }
 
     ///
@@ -434,7 +434,7 @@
     /// The latest operation error code is returned. 0 indicates that no errors occurred.
     ///
     pub fn error(&self) -> i32 {
-        unsafe{ rsgx_ferror(self.stream) }
+        unsafe { rsgx_ferror(self.stream) }
     }
 
     ///
@@ -571,16 +571,12 @@
 ///
 pub fn export_auto_key(filename: &CStr) -> SysResult<sgx_key_128bit_t> {
     let mut key: sgx_key_128bit_t = Default::default();
-    unsafe {
-        rsgx_fexport_auto_key(filename, &mut key).map(|_| key)
-    }
+    unsafe { rsgx_fexport_auto_key(filename, &mut key).map(|_| key) }
 }
 
 pub fn export_align_auto_key(filename: &CStr) -> SysResult<sgx_align_key_128bit_t> {
     let mut align_key: sgx_align_key_128bit_t = Default::default();
-    unsafe {
-        rsgx_fexport_auto_key(filename, &mut align_key.key).map(|_| align_key)
-    }
+    unsafe { rsgx_fexport_auto_key(filename, &mut align_key.key).map(|_| align_key) }
 }
 
 ///
diff --git a/sgx_tprotected_fs/src/lib.rs b/sgx_tprotected_fs/src/lib.rs
index 91537c4..6c12cd7 100644
--- a/sgx_tprotected_fs/src/lib.rs
+++ b/sgx_tprotected_fs/src/lib.rs
@@ -24,8 +24,8 @@
 #![no_std]
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
 
-extern crate sgx_types;
 extern crate sgx_trts;
+extern crate sgx_types;
 
 mod fs;
 pub use self::fs::*;
diff --git a/sgx_trts/src/cpu_feature.rs b/sgx_trts/src/cpu_feature.rs
index f47c884..e650ba1 100644
--- a/sgx_trts/src/cpu_feature.rs
+++ b/sgx_trts/src/cpu_feature.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::impl_enum;
 use crate::enclave;
+use sgx_types::impl_enum;
 
 pub fn check_for(fid: Feature) -> bool {
     let bit = fid.get_feature_bit();
@@ -25,7 +25,9 @@
 
 #[macro_export]
 macro_rules! is_cpu_feature_supported {
-    ($feature:expr) => ( (($feature & $crate::enclave::rsgx_get_cpu_feature()) != 0) )
+    ($feature:expr) => {
+        (($feature & $crate::enclave::rsgx_get_cpu_feature()) != 0)
+    };
 }
 
 #[macro_export]
@@ -309,7 +311,6 @@
     }
 }
 
-
 impl Feature {
     pub fn get_feature_bit(&self) -> u64 {
         let id = *self as u32;
@@ -319,4 +320,4 @@
             0
         }
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_trts/src/enclave.rs b/sgx_trts/src/enclave.rs
index acc7f1f..582d255 100644
--- a/sgx_trts/src/enclave.rs
+++ b/sgx_trts/src/enclave.rs
@@ -31,6 +31,8 @@
     static g_cpu_feature_indicator: uint64_t;
     static g_cpu_core_num: uint32_t;
     static EDMM_supported: c_int;
+    static g_peak_heap_used: size_t;
+    static g_peak_rsrv_mem_committed: size_t;
     pub fn get_thread_data() -> *const c_void;
     pub fn get_enclave_base() -> *const c_void;
     pub fn get_heap_base() -> *const c_void;
@@ -545,7 +547,8 @@
         traversal_layout(
             &mut static_tcs_num,
             &mut dyn_tcs_num,
-            &mut eremove_tcs_num,layout_table,
+            &mut eremove_tcs_num,
+            layout_table,
         );
     }
 
@@ -558,7 +561,8 @@
         for (i, layout) in layout_table.iter().enumerate() {
             if !is_group_id!(layout.group.id as u32) {
                 if (layout.entry.attributes & PAGE_ATTR_EADD) != 0 {
-                    if (layout.entry.content_offset != 0) && (layout.entry.si_flags == SI_FLAGS_TCS) {
+                    if (layout.entry.content_offset != 0) && (layout.entry.si_flags == SI_FLAGS_TCS)
+                    {
                         if (layout.entry.attributes & PAGE_ATTR_EREMOVE) == 0 {
                             *static_num += 1;
                         } else {
@@ -573,7 +577,12 @@
                 }
             } else {
                 for _ in 0..layout.group.load_times {
-                    traversal_layout(static_num, dyn_num, eremove_num, &layout_table[i-layout.group.entry_count as usize..i])
+                    traversal_layout(
+                        static_num,
+                        dyn_num,
+                        eremove_num,
+                        &layout_table[i - layout.group.entry_count as usize..i],
+                    )
                 }
             }
         }
@@ -599,3 +608,13 @@
 pub fn rsgx_get_cpu_core_num() -> u32 {
     unsafe { g_cpu_core_num }
 }
+
+#[inline]
+pub fn rsgx_get_peak_heap_used() -> usize {
+    unsafe { g_peak_heap_used }
+}
+
+#[inline]
+pub fn rsgx_get_peak_rsrv_mem_committed() -> usize {
+    unsafe { g_peak_rsrv_mem_committed }
+}
\ No newline at end of file
diff --git a/sgx_trts/src/lib.rs b/sgx_trts/src/lib.rs
index d1611bb..2a47e7d 100644
--- a/sgx_trts/src/lib.rs
+++ b/sgx_trts/src/lib.rs
@@ -63,7 +63,6 @@
 //!
 
 #![no_std]
-
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
 
 #![feature(allocator_api)]
@@ -87,16 +86,16 @@
 #[macro_use]
 mod macros;
 
-pub mod veh;
-pub mod trts;
-pub mod enclave;
-pub mod memeq;
-pub mod oom;
-pub mod memchr;
 pub mod ascii;
 pub mod c_str;
 pub mod cpu_feature;
 pub mod cpuid;
+pub mod enclave;
+pub mod memchr;
+pub mod memeq;
+pub mod oom;
+pub mod trts;
+pub mod veh;
 
 #[cfg(not(target_env = "sgx"))]
 pub use sgx_libc as libc;
@@ -107,5 +106,5 @@
 }
 
 pub mod error {
-    pub use sgx_libc::{errno, set_errno, error_string};
+    pub use sgx_libc::{errno, error_string, set_errno};
 }
diff --git a/sgx_trts/src/macros.rs b/sgx_trts/src/macros.rs
index 07d706b..52a896c 100644
--- a/sgx_trts/src/macros.rs
+++ b/sgx_trts/src/macros.rs
@@ -26,7 +26,6 @@
 #[macro_export]
 macro_rules! global_ctors_object {
     ($var_name:ident, $func_name:ident = $func:block) => {
-
         cfg_if! {
             if #[cfg(target_os = "linux")] {
                 #[link_section = ".init_array"]
@@ -44,15 +43,16 @@
         }
         #[no_mangle]
         pub fn $func_name() {
-            {$func};
+            {
+                $func
+            };
         }
-    }
+    };
 }
 
 #[macro_export]
 macro_rules! global_dtors_object {
     ($var_name:ident, $func_name:ident = $func:block) => {
-
         cfg_if! {
             if #[cfg(target_os = "linux")] {
                 #[link_section = ".fini_array"]
@@ -70,7 +70,9 @@
         }
         #[no_mangle]
         pub fn $func_name() {
-            {$func};
+            {
+                $func
+            };
         }
-    }
+    };
 }
diff --git a/sgx_trts/src/memchr.rs b/sgx_trts/src/memchr.rs
index edda4d3..ea27c07 100644
--- a/sgx_trts/src/memchr.rs
+++ b/sgx_trts/src/memchr.rs
@@ -15,7 +15,6 @@
 // specific language governing permissions and limitations
 // under the License..
 
-
 /// A safe interface to `memchr`.
 ///
 /// Returns the index corresponding to the first occurrence of `needle` in
@@ -37,12 +36,7 @@
 // }
 
 pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
-    let p = unsafe {
-        sgx_libc::memchr(
-            haystack.as_ptr(),
-            needle,
-            haystack.len())
-    };
+    let p = unsafe { sgx_libc::memchr(haystack.as_ptr(), needle, haystack.len()) };
     if p.is_null() {
         None
     } else {
@@ -56,15 +50,13 @@
         if haystack.is_empty() {
             return None;
         }
-        let p = unsafe {
-            sgx_libc::memrchr(
-                haystack.as_ptr(),
-                needle,
-                haystack.len(),
-            )
-        };
-        if p.is_null() { None } else { Some(p as usize - (haystack.as_ptr() as usize)) }
+        let p = unsafe { sgx_libc::memrchr(haystack.as_ptr(), needle, haystack.len()) };
+        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 b3f1ff9..2fc268f 100644
--- a/sgx_trts/src/memeq.rs
+++ b/sgx_trts/src/memeq.rs
@@ -21,13 +21,15 @@
 //! are useful in cyptographic functions, defending against timing based side
 //! channel attacks
 
-use sgx_types::marker::{BytewiseEquality};
-use core::mem;
 use alloc::slice;
+use core::mem;
+use sgx_types::marker::BytewiseEquality;
 
 pub trait ConsttimeMemEq<T: BytewiseEquality + ?Sized = Self> {
     fn consttime_memeq(&self, other: &T) -> bool;
-    fn consttime_memne(&self, other: &T) -> bool { !self.consttime_memeq(other) }
+    fn consttime_memne(&self, other: &T) -> bool {
+        !self.consttime_memeq(other)
+    }
 }
 
 impl<T> ConsttimeMemEq<[T]> for [T]
@@ -71,11 +73,7 @@
     }
 }
 
-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: i32 = 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 010b262..d14fd19 100644
--- a/sgx_trts/src/oom.rs
+++ b/sgx_trts/src/oom.rs
@@ -16,10 +16,10 @@
 // under the License..
 
 use crate::trts;
-use core::sync::atomic::{AtomicPtr, Ordering};
+use core::alloc::AllocErr;
 use core::mem;
 use core::ptr;
-use core::alloc::AllocErr;
+use core::sync::atomic::{AtomicPtr, Ordering};
 
 static SGX_OOM_HANDLER: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
 
@@ -30,8 +30,11 @@
 
 pub fn rsgx_oom(err: AllocErr) -> ! {
     let hook = SGX_OOM_HANDLER.load(Ordering::SeqCst);
-    let handler: fn(AllocErr) -> ! =
-        if hook.is_null() { default_oom_handler } else { unsafe { mem::transmute(hook) } };
+    let handler: fn(AllocErr) -> ! = if hook.is_null() {
+        default_oom_handler
+    } else {
+        unsafe { mem::transmute(hook) }
+    };
     handler(err)
 }
 
@@ -47,5 +50,9 @@
 ///
 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) } }
+    if hook.is_null() {
+        default_oom_handler
+    } else {
+        unsafe { mem::transmute(hook) }
+    }
 }
diff --git a/sgx_trts/src/trts.rs b/sgx_trts/src/trts.rs
index 5095996..18f6b23 100644
--- a/sgx_trts/src/trts.rs
+++ b/sgx_trts/src/trts.rs
@@ -15,10 +15,10 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::*;
-use sgx_types::marker::ContiguousMemory;
-use core::mem;
 use crate::libc;
+use core::mem;
+use sgx_types::marker::ContiguousMemory;
+use sgx_types::*;
 
 ///
 /// rsgx_read_rand function is used to generate a random number inside the enclave.
@@ -122,7 +122,7 @@
 ///
 #[inline]
 pub fn rsgx_data_is_outside_enclave<T: Copy + ContiguousMemory>(data: &T) -> bool {
-    rsgx_raw_is_outside_enclave(data as *const _ as *const u8,  mem::size_of::<T>())
+    rsgx_raw_is_outside_enclave(data as *const _ as *const u8, mem::size_of::<T>())
 }
 
 ///
@@ -191,15 +191,21 @@
 
 #[inline(always)]
 pub fn rsgx_lfence() {
-    unsafe { asm!{"lfence"}; }
+    unsafe {
+        asm! {"lfence"};
+    }
 }
 
 #[inline(always)]
 pub fn rsgx_sfence() {
-    unsafe { asm!{"sfence"}; }
+    unsafe {
+        asm! {"sfence"};
+    }
 }
 
 #[inline(always)]
 pub fn rsgx_mfence() {
-    unsafe { asm!{"mfence"}; }
+    unsafe {
+        asm! {"mfence"};
+    }
 }
diff --git a/sgx_trts/src/veh.rs b/sgx_trts/src/veh.rs
index 83b1a2f..88ae687 100644
--- a/sgx_trts/src/veh.rs
+++ b/sgx_trts/src/veh.rs
@@ -65,10 +65,11 @@
 ///
 /// The exception handler was not registered.
 ///
-pub fn rsgx_register_exception_handler(is_first_handler: u32, exception_handler: sgx_exception_handler_t) -> Option<exception_handle> {
-    let handle = unsafe {
-        sgx_register_exception_handler(is_first_handler, exception_handler)
-    };
+pub fn rsgx_register_exception_handler(
+    is_first_handler: u32,
+    exception_handler: sgx_exception_handler_t,
+) -> Option<exception_handle> {
+    let handle = unsafe { sgx_register_exception_handler(is_first_handler, exception_handler) };
     if handle.is_null() {
         None
     } else {
diff --git a/sgx_tse/src/se.rs b/sgx_tse/src/se.rs
index 8a3b7a3..cf46fda 100644
--- a/sgx_tse/src/se.rs
+++ b/sgx_tse/src/se.rs
@@ -74,7 +74,10 @@
 ///
 /// Indicates that the enclave is out of memory.
 ///
-pub fn rsgx_create_report(target_info: &sgx_target_info_t, report_data: &sgx_report_data_t) -> SgxResult<sgx_report_t> {
+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(
@@ -194,7 +197,10 @@
 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)
+        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),
@@ -205,7 +211,10 @@
 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)
+        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),
@@ -214,5 +223,5 @@
 }
 
 pub fn rsgx_self_report() -> sgx_report_t {
-    unsafe { * sgx_self_report() }
+    unsafe { *sgx_self_report() }
 }
diff --git a/sgx_tseal/src/aad.rs b/sgx_tseal/src/aad.rs
index 294c07d..86eb071 100644
--- a/sgx_tseal/src/aad.rs
+++ b/sgx_tseal/src/aad.rs
@@ -18,13 +18,13 @@
 //!
 //! Provides APIs to authenticate and verify the input data with AES-GMAC.
 //!
-use sgx_types::*;
-use sgx_types::marker::ContiguousMemory;
 use crate::internal::*;
-use core::mem;
-use core::marker::PhantomData;
-use alloc::slice;
 use alloc::boxed::Box;
+use alloc::slice;
+use core::marker::PhantomData;
+use core::mem;
+use sgx_types::marker::ContiguousMemory;
+use sgx_types::*;
 
 /// The structure about sealed data, for authenticate and verify.
 pub struct SgxMacAadata<'a, T: 'a + ?Sized> {
@@ -44,8 +44,8 @@
 impl<'a, T: 'a + Clone + ?Sized> Clone for SgxMacAadata<'a, T> {
     fn clone(&self) -> SgxMacAadata<'a, T> {
         SgxMacAadata {
-           inner: self.inner.clone(),
-           marker: PhantomData,
+            inner: self.inner.clone(),
+            marker: PhantomData,
         }
     }
 }
@@ -103,11 +103,17 @@
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         let aad_slice: &[u8] = unsafe {
-            slice::from_raw_parts(additional_text as *const _ as *const u8, mem::size_of_val(additional_text))
+            slice::from_raw_parts(
+                additional_text as *const _ as *const u8,
+                mem::size_of_val(additional_text),
+            )
         };
 
         let result = SgxInternalSealedData::mac_aadata(aad_slice);
-        result.map(|x| SgxMacAadata {inner: x, marker: PhantomData})
+        result.map(|x| SgxMacAadata {
+            inner: x,
+            marker: PhantomData,
+        })
     }
 
     ///
@@ -187,17 +193,18 @@
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         let aad_slice: &[u8] = unsafe {
-            slice::from_raw_parts(additional_text as *const _ as *const u8, mem::size_of_val(additional_text))
+            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,
-            );
-        result.map(|x| SgxMacAadata {inner: x, marker: PhantomData})
+            SgxInternalSealedData::mac_aadata_ex(key_policy, attribute_mask, misc_mask, aad_slice);
+        result.map(|x| SgxMacAadata {
+            inner: x,
+            marker: PhantomData,
+        })
     }
 
     ///
@@ -269,7 +276,10 @@
             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,
+        })
     }
 
     ///
@@ -295,13 +305,16 @@
     ///
     /// May be the parameter p and len is not avaliable.
     ///
-    pub unsafe fn to_raw_sealed_data_t(&self, p: *mut sgx_sealed_data_t, len: u32) -> Option<*mut sgx_sealed_data_t> {
+    pub unsafe fn to_raw_sealed_data_t(
+        &self,
+        p: *mut sgx_sealed_data_t,
+        len: u32,
+    ) -> Option<*mut sgx_sealed_data_t> {
         self.inner.to_raw_sealed_data_t(p, len)
     }
 }
 
 impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
-
     ///
     /// This function is used to authenticate the input data with AES-GMAC.
     ///
@@ -311,12 +324,14 @@
         if size == 0 || len == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        let aad_slice: &[u8] = unsafe {
-            slice::from_raw_parts(additional_text.as_ptr() as *const u8, len)
-        };
+        let aad_slice: &[u8] =
+            unsafe { slice::from_raw_parts(additional_text.as_ptr() as *const u8, len) };
 
         let result = SgxInternalSealedData::mac_aadata(aad_slice);
-        result.map(|x| SgxMacAadata { inner: x, marker: PhantomData })
+        result.map(|x| SgxMacAadata {
+            inner: x,
+            marker: PhantomData,
+        })
     }
 
     ///
@@ -334,17 +349,14 @@
         if size == 0 || len == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        let aad_slice: &[u8] = unsafe {
-            slice::from_raw_parts(additional_text.as_ptr() as *const u8, len)
-        };
+        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,
-            );
-        result.map(|x| SgxMacAadata {inner: x, marker: PhantomData})
+            SgxInternalSealedData::mac_aadata_ex(key_policy, attribute_mask, misc_mask, aad_slice);
+        result.map(|x| SgxMacAadata {
+            inner: x,
+            marker: PhantomData,
+        })
     }
 
     ///
@@ -362,10 +374,10 @@
         if (aad_len % size) != 0 {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
-         self.inner.unmac_aadata().map(|x| {
+        self.inner.unmac_aadata().map(|x| {
             let ptr = Box::into_raw(x.additional);
             unsafe {
-                let slice = slice::from_raw_parts_mut(ptr as *mut T, aad_len/size);
+                let slice = slice::from_raw_parts_mut(ptr as *mut T, aad_len / size);
                 Box::from_raw(slice as *mut [T])
             }
         })
@@ -380,7 +392,10 @@
             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,
+        })
     }
 
     ///
@@ -406,7 +421,11 @@
     ///
     /// May be the parameter p and len is not avaliable.
     ///
-    pub unsafe fn to_raw_sealed_data_t(&self, p: *mut sgx_sealed_data_t, len: u32) -> Option<*mut sgx_sealed_data_t> {
+    pub unsafe fn to_raw_sealed_data_t(
+        &self,
+        p: *mut sgx_sealed_data_t,
+        len: u32,
+    ) -> Option<*mut sgx_sealed_data_t> {
         self.inner.to_raw_sealed_data_t(p, len)
     }
 }
@@ -450,7 +469,7 @@
     ///
     /// Calculate the size of the sealed data in SgxMacAadata.
     ///
-    pub fn calc_raw_sealed_data_size(add_mac_txt_size: u32, encrypt_txt_size: u32) -> u32  {
+    pub fn calc_raw_sealed_data_size(add_mac_txt_size: u32, encrypt_txt_size: u32) -> u32 {
         SgxInternalSealedData::calc_raw_sealed_data_size(add_mac_txt_size, encrypt_txt_size)
     }
 
diff --git a/sgx_tseal/src/internal.rs b/sgx_tseal/src/internal.rs
index da9af99..bf63b14 100644
--- a/sgx_tseal/src/internal.rs
+++ b/sgx_tseal/src/internal.rs
@@ -15,17 +15,18 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::*;
-use sgx_trts::trts::*;
-use sgx_tcrypto::*;
-use sgx_tse::*;
-use core::mem;
-use core::ptr;
 use alloc::boxed::Box;
 use alloc::vec::Vec;
+use core::mem;
+use core::ptr;
+use sgx_tcrypto::*;
+use sgx_trts::trts::*;
+use sgx_tse::*;
+use sgx_types::*;
 
 /* intel sgx sdk 2.4 */
-const KEY_POLICY_KSS: uint16_t = SGX_KEYPOLICY_CONFIGID | SGX_KEYPOLICY_ISVFAMILYID | SGX_KEYPOLICY_ISVEXTPRODID;
+const KEY_POLICY_KSS: uint16_t =
+    SGX_KEYPOLICY_CONFIGID | SGX_KEYPOLICY_ISVFAMILYID | SGX_KEYPOLICY_ISVEXTPRODID;
 
 #[derive(Clone, Default)]
 pub struct SgxInternalUnsealedData {
@@ -94,7 +95,7 @@
     }
 
     pub fn calc_raw_sealed_data_size(add_mac_txt_size: u32, encrypt_txt_size: u32) -> u32 {
-        let max = u32::max_value();
+        let max = u32::MAX;
         let sealed_data_size = mem::size_of::<sgx_sealed_data_t>() as u32;
 
         if add_mac_txt_size > max - encrypt_txt_size {
@@ -109,9 +110,10 @@
 
     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 {
-            u32::max_value()
+        if data_size > self.payload_data.payload_size as usize
+            || data_size >= u32::MAX as usize
+        {
+            u32::MAX
         } else {
             data_size as u32
         }
@@ -119,26 +121,32 @@
 
     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 {
-            u32::max_value()
+        if data_size > self.payload_data.payload_size as usize
+            || data_size >= u32::MAX as usize
+        {
+            u32::MAX
         } else {
             data_size as u32
         }
     }
 
-    pub unsafe fn to_raw_sealed_data_t(&self, p: *mut sgx_sealed_data_t, len: u32) -> Option<*mut sgx_sealed_data_t> {
+    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;
         }
-        if !rsgx_raw_is_within_enclave(p as *mut u8, len as usize) &&
-           !rsgx_raw_is_outside_enclave(p as *mut u8, len as usize) {
+        if !rsgx_raw_is_within_enclave(p as *mut u8, len as usize)
+            && !rsgx_raw_is_outside_enclave(p as *mut u8, len as usize)
+        {
             return None;
         }
 
         let additional_len = self.get_add_mac_txt_len();
         let encrypt_len = self.get_encrypt_txt_len();
-        if (additional_len == u32::max_value()) || (encrypt_len == u32::max_value()) {
+        if (additional_len == u32::MAX) || (encrypt_len == u32::MAX) {
             return None;
         }
         if (additional_len + encrypt_len) != self.get_payload_size() {
@@ -146,7 +154,7 @@
         }
 
         let sealed_data_size = sgx_calc_sealed_data_size(additional_len, encrypt_len);
-        if sealed_data_size == u32::max_value() {
+        if sealed_data_size == u32::MAX {
             return None;
         }
         if len < sealed_data_size {
@@ -156,11 +164,19 @@
         let ptr_sealed_data = p as *mut u8;
         let ptr_encrypt = ptr_sealed_data.add(mem::size_of::<sgx_sealed_data_t>());
         if encrypt_len > 0 {
-            ptr::copy_nonoverlapping(self.payload_data.encrypt.as_ptr(), ptr_encrypt, encrypt_len as usize);
+            ptr::copy_nonoverlapping(
+                self.payload_data.encrypt.as_ptr(),
+                ptr_encrypt,
+                encrypt_len as usize,
+            );
         }
         if additional_len > 0 {
             let ptr_additional = ptr_encrypt.offset(encrypt_len as isize);
-            ptr::copy_nonoverlapping(self.payload_data.additional.as_ptr(), ptr_additional, additional_len as usize);
+            ptr::copy_nonoverlapping(
+                self.payload_data.additional.as_ptr(),
+                ptr_additional,
+                additional_len as usize,
+            );
         }
 
         let raw_sealed_data = &mut *p;
@@ -177,8 +193,9 @@
         if p.is_null() {
             return None;
         }
-        if !rsgx_raw_is_within_enclave(p as *mut u8, len as usize) &&
-           !rsgx_raw_is_outside_enclave(p as *mut u8, len as usize) {
+        if !rsgx_raw_is_within_enclave(p as *mut u8, len as usize)
+            && !rsgx_raw_is_outside_enclave(p as *mut u8, len as usize)
+        {
             return None;
         }
 
@@ -194,7 +211,7 @@
         let ptr_sealed_data = p as *mut u8;
         let additional_len = sgx_get_add_mac_txt_len(ptr_sealed_data as *const sgx_sealed_data_t);
         let encrypt_len = sgx_get_encrypt_txt_len(ptr_sealed_data as *const sgx_sealed_data_t);
-        if (additional_len == u32::max_value()) || (encrypt_len == u32::max_value()) {
+        if (additional_len == u32::MAX) || (encrypt_len == u32::MAX) {
             return None;
         }
         if (additional_len + encrypt_len) != raw_sealed_data.aes_data.payload_size {
@@ -202,7 +219,7 @@
         }
 
         let sealed_data_size = sgx_calc_sealed_data_size(additional_len, encrypt_len);
-        if sealed_data_size == u32::max_value() {
+        if sealed_data_size == u32::MAX {
             return None;
         }
         if len < sealed_data_size {
@@ -214,7 +231,11 @@
         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);
+            ptr::copy_nonoverlapping(
+                ptr_encrypt as *const u8,
+                temp.as_mut_ptr(),
+                encrypt_len as usize,
+            );
             temp
         } else {
             Vec::new()
@@ -224,7 +245,11 @@
             let ptr_additional = ptr_encrypt.offset(encrypt_len as isize);
             let mut temp: Vec<u8> = Vec::with_capacity(additional_len as usize);
             temp.set_len(additional_len as usize);
-            ptr::copy_nonoverlapping(ptr_additional as *const u8, temp.as_mut_ptr(), additional_len as usize);
+            ptr::copy_nonoverlapping(
+                ptr_additional as *const u8,
+                temp.as_mut_ptr(),
+                additional_len as usize,
+            );
             temp
         } else {
             Vec::new()
@@ -243,7 +268,10 @@
     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};
+        let attribute_mask = sgx_attributes_t {
+            flags: TSEAL_DEFAULT_FLAGSMASK,
+            xfrm: 0,
+        };
         /* intel sgx sdk 2.4 */
         let mut key_policy = SGX_KEYPOLICY_MRSIGNER;
         let report = rsgx_self_report();
@@ -270,22 +298,33 @@
         let additional_len = additional_text.len();
         let encrypt_len = encrypt_text.len();
 
-        if (additional_len >= u32::max_value() as usize) || (encrypt_len >= u32::max_value() as usize) {
+        if (additional_len >= u32::MAX as usize)
+            || (encrypt_len >= u32::MAX as usize)
+        {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if Self::calc_raw_sealed_data_size(additional_len as u32, encrypt_len as u32) == u32::max_value() {
+        if Self::calc_raw_sealed_data_size(additional_len as u32, encrypt_len as u32)
+            == u32::MAX
+        {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         if encrypt_len == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
-        if (key_policy & (!(SGX_KEYPOLICY_MRENCLAVE | SGX_KEYPOLICY_MRSIGNER | KEY_POLICY_KSS | SGX_KEYPOLICY_NOISVPRODID)) != 0) ||
-           ((key_policy & (SGX_KEYPOLICY_MRENCLAVE | SGX_KEYPOLICY_MRSIGNER)) == 0) {
+        if (key_policy
+            & (!(SGX_KEYPOLICY_MRENCLAVE
+                | SGX_KEYPOLICY_MRSIGNER
+                | KEY_POLICY_KSS
+                | SGX_KEYPOLICY_NOISVPRODID))
+            != 0)
+            || ((key_policy & (SGX_KEYPOLICY_MRENCLAVE | SGX_KEYPOLICY_MRSIGNER)) == 0)
+        {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if ((attribute_mask.flags & SGX_FLAGS_INITTED) == 0) ||
-           ((attribute_mask.flags & SGX_FLAGS_DEBUG) == 0) {
+        if ((attribute_mask.flags & SGX_FLAGS_INITTED) == 0)
+            || ((attribute_mask.flags & SGX_FLAGS_DEBUG) == 0)
+        {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
@@ -293,9 +332,10 @@
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
-        if additional_len > 0 &&
-           !rsgx_slice_is_within_enclave(additional_text) &&
-           !rsgx_slice_is_outside_enclave(additional_text) {
+        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);
         }
 
@@ -327,9 +367,12 @@
         };
 
         let payload_iv = [0_u8; SGX_SEAL_IV_SIZE];
-        let mut result = Self::seal_data_iv(additional_text, encrypt_text, &payload_iv, &key_request);
+        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();
@@ -341,10 +384,10 @@
         let additional_len = self.get_add_mac_txt_len();
         let encrypt_len = self.get_encrypt_txt_len();
 
-        if (additional_len == u32::max_value()) || (encrypt_len == u32::max_value()) {
+        if (additional_len == u32::MAX) || (encrypt_len == u32::MAX) {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
-        if Self::calc_raw_sealed_data_size(additional_len, encrypt_len) == u32::max_value() {
+        if Self::calc_raw_sealed_data_size(additional_len, encrypt_len) == u32::MAX {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
         if encrypt_len < 1 {
@@ -353,14 +396,13 @@
         if (additional_len + encrypt_len) != self.get_payload_size() {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
-        if !rsgx_raw_is_within_enclave(self as *const _ as *const u8,  mem::size_of::<Self>()) {
+        if !rsgx_raw_is_within_enclave(self as *const _ as *const u8, mem::size_of::<Self>()) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         if !rsgx_slice_is_within_enclave(self.get_encrypt_txt()) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if additional_len > 0 &&
-           !rsgx_slice_is_within_enclave(self.get_additional_txt()) {
+        if additional_len > 0 && !rsgx_slice_is_within_enclave(self.get_additional_txt()) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
@@ -368,7 +410,10 @@
     }
 
     pub fn mac_aadata(additional_text: &[u8]) -> SgxResult<Self> {
-        let attribute_mask = sgx_attributes_t{flags: TSEAL_DEFAULT_FLAGSMASK, xfrm: 0};
+        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();
 
@@ -391,27 +436,35 @@
         additional_text: &[u8],
     ) -> SgxResult<Self> {
         let additional_len = additional_text.len();
-        if additional_len >= u32::max_value() as usize {
+        if additional_len >= u32::MAX as usize {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if Self::calc_raw_sealed_data_size(additional_len as u32, 0_u32) == u32::max_value() {
+        if Self::calc_raw_sealed_data_size(additional_len as u32, 0_u32) == u32::MAX {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         if additional_len == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
-        if (key_policy & (!(SGX_KEYPOLICY_MRENCLAVE | SGX_KEYPOLICY_MRSIGNER | KEY_POLICY_KSS | SGX_KEYPOLICY_NOISVPRODID)) != 0) ||
-           ((key_policy & (SGX_KEYPOLICY_MRENCLAVE | SGX_KEYPOLICY_MRSIGNER)) == 0) {
+        if (key_policy
+            & (!(SGX_KEYPOLICY_MRENCLAVE
+                | SGX_KEYPOLICY_MRSIGNER
+                | KEY_POLICY_KSS
+                | SGX_KEYPOLICY_NOISVPRODID))
+            != 0)
+            || ((key_policy & (SGX_KEYPOLICY_MRENCLAVE | SGX_KEYPOLICY_MRSIGNER)) == 0)
+        {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        if ((attribute_mask.flags & SGX_FLAGS_INITTED) == 0) ||
-           ((attribute_mask.flags & SGX_FLAGS_DEBUG) == 0) {
+        if ((attribute_mask.flags & SGX_FLAGS_INITTED) == 0)
+            || ((attribute_mask.flags & SGX_FLAGS_DEBUG) == 0)
+        {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
-        if !rsgx_slice_is_within_enclave(additional_text) &&
-           !rsgx_slice_is_outside_enclave(additional_text) {
+        if !rsgx_slice_is_within_enclave(additional_text)
+            && !rsgx_slice_is_outside_enclave(additional_text)
+        {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
@@ -444,7 +497,9 @@
 
         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();
@@ -456,7 +511,7 @@
         let additional_len = self.get_add_mac_txt_len();
         let encrypt_len = self.get_encrypt_txt_len();
 
-        if (additional_len == u32::max_value()) || (encrypt_len == u32::max_value()) {
+        if (additional_len == u32::MAX) || (encrypt_len == u32::MAX) {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
         if additional_len < 1 {
@@ -465,14 +520,14 @@
         if encrypt_len != 0 {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
-        if Self::calc_raw_sealed_data_size(additional_len, encrypt_len) == u32::max_value() {
+        if Self::calc_raw_sealed_data_size(additional_len, encrypt_len) == u32::MAX {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
         if (additional_len + encrypt_len) != self.get_payload_size() {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
 
-        if !rsgx_raw_is_within_enclave(self as *const _ as *const u8,  mem::size_of::<Self>()) {
+        if !rsgx_raw_is_within_enclave(self as *const _ as *const u8, mem::size_of::<Self>()) {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         if !rsgx_slice_is_within_enclave(self.get_additional_txt()) {
@@ -524,9 +579,10 @@
 
     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) ||
-               (ret == sgx_status_t::SGX_ERROR_OUT_OF_MEMORY) {
+            if (ret == sgx_status_t::SGX_ERROR_INVALID_CPUSVN)
+                || (ret == sgx_status_t::SGX_ERROR_INVALID_ISVSVN)
+                || (ret == sgx_status_t::SGX_ERROR_OUT_OF_MEMORY)
+            {
                 ret
             } else {
                 sgx_status_t::SGX_ERROR_MAC_MISMATCH
diff --git a/sgx_tseal/src/lib.rs b/sgx_tseal/src/lib.rs
index 596b15a..e944626 100644
--- a/sgx_tseal/src/lib.rs
+++ b/sgx_tseal/src/lib.rs
@@ -79,15 +79,15 @@
 #[macro_use]
 extern crate alloc;
 
-extern crate sgx_types;
-extern crate sgx_trts;
 extern crate sgx_tcrypto;
+extern crate sgx_trts;
 extern crate sgx_tse;
+extern crate sgx_types;
 
 mod seal;
 pub use self::seal::{SgxSealedData, SgxUnsealedData};
 
 mod aad;
-pub use self::aad::{SgxMacAadata};
+pub use self::aad::SgxMacAadata;
 
 mod internal;
diff --git a/sgx_tseal/src/seal.rs b/sgx_tseal/src/seal.rs
index b898286..8b866a7 100644
--- a/sgx_tseal/src/seal.rs
+++ b/sgx_tseal/src/seal.rs
@@ -27,13 +27,13 @@
 //!
 //! The library also provides APIs to help calculate the sealed data size, encrypt text length, and Message Authentication Code (MAC) text length.
 //!
-use sgx_types::*;
-use sgx_types::marker::ContiguousMemory;
 use crate::internal::*;
-use core::mem;
-use core::marker::PhantomData;
-use alloc::slice;
 use alloc::boxed::Box;
+use alloc::slice;
+use core::marker::PhantomData;
+use core::mem;
+use sgx_types::marker::ContiguousMemory;
+use sgx_types::*;
 
 /// The structure about the unsealed data.
 pub struct SgxUnsealedData<'a, T: 'a + ?Sized> {
@@ -89,10 +89,10 @@
 impl<'a, T: 'a + Clone + ?Sized> Clone for SgxUnsealedData<'a, T> {
     fn clone(&self) -> SgxUnsealedData<'a, T> {
         SgxUnsealedData {
-           payload_size: self.payload_size,
-           decrypt: self.decrypt.clone(),
-           additional: self.additional.clone(),
-           marker: PhantomData,
+            payload_size: self.payload_size,
+            decrypt: self.decrypt.clone(),
+            additional: self.additional.clone(),
+            marker: PhantomData,
         }
     }
 }
@@ -115,8 +115,8 @@
 impl<'a, T: 'a + Clone + ?Sized> Clone for SgxSealedData<'a, T> {
     fn clone(&self) -> SgxSealedData<'a, T> {
         SgxSealedData {
-           inner: self.inner.clone(),
-           marker: PhantomData,
+            inner: self.inner.clone(),
+            marker: PhantomData,
         }
     }
 }
@@ -186,14 +186,15 @@
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         let encrypt_slice: &[u8] = unsafe {
-            slice::from_raw_parts(encrypt_text as *const _ as *const u8, mem::size_of_val(encrypt_text))
+            slice::from_raw_parts(
+                encrypt_text as *const _ as *const u8,
+                mem::size_of_val(encrypt_text),
+            )
         };
         let result = SgxInternalSealedData::seal_data(additional_text, encrypt_slice);
-        result.map(|x| {
-            SgxSealedData {
-                inner: x,
-                marker: PhantomData,
-            }
+        result.map(|x| SgxSealedData {
+            inner: x,
+            marker: PhantomData,
         })
     }
 
@@ -283,21 +284,21 @@
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
         let encrypt_slice: &[u8] = unsafe {
-            slice::from_raw_parts(encrypt_text as *const _ as *const u8, mem::size_of_val(encrypt_text))
+            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,
-            );
-        result.map(|x| {
-            SgxSealedData {
-                inner: x,
-                marker: PhantomData,
-            }
+        let result = SgxInternalSealedData::seal_data_ex(
+            key_policy,
+            attribute_mask,
+            misc_mask,
+            additional_text,
+            encrypt_slice,
+        );
+        result.map(|x| SgxSealedData {
+            inner: x,
+            marker: PhantomData,
         })
     }
 
@@ -362,7 +363,7 @@
             let ptr = Box::into_raw(x.decrypt);
             SgxUnsealedData {
                 payload_size: x.payload_size,
-                decrypt: unsafe{Box::from_raw(ptr as *mut T)},
+                decrypt: unsafe { Box::from_raw(ptr as *mut T) },
                 additional: x.additional,
                 marker: PhantomData,
             }
@@ -402,10 +403,9 @@
             return None;
         }
         let opt = SgxInternalSealedData::from_raw_sealed_data_t(p, len);
-        opt.map(|x| {
-            SgxSealedData{
-                inner: x,
-                marker: PhantomData}
+        opt.map(|x| SgxSealedData {
+            inner: x,
+            marker: PhantomData,
         })
     }
 
@@ -432,7 +432,11 @@
     ///
     /// May be the parameter p and len is not avaliable.
     ///
-    pub unsafe fn to_raw_sealed_data_t(&self, p: *mut sgx_sealed_data_t, len: u32) -> Option<*mut sgx_sealed_data_t> {
+    pub unsafe fn to_raw_sealed_data_t(
+        &self,
+        p: *mut sgx_sealed_data_t,
+        len: u32,
+    ) -> Option<*mut sgx_sealed_data_t> {
         self.inner.to_raw_sealed_data_t(p, len)
     }
 }
@@ -502,16 +506,13 @@
         if size == 0 || len == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        let encrypt_slice: &[u8] = unsafe {
-            slice::from_raw_parts(encrypt_text.as_ptr() as *const u8, len)
-        };
+        let encrypt_slice: &[u8] =
+            unsafe { slice::from_raw_parts(encrypt_text.as_ptr() as *const u8, len) };
 
         let result = SgxInternalSealedData::seal_data(additional_text, encrypt_slice);
-        result.map(|x| {
-            SgxSealedData {
-                inner: x,
-                marker: PhantomData,
-            }
+        result.map(|x| SgxSealedData {
+            inner: x,
+            marker: PhantomData,
         })
     }
 
@@ -601,23 +602,19 @@
         if size == 0 || len == 0 {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
-        let encrypt_slice: &[u8] = unsafe {
-            slice::from_raw_parts(encrypt_text.as_ptr() as *const u8, len)
-        };
+        let encrypt_slice: &[u8] =
+            unsafe { 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,
-            );
-        result.map(|x| {
-            SgxSealedData {
-                inner: x,
-                marker: PhantomData,
-            }
+        let result = SgxInternalSealedData::seal_data_ex(
+            key_policy,
+            attribute_mask,
+            misc_mask,
+            additional_text,
+            encrypt_slice,
+        );
+        result.map(|x| SgxSealedData {
+            inner: x,
+            marker: PhantomData,
         })
     }
 
@@ -684,10 +681,10 @@
 
         self.inner.unseal_data().map(|x| {
             let ptr = Box::into_raw(x.decrypt);
-            let slice = unsafe{slice::from_raw_parts_mut(ptr as *mut T, encrypt_len/size)};
+            let slice = unsafe { slice::from_raw_parts_mut(ptr as *mut T, encrypt_len / size) };
             SgxUnsealedData {
                 payload_size: x.payload_size,
-                decrypt: unsafe{Box::from_raw(slice as *mut [T])},
+                decrypt: unsafe { Box::from_raw(slice as *mut [T]) },
                 additional: x.additional,
                 marker: PhantomData,
             }
@@ -727,11 +724,9 @@
             return None;
         }
         let opt = SgxInternalSealedData::from_raw_sealed_data_t(p, len);
-        opt.map(|x| {
-            SgxSealedData {
-                inner: x,
-                marker: PhantomData,
-            }
+        opt.map(|x| SgxSealedData {
+            inner: x,
+            marker: PhantomData,
         })
     }
 
@@ -758,7 +753,11 @@
     ///
     /// May be the parameter p and len is not avaliable.
     ///
-    pub unsafe fn to_raw_sealed_data_t(&self, p: *mut sgx_sealed_data_t, len: u32) -> Option<*mut sgx_sealed_data_t> {
+    pub unsafe fn to_raw_sealed_data_t(
+        &self,
+        p: *mut sgx_sealed_data_t,
+        len: u32,
+    ) -> Option<*mut sgx_sealed_data_t> {
         self.inner.to_raw_sealed_data_t(p, len)
     }
 }
@@ -809,7 +808,7 @@
     ///
     /// Calculate the size of the sealed data in SgxSealedData.
     ///
-    pub fn calc_raw_sealed_data_size(add_mac_txt_size: u32, encrypt_txt_size: u32) -> u32  {
+    pub fn calc_raw_sealed_data_size(add_mac_txt_size: u32, encrypt_txt_size: u32) -> u32 {
         SgxInternalSealedData::calc_raw_sealed_data_size(add_mac_txt_size, encrypt_txt_size)
     }
 
diff --git a/sgx_tstd/src/lib.rs b/sgx_tstd/src/lib.rs
index 020dfe0..f8ff0f6 100644
--- a/sgx_tstd/src/lib.rs
+++ b/sgx_tstd/src/lib.rs
@@ -94,7 +94,7 @@
 #![feature(panic_info_message)]
 #![feature(unicode_internals)]
 #![feature(alloc_layout_extra)]
-#![feature(vec_remove_item)]
+#![feature(linked_list_remove)]
 #![feature(int_error_matching)]
 #![feature(drain_filter)]
 #![feature(negative_impls)]
diff --git a/sgx_tstd/src/sys/condvar.rs b/sgx_tstd/src/sys/condvar.rs
index 0071edb..4a749c1 100644
--- a/sgx_tstd/src/sys/condvar.rs
+++ b/sgx_tstd/src/sys/condvar.rs
@@ -15,43 +15,44 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::{SysError, sgx_thread_t, SGX_THREAD_T_NULL};
-use sgx_trts::enclave::SgxThreadData;
-use sgx_trts::libc;
+use alloc_crate::collections::LinkedList;
 use core::cell::UnsafeCell;
 use crate::io::{self, Error};
 use crate::sys::mutex::{self, SgxThreadMutex};
 use crate::sync::SgxThreadSpinlock;
 use crate::time::Duration;
-use crate::thread::{self, rsgx_thread_self};
+use crate::thread::rsgx_thread_self;
 use crate::u64;
+use sgx_trts::enclave::SgxThreadData;
+use sgx_trts::libc;
+use sgx_types::{SysError, sgx_thread_t, SGX_THREAD_T_NULL};
 
 struct SgxThreadCondvarInner {
-    spinlock: SgxThreadSpinlock,
-    thread_vec: Vec<sgx_thread_t>,
+    lock: SgxThreadSpinlock,
+    queue: LinkedList<sgx_thread_t>,
 }
 
 impl SgxThreadCondvarInner {
     pub const fn new() -> Self {
         SgxThreadCondvarInner {
-            spinlock: SgxThreadSpinlock::new(),
-            thread_vec: Vec::new(),
+            lock: SgxThreadSpinlock::new(),
+            queue: LinkedList::new(),
         }
     }
 
     pub unsafe fn wait(&mut self, mutex: &SgxThreadMutex) -> SysError {
-        self.spinlock.lock();
-        self.thread_vec.push(rsgx_thread_self());
+        self.lock.lock();
+        self.queue.push_back(rsgx_thread_self());
         let mut waiter: sgx_thread_t = SGX_THREAD_T_NULL;
 
         mutex.unlock_lazy(&mut waiter).map_err(|ret| {
-            self.thread_vec.pop();
-            self.spinlock.unlock();
+            self.queue.pop_back();
+            self.lock.unlock();
             ret
         })?;
 
         loop {
-            self.spinlock.unlock();
+            self.lock.unlock();
             if waiter == SGX_THREAD_T_NULL {
                 mutex::thread_wait_event(SgxThreadData::current().get_tcs(), Duration::new(u64::MAX, 1_000_000_000 - 1));
             } else {
@@ -62,36 +63,30 @@
                 );
                 waiter = SGX_THREAD_T_NULL;
             }
-            self.spinlock.lock();
-            let mut thread_waiter: sgx_thread_t = SGX_THREAD_T_NULL;
-            for tmp in &self.thread_vec {
-                if thread::rsgx_thread_equal(*tmp, rsgx_thread_self()) {
-                    thread_waiter = *tmp;
-                    break;
-                }
-            }
-            if thread_waiter == SGX_THREAD_T_NULL {
+            self.lock.lock();
+
+            if !self.queue.contains(&rsgx_thread_self()) {
                 break;
             }
         }
-        self.spinlock.unlock();
+        self.lock.unlock();
         mutex.lock();
         Ok(())
     }
 
     pub unsafe fn wait_timeout(&mut self, mutex: &SgxThreadMutex, dur: Duration) -> SysError {
-        self.spinlock.lock();
-        self.thread_vec.push(rsgx_thread_self());
+        self.lock.lock();
+        self.queue.push_back(rsgx_thread_self());
         let mut waiter: sgx_thread_t = SGX_THREAD_T_NULL;
 
         mutex.unlock_lazy(&mut waiter).map_err(|ret| {
-            self.thread_vec.pop();
-            self.spinlock.unlock();
+            self.queue.pop_back();
+            self.lock.unlock();
             ret
         })?;
         let mut ret = Ok(());
         loop {
-            self.spinlock.unlock();
+            self.lock.unlock();
             let mut result = 0;
             if waiter == SGX_THREAD_T_NULL {
                 result = mutex::thread_wait_event(SgxThreadData::current().get_tcs(), dur);
@@ -104,58 +99,53 @@
                 waiter = SGX_THREAD_T_NULL;
             }
 
-            self.spinlock.lock();
-            let mut thread_waiter: sgx_thread_t = SGX_THREAD_T_NULL;
-            for tmp in &self.thread_vec {
-                if thread::rsgx_thread_equal(*tmp, rsgx_thread_self()) {
-                    thread_waiter = *tmp;
-                    break;
+            self.lock.lock();
+            match self
+                .queue
+                .iter()
+                .position(|&waiter| waiter == rsgx_thread_self())
+            {
+                Some(pos) => {
+                    if result < 0 && Error::last_os_error().kind() == io::ErrorKind::TimedOut {
+                        self.queue.remove(pos);
+                        ret = Err(libc::ETIMEDOUT);
+                        break;
+                    }
                 }
-            }
-
-            if thread_waiter != SGX_THREAD_T_NULL && result < 0 {
-                if Error::last_os_error().kind() == io::ErrorKind::TimedOut {
-                    self.thread_vec.remove_item(&thread_waiter);
-                    ret = Err(libc::ETIMEDOUT);
-                    break;
-                }
-            }
-
-            if thread_waiter == SGX_THREAD_T_NULL {
-                break;
+                None => break,
             }
         }
-        self.spinlock.unlock();
+        self.lock.unlock();
         mutex.lock();
         ret
     }
 
     pub unsafe fn signal(&mut self) -> SysError {
-        self.spinlock.lock();
-        if self.thread_vec.is_empty() {
-            self.spinlock.unlock();
+        self.lock.lock();
+        if self.queue.is_empty() {
+            self.lock.unlock();
             return Ok(());
         }
 
-        let waiter: sgx_thread_t = *self.thread_vec.first().unwrap();
-        self.thread_vec.remove(0);
-        self.spinlock.unlock();
+        let waiter: sgx_thread_t = *self.queue.front().unwrap();
+        self.queue.pop_front();
+        self.lock.unlock();
         mutex::thread_set_event(SgxThreadData::from_raw(waiter).get_tcs());
         Ok(())
     }
 
     pub unsafe fn broadcast(&mut self) -> SysError {
-        self.spinlock.lock();
-        if self.thread_vec.is_empty() {
-            self.spinlock.unlock();
+        self.lock.lock();
+        if self.queue.is_empty() {
+            self.lock.unlock();
             return Ok(());
         }
 
         let mut tcs_vec: Vec<usize> = Vec::new();
-        while let Some(waiter) = self.thread_vec.pop() {
+        while let Some(waiter) = self.queue.pop_back() {
            tcs_vec.push(SgxThreadData::from_raw(waiter).get_tcs())
         }
-        self.spinlock.unlock();
+        self.lock.unlock();
         mutex::thread_set_multiple_events(tcs_vec.as_slice());
         Ok(())
     }
@@ -169,17 +159,21 @@
     }
 
     pub unsafe fn destroy(&mut self) -> SysError {
-        self.spinlock.lock();
-        let ret = if self.thread_vec.is_empty() {
+        self.lock.lock();
+        let ret = if self.queue.is_empty() {
             Ok(())
         } else {
             Err(libc::EBUSY)
         };
-        self.spinlock.unlock();
+        self.lock.unlock();
         ret
     }
 }
 
+unsafe impl Send for SgxThreadCondvar {}
+unsafe impl Sync for SgxThreadCondvar {}
+
+
 pub struct SgxThreadCondvar {
     inner: UnsafeCell<SgxThreadCondvarInner>,
 }
diff --git a/sgx_tstd/src/sys/mutex.rs b/sgx_tstd/src/sys/mutex.rs
index e8adb43..6fcb7f4 100644
--- a/sgx_tstd/src/sys/mutex.rs
+++ b/sgx_tstd/src/sys/mutex.rs
@@ -15,18 +15,19 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::{self, SysError, sgx_status_t, sgx_thread_t, SGX_THREAD_T_NULL};
-use sgx_trts::libc;
-use sgx_trts::error::set_errno;
-use sgx_trts::enclave::SgxThreadData;
-use sgx_libc::{c_void, c_int, c_long, time_t, timespec};
-use core::ptr;
-use core::cmp;
+use alloc_crate::collections::LinkedList;
 use core::cell::UnsafeCell;
+use core::cmp;
+use core::ptr;
 use crate::sync::SgxThreadSpinlock;
-use crate::thread::{self, rsgx_thread_self};
+use crate::thread::rsgx_thread_self;
 use crate::time::Duration;
 use crate::u64;
+use sgx_libc::{c_int, c_long, c_void, time_t, timespec};
+use sgx_trts::enclave::SgxThreadData;
+use sgx_trts::error::set_errno;
+use sgx_trts::libc;
+use sgx_types::{self, sgx_status_t, sgx_thread_t, SysError, SGX_THREAD_T_NULL};
 
 extern "C" {
     pub fn u_thread_wait_event_ocall(
@@ -61,9 +62,12 @@
 pub unsafe fn thread_wait_event(tcs: usize, dur: Duration) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let mut timeout = timespec { tv_sec: 0, tv_nsec: 0 };
+    let mut timeout = timespec {
+        tv_sec: 0,
+        tv_nsec: 0,
+    };
     let timeout_ptr: *const timespec = if dur != Duration::new(u64::MAX, 1_000_000_000 - 1) {
-        timeout.tv_sec = cmp::min(dur.as_secs(), time_t::max_value() as u64) as time_t;
+        timeout.tv_sec = cmp::min(dur.as_secs(), time_t::MAX as u64) as time_t;
         timeout.tv_nsec = dur.subsec_nanos() as c_long;
         &timeout as *const timespec
     } else {
@@ -77,7 +81,9 @@
         timeout_ptr,
     );
     if status == sgx_status_t::SGX_SUCCESS {
-        if result == -1 { set_errno(error); }
+        if result == -1 {
+            set_errno(error);
+        }
     } else {
         set_errno(libc::ESGX);
         result = -1;
@@ -94,7 +100,9 @@
         tcs as *const c_void,
     );
     if status == sgx_status_t::SGX_SUCCESS {
-        if result == -1 { set_errno(error); }
+        if result == -1 {
+            set_errno(error);
+        }
     } else {
         set_errno(libc::ESGX);
         result = -1;
@@ -126,9 +134,12 @@
 pub unsafe fn thread_setwait_events(wait_tcs: usize, self_tcs: usize, dur: Duration) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let mut timeout = timespec { tv_sec: 0, tv_nsec: 0 };
+    let mut timeout = timespec {
+        tv_sec: 0,
+        tv_nsec: 0,
+    };
     let timeout_ptr: *const timespec = if dur != Duration::new(u64::MAX, 1_000_000_000 - 1) {
-        timeout.tv_sec = cmp::min(dur.as_secs(), time_t::max_value() as u64) as time_t;
+        timeout.tv_sec = cmp::min(dur.as_secs(), time_t::MAX as u64) as time_t;
         timeout.tv_nsec = dur.subsec_nanos() as c_long;
         &timeout as *const timespec
     } else {
@@ -143,7 +154,9 @@
         timeout_ptr,
     );
     if status == sgx_status_t::SGX_SUCCESS {
-        if result == -1 { set_errno(error); }
+        if result == -1 {
+            set_errno(error);
+        }
     } else {
         set_errno(libc::ESGX);
         result = -1;
@@ -160,88 +173,83 @@
 struct SgxThreadMutexInner {
     refcount: usize,
     control: SgxThreadMutexControl,
-    spinlock: SgxThreadSpinlock,
-    thread_owner: sgx_thread_t,
-    thread_vec: Vec<sgx_thread_t>,
+    lock: SgxThreadSpinlock,
+    owner: sgx_thread_t,
+    queue: LinkedList<sgx_thread_t>,
 }
 
 impl SgxThreadMutexInner {
-
     const fn new(control: SgxThreadMutexControl) -> Self {
         SgxThreadMutexInner {
             refcount: 0,
             control: control,
-            spinlock: SgxThreadSpinlock::new(),
-            thread_owner: SGX_THREAD_T_NULL,
-            thread_vec: Vec::new(),
+            lock: SgxThreadSpinlock::new(),
+            owner: SGX_THREAD_T_NULL,
+            queue: LinkedList::new(),
         }
     }
 
     unsafe fn lock(&mut self) -> SysError {
         loop {
-            self.spinlock.lock();
-            if self.control == SgxThreadMutexControl::SGX_THREAD_MUTEX_RECURSIVE &&
-                self.thread_owner == rsgx_thread_self() {
+            self.lock.lock();
+            if self.control == SgxThreadMutexControl::SGX_THREAD_MUTEX_RECURSIVE
+                && self.owner == rsgx_thread_self()
+            {
                 self.refcount += 1;
-                self.spinlock.unlock();
+                self.lock.unlock();
                 return Ok(());
             }
 
-            if self.thread_owner == SGX_THREAD_T_NULL &&
-                (self.thread_vec.first() == Some(&rsgx_thread_self()) ||
-                self.thread_vec.first() == None) {
-
-                if self.thread_vec.first() == Some(&rsgx_thread_self()) {
-                    self.thread_vec.remove(0);
+            if self.owner == SGX_THREAD_T_NULL
+                && (self.queue.front() == Some(&rsgx_thread_self())
+                    || self.queue.front() == None)
+            {
+                if self.queue.front() == Some(&rsgx_thread_self()) {
+                    self.queue.pop_front();
                 }
 
-                self.thread_owner = rsgx_thread_self();
+                self.owner = rsgx_thread_self();
                 self.refcount += 1;
-                self.spinlock.unlock();
-
+                self.lock.unlock();
                 return Ok(());
             }
 
-            let mut thread_waiter: sgx_thread_t = SGX_THREAD_T_NULL;
-            for waiter in &self.thread_vec {
-                if thread::rsgx_thread_equal(*waiter, rsgx_thread_self()) {
-                    thread_waiter = *waiter;
-                    break;
-                }
+            if !self.queue.contains(&rsgx_thread_self()) {
+                self.queue.push_back(rsgx_thread_self());
             }
 
-            if thread_waiter == SGX_THREAD_T_NULL {
-                self.thread_vec.push(rsgx_thread_self());
-            }
-            self.spinlock.unlock();
-            thread_wait_event(SgxThreadData::current().get_tcs(), Duration::new(u64::MAX, 1_000_000_000 - 1));
+            self.lock.unlock();
+            thread_wait_event(
+                SgxThreadData::current().get_tcs(),
+                Duration::new(u64::MAX, 1_000_000_000 - 1),
+            );
         }
     }
 
     unsafe fn try_lock(&mut self) -> SysError {
-        self.spinlock.lock();
-        if self.control == SgxThreadMutexControl::SGX_THREAD_MUTEX_RECURSIVE &&
-            self.thread_owner == rsgx_thread_self() {
-
+        self.lock.lock();
+        if self.control == SgxThreadMutexControl::SGX_THREAD_MUTEX_RECURSIVE
+            && self.owner == rsgx_thread_self()
+        {
             self.refcount += 1;
-            self.spinlock.unlock();
+            self.lock.unlock();
             return Ok(());
         }
 
-        if self.thread_owner == SGX_THREAD_T_NULL &&
-            (self.thread_vec.first() == Some(&rsgx_thread_self()) ||
-            self.thread_vec.first() == None) {
-
-            if self.thread_vec.first() == Some(&rsgx_thread_self()) {
-                self.thread_vec.remove(0);
+        if self.owner == SGX_THREAD_T_NULL
+            && (self.queue.front() == Some(&rsgx_thread_self())
+                || self.queue.front() == None)
+        {
+            if self.queue.front() == Some(&rsgx_thread_self()) {
+                self.queue.pop_front();
             }
 
-            self.thread_owner = rsgx_thread_self();
+            self.owner = rsgx_thread_self();
             self.refcount += 1;
-            self.spinlock.unlock();
+            self.lock.unlock();
             return Ok(());
         }
-        self.spinlock.unlock();
+        self.lock.unlock();
         Err(libc::EBUSY)
     }
 
@@ -249,67 +257,71 @@
         let mut thread_waiter = SGX_THREAD_T_NULL;
         self.unlock_lazy(&mut thread_waiter)?;
 
-        if thread_waiter != SGX_THREAD_T_NULL /* wake the waiter up*/ {
+        if thread_waiter != SGX_THREAD_T_NULL {
+            // wake the waiter up
             thread_set_event(SgxThreadData::from_raw(thread_waiter).get_tcs());
         }
         Ok(())
     }
 
     unsafe fn unlock_lazy(&mut self, waiter: &mut sgx_thread_t) -> SysError {
-        self.spinlock.lock();
-        //if the mutux is not locked by anyone
-        if self.thread_owner == SGX_THREAD_T_NULL {
-            self.spinlock.unlock();
+        self.lock.lock();
+        // if the mutux is not locked by anyone
+        if self.owner == SGX_THREAD_T_NULL {
+            self.lock.unlock();
             return Err(libc::EPERM);
         }
 
-        //if the mutex is locked by another thread
-        if self.thread_owner != rsgx_thread_self() {
-            self.spinlock.unlock();
+        // if the mutex is locked by another thread
+        if self.owner != rsgx_thread_self() {
+            self.lock.unlock();
             return Err(libc::EPERM);
         }
-        //the mutex is locked by current thread
+        // the mutex is locked by current thread
         self.refcount -= 1;
         if self.refcount == 0 {
-            self.thread_owner = SGX_THREAD_T_NULL;
+            self.owner = SGX_THREAD_T_NULL;
         } else {
-            self.spinlock.unlock();
+            self.lock.unlock();
             return Ok(());
         }
-        //Before releasing the mutex, get the first thread,
-        //the thread should be waked up by the caller.
-        if self.thread_vec.is_empty() {
+        // Before releasing the mutex, get the first thread,
+        // the thread should be waked up by the caller.
+        if self.queue.is_empty() {
             *waiter = SGX_THREAD_T_NULL;
         } else {
-            *waiter = *self.thread_vec.first().unwrap();
+            *waiter = *self.queue.front().unwrap();
         }
 
-        self.spinlock.unlock();
+        self.lock.unlock();
         Ok(())
     }
 
     unsafe fn destroy(&mut self) -> SysError {
-        self.spinlock.lock();
-        if self.thread_owner != SGX_THREAD_T_NULL || !self.thread_vec.is_empty() {
-            self.spinlock.unlock();
+        self.lock.lock();
+        let ret = if self.owner != SGX_THREAD_T_NULL || !self.queue.is_empty() {
             Err(libc::EBUSY)
         } else {
             self.control = SgxThreadMutexControl::SGX_THREAD_MUTEX_NONRECURSIVE;
             self.refcount = 0;
-            self.spinlock.unlock();
             Ok(())
-        }
+        };
+        self.lock.unlock();
+        ret
     }
 }
 
+unsafe impl Send for SgxThreadMutex {}
+unsafe impl Sync for SgxThreadMutex {}
+
 pub struct SgxThreadMutex {
     lock: UnsafeCell<SgxThreadMutexInner>,
 }
 
 impl SgxThreadMutex {
     pub const fn new(control: SgxThreadMutexControl) -> Self {
-        SgxThreadMutex { 
-            lock: UnsafeCell::new(SgxThreadMutexInner::new(control))
+        SgxThreadMutex {
+            lock: UnsafeCell::new(SgxThreadMutexInner::new(control)),
         }
     }
 
diff --git a/sgx_tstd/src/sys/rwlock.rs b/sgx_tstd/src/sys/rwlock.rs
index d82f66b..702d685 100644
--- a/sgx_tstd/src/sys/rwlock.rs
+++ b/sgx_tstd/src/sys/rwlock.rs
@@ -15,233 +15,218 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::{SysError, sgx_thread_t, SGX_THREAD_T_NULL};
-use sgx_trts::libc;
-use crate::thread;
-use crate::sync::SgxThreadMutex;
-use crate::sync::SgxThreadCondvar;
-use crate::sync::SgxThreadSpinlock;
+use alloc_crate::collections::LinkedList;
 use core::cell::UnsafeCell;
+use crate::sync::SgxThreadSpinlock;
+use crate::time::Duration;
+use crate::thread::rsgx_thread_self;
+use crate::sys::mutex;
+use sgx_trts::enclave::SgxThreadData;
+use sgx_trts::libc;
+use sgx_types::{sgx_thread_t, SysError, SGX_THREAD_T_NULL};
 
 struct SgxThreadRwLockInner {
-    readers_num: u32,
-    writers_num: u32,
-    busy: u32,
-    writer_thread: sgx_thread_t,
-    condvar: SgxThreadCondvar,
-    mutex: SgxThreadMutex,
-    spinlock: SgxThreadSpinlock,
+    reader_count: u32,
+    writer_waiting: u32,
+    lock: SgxThreadSpinlock,
+    owner: sgx_thread_t,
+    reader_queue: LinkedList<sgx_thread_t>,
+    writer_queue: LinkedList<sgx_thread_t>,
 }
 
 impl SgxThreadRwLockInner {
-
     const fn new() -> Self {
-        SgxThreadRwLockInner{
-            readers_num: 0,
-            writers_num: 0,
-            busy: 0,
-            writer_thread: SGX_THREAD_T_NULL,
-            condvar: SgxThreadCondvar::new(),
-            mutex: SgxThreadMutex::new(),
-            spinlock: SgxThreadSpinlock::new(),
+        SgxThreadRwLockInner {
+            reader_count: 0,
+            writer_waiting: 0,
+            lock: SgxThreadSpinlock::new(),
+            owner: SGX_THREAD_T_NULL,
+            reader_queue: LinkedList::new(),
+            writer_queue: LinkedList::new(),
         }
     }
 
-    unsafe fn ref_busy(&mut self) -> SysError {
-        let ret: SysError;
-        self.spinlock.lock();
-        {
-            if self.busy == u32::max_value() {
-                ret = Err(libc::EAGAIN);
-            } else {
-                self.busy += 1;
-                ret = Ok(());
-            }
-        }
-        self.spinlock.unlock();
-        ret
-    }
-
-    unsafe fn deref_busy(&mut self) -> SysError {
-        let ret: SysError;
-        self.spinlock.lock();
-        {
-            if self.busy == 0 {
-                ret = Err(libc::EAGAIN);
-            } else {
-                self.busy -= 1;
-                ret = Ok(());
-            }
-        }
-        self.spinlock.unlock();
-        ret
-    }
-
     unsafe fn read(&mut self) -> SysError {
-        self.ref_busy()?;
-        self.mutex.lock();
-        {
-            if self.writer_thread == thread::rsgx_thread_self() {
-                self.mutex.unlock();
-                self.deref_busy();
+        let current = rsgx_thread_self();
+
+        self.lock.lock();
+        if self.owner == SGX_THREAD_T_NULL {
+            self.reader_count += 1;
+        } else {
+            if self.owner == current {
+                self.lock.unlock();
                 return Err(libc::EDEADLK);
             }
-            if self.readers_num == u32::max_value() {
-                self.mutex.unlock();
-                self.deref_busy();
-                return Err(libc::EAGAIN);
+
+            self.reader_queue.push_back(current);
+
+            loop {
+                self.lock.unlock();
+                mutex::thread_wait_event(
+                    SgxThreadData::from_raw(current).get_tcs(),
+                    Duration::new(u64::MAX, 1_000_000_000 - 1),
+                );
+
+                self.lock.lock();
+                if self.owner == SGX_THREAD_T_NULL {
+                    self.reader_count += 1;
+                    if let Some(pos) = self
+                        .reader_queue
+                        .iter()
+                        .position(|&waiter| waiter == current)
+                    {
+                        self.reader_queue.remove(pos);
+                    }
+                    break;
+                }
             }
-            while self.writers_num > 0 {
-                self.condvar.wait(&self.mutex);
-            }
-            self.readers_num += 1;
         }
-        self.mutex.unlock();
-        self.deref_busy();
+        self.lock.unlock();
         Ok(())
     }
 
     unsafe fn try_read(&mut self) -> SysError {
-        self.ref_busy()?;
-        self.mutex.lock();
-        {
-            let mut ret = Ok(());
-            if self.writer_thread == thread::rsgx_thread_self() {
-                ret = Err(libc::EDEADLK);
-            }
-            else if self.readers_num == u32::max_value() {
-                ret = Err(libc::EAGAIN);
-            }
-            else if self.writers_num > 0 {
-                ret = Err(libc::EBUSY);
-            }
-            match ret {
-                Ok(_) => {},
-                Err(e) => {
-                    self.mutex.unlock();
-                    self.deref_busy();
-                    return Err(e);
-                }
-            }
-            self.readers_num += 1;
-        }
-        self.mutex.unlock();
-        self.deref_busy();
-        Ok(())
+        self.lock.lock();
+        let ret = if self.owner == SGX_THREAD_T_NULL {
+            self.reader_count += 1;
+            Ok(())
+        } else {
+            Err(libc::EBUSY)
+        };
+        self.lock.unlock();
+        ret
     }
 
     unsafe fn write(&mut self) -> SysError {
-        self.ref_busy()?;
-        self.mutex.lock();
-        {
-            if self.writer_thread == thread::rsgx_thread_self() {
-                self.mutex.unlock();
-                self.deref_busy();
+        let current = rsgx_thread_self();
+
+        self.lock.lock();
+        if self.owner == SGX_THREAD_T_NULL && self.reader_count == 0 {
+            self.owner = current;
+        } else {
+            if self.owner == current {
+                self.lock.unlock();
                 return Err(libc::EDEADLK);
             }
 
-            if self.writers_num == u32::max_value() {
-                self.mutex.unlock();
-                self.deref_busy();
-                return Err(libc::EAGAIN);
-            }
+            self.writer_queue.push_back(current);
 
-            self.writers_num += 1;
-            while self.readers_num > 0 {
-                self.condvar.wait(&self.mutex);
+            loop {
+                self.lock.unlock();
+                mutex::thread_wait_event(
+                    SgxThreadData::from_raw(current).get_tcs(),
+                    Duration::new(u64::MAX, 1_000_000_000 - 1),
+                );
+
+                self.lock.lock();
+                if self.owner == SGX_THREAD_T_NULL && self.reader_count == 0 {
+                    self.owner = current;
+                    if let Some(pos) = self
+                        .writer_queue
+                        .iter()
+                        .position(|&waiter| waiter == current)
+                    {
+                        self.writer_queue.remove(pos);
+                    }
+                    break;
+                }
             }
-            while self.writer_thread != SGX_THREAD_T_NULL {
-                self.condvar.wait(&self.mutex);
-            }
-            self.writer_thread = thread::rsgx_thread_self();
         }
-        self.mutex.unlock();
-        self.deref_busy();
+        self.lock.unlock();
         Ok(())
     }
 
-    pub unsafe fn try_write(&mut self) -> SysError {
-        self.ref_busy()?;
-        self.mutex.lock();
-        {
-            let mut ret = Ok(());
-            if self.writer_thread == thread::rsgx_thread_self() {
-                ret = Err(libc::EDEADLK);
-            }
-            else if self.writers_num == u32::max_value() {
-                ret = Err(libc::EAGAIN);
-            }
-            else if self.readers_num > 0 || self.writer_thread != SGX_THREAD_T_NULL {
-                ret = Err(libc::EBUSY);
-            }
+    unsafe fn try_write(&mut self) -> SysError {
+        let current = rsgx_thread_self();
 
-            match ret {
-                Ok(_) => {},
-                Err(e) => {
-                    self.mutex.unlock();
-                    self.deref_busy();
-                    return Err(e);
-                }
-            }
-            self.writers_num += 1;
-            self.writer_thread = thread::rsgx_thread_self();
-        }
-        self.mutex.unlock();
-        self.deref_busy();
-        Ok(())
+        self.lock.lock();
+        let ret = if self.owner == SGX_THREAD_T_NULL && self.reader_count == 0 {
+            self.owner = current;
+            Ok(())
+        } else {
+            Err(libc::EBUSY)
+        };
+        self.lock.unlock();
+        ret
     }
 
     unsafe fn read_unlock(&mut self) -> SysError {
-        self.raw_unlock()
+        self.lock.lock();
+
+        if self.reader_count == 0 {
+            self.lock.unlock();
+            return Err(libc::EPERM);
+        }
+
+        self.reader_count -= 1;
+        if self.reader_count == 0 {
+            let waiter = self.reader_queue.front();
+            self.lock.unlock();
+            if waiter.is_some() {
+                mutex::thread_set_event(SgxThreadData::from_raw(*waiter.unwrap()).get_tcs());
+            }
+        } else {
+            self.lock.unlock();
+        }
+        Ok(())
     }
 
     unsafe fn write_unlock(&mut self) -> SysError {
-        self.raw_unlock()
-    }
+        let current = rsgx_thread_self();
 
-    unsafe fn raw_unlock(&mut self) -> SysError {
-        self.mutex.lock();
-        {
-            if self.readers_num > 0 {
-                self.readers_num -= 1;
-                if self.readers_num == 0 && self.writers_num > 0 {
-                    self.condvar.broadcast();
-                }
-            } else {
-                if self.writer_thread != thread::rsgx_thread_self() {
-                    self.mutex.unlock();
-                    return Err(libc::EPERM);
-                }
-                self.writers_num -= 1;
-                self.writer_thread = SGX_THREAD_T_NULL;
-                if self.busy > 0 {
-                    self.condvar.broadcast();
-                }
+        self.lock.lock();
+
+        if self.owner != current {
+            self.lock.unlock();
+            return Err(libc::EPERM);
+        }
+
+        self.owner = SGX_THREAD_T_NULL;
+        if !self.reader_queue.is_empty() {
+            let mut tcs_vec: Vec<usize> = Vec::new();
+            for waiter in self.reader_queue.iter() {
+                tcs_vec.push(SgxThreadData::from_raw(*waiter).get_tcs())
+            }
+            self.lock.unlock();
+            mutex::thread_set_multiple_events(tcs_vec.as_slice());
+        } else {
+            let waiter = self.writer_queue.front();
+            self.lock.unlock();
+            if waiter.is_some() {
+                mutex::thread_set_event(SgxThreadData::from_raw(*waiter.unwrap()).get_tcs());
             }
         }
-        self.mutex.unlock();
         Ok(())
     }
 
+    unsafe fn unlock(&mut self) -> SysError {
+        if self.owner == rsgx_thread_self() {
+            self.write_unlock()
+        } else {
+            self.read_unlock()
+        }
+    }
+
     unsafe fn destroy(&mut self) -> SysError {
-        self.mutex.lock();
+        self.lock.lock();
+        let ret = if self.owner != SGX_THREAD_T_NULL
+            || self.reader_count != 0
+            || self.writer_waiting != 0
+            || !self.reader_queue.is_empty()
+            || !self.writer_queue.is_empty()
         {
-            if self.readers_num > 0 ||
-               self.writers_num > 0 ||
-               self.busy > 0 {
-
-                self.spinlock.unlock();
-                return Err(libc::EBUSY);
-            }
-
-            self.condvar.destroy();
-            self.mutex.destroy();
-        }
-        self.spinlock.unlock();
-        Ok(())
+            Err(libc::EBUSY)
+        } else {
+            Ok(())
+        };
+        self.lock.unlock();
+        ret
     }
 }
 
+unsafe impl Send for SgxThreadRwLock {}
+unsafe impl Sync for SgxThreadRwLock {}
+
 /// An OS-based reader-writer lock.
 ///
 /// This structure is entirely unsafe and serves as the lowest layer of a
@@ -254,8 +239,8 @@
 impl SgxThreadRwLock {
     /// Creates a new reader-writer lock for use.
     pub const fn new() -> Self {
-        SgxThreadRwLock { 
-            lock: UnsafeCell::new(SgxThreadRwLockInner::new())
+        SgxThreadRwLock {
+            lock: UnsafeCell::new(SgxThreadRwLockInner::new()),
         }
     }
 
@@ -309,6 +294,12 @@
         rwlock.write_unlock()
     }
 
+    #[inline]
+    pub unsafe fn unlock(&self) -> SysError {
+        let rwlock: &mut SgxThreadRwLockInner = &mut *self.lock.get();
+        rwlock.unlock()
+    }
+
     /// Destroys OS-related resources with this RWLock.
     #[inline]
     pub unsafe fn destroy(&self) -> SysError {
diff --git a/sgx_tunittest/src/lib.rs b/sgx_tunittest/src/lib.rs
index 246c75d..103bc2c 100644
--- a/sgx_tunittest/src/lib.rs
+++ b/sgx_tunittest/src/lib.rs
@@ -69,8 +69,10 @@
 //!
 
 #![cfg_attr(not(target_env = "sgx"), no_std)]
-#![cfg_attr(all(target_env = "sgx", target_vendor = "mesalock"), feature(rustc_private))]
-
+#![cfg_attr(
+    all(target_env = "sgx", target_vendor = "mesalock"),
+    feature(rustc_private)
+)]
 #![feature(const_fn)]
 
 #[cfg(not(target_env = "sgx"))]
@@ -106,12 +108,12 @@
 /// This requires developer to identify the line which triggers panic exactly.
 #[macro_export]
 macro_rules! should_panic {
-    ($fmt:expr) => ({
-        match ::std::panic::catch_unwind(|| { $fmt }).is_err() {
+    ($fmt:expr) => {{
+        match ::std::panic::catch_unwind(|| $fmt).is_err() {
             true => {}
-            false => { ::std::rt::begin_panic($fmt) }
+            false => ::std::rt::begin_panic($fmt),
         }
-    });
+    }};
 }
 
 /// This macro works as test case driver.
@@ -161,7 +163,7 @@
 /// To initiate the test environment, `rsgx_unit_tests!` macro would trigger
 /// `rsgx_unit_test_start` at the very beginning. `rsgx_unit_test_start` inits
 /// the test counter and fail test list, and print the prologue message.
-pub fn rsgx_unit_test_start () {
+pub fn rsgx_unit_test_start() {
     println!("\nstart running tests");
 }
 
@@ -170,17 +172,18 @@
 /// `rsgx_unit_test_end` prints the statistics on test result, including
 /// a list of failed tests and the statistics.
 /// It will return the amount of failed tests. (success == 0)
-pub fn rsgx_unit_test_end(ntestcases : u64, failurecases : Vec<String>) -> usize {
+pub fn rsgx_unit_test_end(ntestcases: u64, failurecases: Vec<String>) -> usize {
     let ntotal = ntestcases as usize;
-    let nsucc  = ntestcases as usize - failurecases.len();
+    let nsucc = ntestcases as usize - failurecases.len();
 
-    if failurecases.len() != 0{
+    if failurecases.len() != 0 {
         print!("\nfailures: ");
-        println!("    {}",
-                 failurecases.iter()
-                          .fold(
-                              String::new(),
-                              |s, per| s + "\n    " + per));
+        println!(
+            "    {}",
+            failurecases
+                .iter()
+                .fold(String::new(), |s, per| s + "\n    " + per)
+        );
     }
 
     if ntotal == nsucc {
@@ -189,7 +192,12 @@
         print!("\ntest result \x1B[1;31mFAILED\x1B[0m. ");
     }
 
-    println!("{} tested, {} passed, {} failed", ntotal, nsucc, ntotal - nsucc);
+    println!(
+        "{} tested, {} passed, {} failed",
+        ntotal,
+        nsucc,
+        ntotal - nsucc
+    );
     failurecases.len()
 }
 
@@ -200,23 +208,22 @@
 /// and on test fails, it records the failed test.
 /// Required test function must be `Fn()`, taking nothing as input and returns
 /// nothing.
-pub fn rsgx_unit_test<F, R>(ncases: &mut u64, failurecases: &mut Vec<String>, f:F, name: &str)
-    where F: FnOnce() -> R + std::panic::UnwindSafe {
+pub fn rsgx_unit_test<F, R>(ncases: &mut u64, failurecases: &mut Vec<String>, f: F, name: &str)
+where
+    F: FnOnce() -> R + std::panic::UnwindSafe,
+{
     *ncases = *ncases + 1;
-    match std::panic::catch_unwind (|| { f(); } ).is_ok() {
+    match std::panic::catch_unwind(|| {
+        f();
+    })
+    .is_ok()
+    {
         true => {
-            println!("{} {} ... {}!",
-                    "testing",
-                    name,
-                    "\x1B[1;32mok\x1B[0m");
+            println!("{} {} ... {}!", "testing", name, "\x1B[1;32mok\x1B[0m");
         }
         false => {
-            println!("{} {} ... {}!",
-                    "testing",
-                    name,
-                    "\x1B[1;31mfailed\x1B[0m");
+            println!("{} {} ... {}!", "testing", name, "\x1B[1;31mfailed\x1B[0m");
             failurecases.push(String::from(name));
         }
     }
 }
-
diff --git a/sgx_types/src/cpu_feature.rs b/sgx_types/src/cpu_feature.rs
index 5a29324..da553f6 100644
--- a/sgx_types/src/cpu_feature.rs
+++ b/sgx_types/src/cpu_feature.rs
@@ -20,248 +20,243 @@
 //
 // The processor is a generic IA32 CPU
 //
-pub const CPU_FEATURE_GENERIC_IA32          :uint64_t = 0x00000001;
+pub const CPU_FEATURE_GENERIC_IA32: uint64_t = 0x0000_0001;
 
 //
 // Floating point unit is on-chip.
 //
-pub const CPU_FEATURE_FPU                   :uint64_t = 0x00000002;
+pub const CPU_FEATURE_FPU: uint64_t = 0x0000_0002;
 
 //
 // Conditional mov instructions are supported.
 //
-pub const CPU_FEATURE_CMOV                  :uint64_t = 0x00000004;
+pub const CPU_FEATURE_CMOV: uint64_t = 0x0000_0004;
 
 //
 // The processor supports the MMX technology instruction set extensions
 // to Intel Architecture.
 //
-pub const CPU_FEATURE_MMX                   :uint64_t = 0x00000008;
+pub const CPU_FEATURE_MMX: uint64_t = 0x0000_0008;
 
 //
 // The FXSAVE and FXRSTOR instructions are supported for fast
 // save and restore of the floating point context.
 //
-pub const CPU_FEATURE_FXSAVE                :uint64_t = 0x00000010;
+pub const CPU_FEATURE_FXSAVE: uint64_t = 0x0000_0010;
 
 //
 // Indicates the processor supports the Streaming SIMD Extensions Instructions.
 //
-pub const CPU_FEATURE_SSE                   :uint64_t = 0x00000020;
+pub const CPU_FEATURE_SSE: uint64_t = 0x0000_0020;
 
 //
 // Indicates the processor supports the Streaming SIMD
 // Extensions 2 Instructions.
 //
-pub const CPU_FEATURE_SSE2                  :uint64_t = 0x00000040;
+pub const CPU_FEATURE_SSE2: uint64_t = 0x0000_0040;
 
 //
 // Indicates the processor supports the Streaming SIMD
 // Extensions 3 Instructions. (PNI)
 //
-pub const CPU_FEATURE_SSE3                  :uint64_t = 0x00000080;
+pub const CPU_FEATURE_SSE3: uint64_t = 0x0000_0080;
 
 //
 // The processor supports the Supplemental Streaming SIMD Extensions 3
 // instructions. (MNI)
 //
-pub const CPU_FEATURE_SSSE3                 :uint64_t = 0x00000100;
+pub const CPU_FEATURE_SSSE3: uint64_t = 0x0000_0100;
 
 //
 // The processor supports the Streaming SIMD Extensions 4.1 instructions.(SNI)
 //
-pub const CPU_FEATURE_SSE4_1                :uint64_t = 0x00000200;
+pub const CPU_FEATURE_SSE4_1: uint64_t = 0x0000_0200;
 
 //
 // The processor supports the Streaming SIMD Extensions 4.1 instructions.
 // (NNI + STTNI)
 //
-pub const CPU_FEATURE_SSE4_2                :uint64_t = 0x00000400;
+pub const CPU_FEATURE_SSE4_2: uint64_t = 0x0000_0400;
 
 //
 // The processor supports MOVBE instruction.
 //
-pub const CPU_FEATURE_MOVBE                 :uint64_t = 0x00000800;
-
+pub const CPU_FEATURE_MOVBE: uint64_t = 0x0000_0800;
 
 //
 // The processor supports POPCNT instruction.
 //
-pub const CPU_FEATURE_POPCNT                :uint64_t = 0x00001000;
-
+pub const CPU_FEATURE_POPCNT: uint64_t = 0x0000_1000;
 
 //
 // The processor supports PCLMULQDQ instruction.
 //
-pub const CPU_FEATURE_PCLMULQDQ             :uint64_t = 0x00002000;
+pub const CPU_FEATURE_PCLMULQDQ: uint64_t = 0x0000_2000;
 
 //
 // The processor supports instruction extension for encryption.
 //
-pub const CPU_FEATURE_AES                   :uint64_t = 0x00004000;
+pub const CPU_FEATURE_AES: uint64_t = 0x0000_4000;
 
 //
 // The processor supports 16-bit floating-point conversions instructions.
 //
-pub const CPU_FEATURE_F16C                  :uint64_t = 0x00008000;
+pub const CPU_FEATURE_F16C: uint64_t = 0x0000_8000;
 
 //
 // The processor supports AVX instruction extension.
 //
-pub const CPU_FEATURE_AVX                   :uint64_t = 0x00010000;
+pub const CPU_FEATURE_AVX: uint64_t = 0x0001_0000;
 
 //
 // The processor supports RDRND (read random value) instruction.
 //
-pub const CPU_FEATURE_RDRND                 :uint64_t = 0x00020000;
+pub const CPU_FEATURE_RDRND: uint64_t = 0x0002_0000;
 
 //
 // The processor supports FMA instructions.
 //
-pub const CPU_FEATURE_FMA                   :uint64_t = 0x00040000;
+pub const CPU_FEATURE_FMA: uint64_t = 0x0004_0000;
 
 //
-// The processor supports two groups of advanced bit manipulation extensions. - Haswell introduced, AVX2 related 
+// The processor supports two groups of advanced bit manipulation extensions. - Haswell introduced, AVX2 related
 //
-pub const CPU_FEATURE_BMI                   :uint64_t = 0x00080000;
+pub const CPU_FEATURE_BMI: uint64_t = 0x0008_0000;
 
 //
 // The processor supports LZCNT instruction (counts the number of leading zero
 // bits). - Haswell introduced
 //
-pub const CPU_FEATURE_LZCNT                 :uint64_t = 0x00100000;
+pub const CPU_FEATURE_LZCNT: uint64_t = 0x0010_0000;
 
 //
 // The processor supports HLE extension (hardware lock elision). - Haswell introduced
 //
-pub const CPU_FEATURE_HLE                   :uint64_t = 0x00200000;
+pub const CPU_FEATURE_HLE: uint64_t = 0x0020_0000;
 
 //
 // The processor supports RTM extension (restricted transactional memory) - Haswell AVX2 related.
 //
-pub const CPU_FEATURE_RTM                   :uint64_t = 0x00400000;
+pub const CPU_FEATURE_RTM: uint64_t = 0x0040_0000;
 
 //
 // The processor supports AVX2 instruction extension.
 //
-pub const CPU_FEATURE_AVX2                  :uint64_t = 0x00800000;
+pub const CPU_FEATURE_AVX2: uint64_t = 0x0080_0000;
 
 //
-// The processor supports AVX512 dword/qword instruction extension. 
+// The processor supports AVX512 dword/qword instruction extension.
 //
-pub const CPU_FEATURE_AVX512DQ              :uint64_t = 0x01000000;
+pub const CPU_FEATURE_AVX512DQ: uint64_t = 0x0100_0000;
 
 //
 // The processor supports the PTWRITE instruction.
 //
-pub const CPU_FEATURE_PTWRITE               :uint64_t = 0x02000000;
+pub const CPU_FEATURE_PTWRITE: uint64_t = 0x0200_0000;
 
 //
 // KNC instruction set
 //
-pub const CPU_FEATURE_KNCNI                 :uint64_t = 0x04000000;
+pub const CPU_FEATURE_KNCNI: uint64_t = 0x0400_0000;
 
 //
 // AVX512 foundation instructions
 //
-pub const CPU_FEATURE_AVX512F               :uint64_t = 0x08000000;
+pub const CPU_FEATURE_AVX512F: uint64_t = 0x0800_0000;
 
 //
 // The processor supports uint add with OF or CF flags (ADOX, ADCX)
 //
-pub const CPU_FEATURE_ADX                   :uint64_t = 0x10000000;
+pub const CPU_FEATURE_ADX: uint64_t = 0x1000_0000;
 
 //
 // The processor supports RDSEED instruction.
 //
-pub const CPU_FEATURE_RDSEED                :uint64_t = 0x20000000;
+pub const CPU_FEATURE_RDSEED: uint64_t = 0x2000_0000;
 
 // AVX512IFMA52: vpmadd52huq and vpmadd52luq
-pub const CPU_FEATURE_AVX512IFMA52          :uint64_t = 0x40000000;
+pub const CPU_FEATURE_AVX512IFMA52: uint64_t = 0x4000_0000;
 
 //
 // The processor is a full inorder (Silverthorne) processor
-// 
-pub const CPU_FEATURE_F_INORDER             :uint64_t = 0x80000000;
-
+//
+pub const CPU_FEATURE_F_INORDER: uint64_t = 0x8000_0000;
 
 // AVX512 exponential and reciprocal instructions
-pub const CPU_FEATURE_AVX512ER              :uint64_t = 0x100000000;
+pub const CPU_FEATURE_AVX512ER: uint64_t = 0x0001_0000_0000;
 
 // AVX512 prefetch instructions
-pub const CPU_FEATURE_AVX512PF              :uint64_t = 0x200000000;
+pub const CPU_FEATURE_AVX512PF: uint64_t = 0x0002_0000_0000;
 
 // AVX-512 conflict detection instructions
-pub const CPU_FEATURE_AVX512CD              :uint64_t = 0x400000000;
+pub const CPU_FEATURE_AVX512CD: uint64_t = 0x0004_0000_0000;
 
 // Secure Hash Algorithm instructions (SHA)
-pub const CPU_FEATURE_SHA                   :uint64_t = 0x800000000;
+pub const CPU_FEATURE_SHA: uint64_t = 0x0008_0000_0000;
 
 // Memory Protection Extensions (MPX)
-pub const CPU_FEATURE_MPX                   :uint64_t = 0x1000000000;
+pub const CPU_FEATURE_MPX: uint64_t = 0x0010_0000_0000;
 
 // AVX512BW - AVX512 byte/word vector instruction set
-pub const CPU_FEATURE_AVX512BW              :uint64_t = 0x2000000000;
+pub const CPU_FEATURE_AVX512BW: uint64_t = 0x0020_0000_0000;
 
 // AVX512VL - 128/256-bit vector support of AVX512 instructions
-pub const CPU_FEATURE_AVX512VL              :uint64_t = 0x4000000000;
+pub const CPU_FEATURE_AVX512VL: uint64_t = 0x0040_0000_0000;
 
 // AVX512VBMI:  vpermb, vpermi2b, vpermt2b and vpmultishiftqb
-pub const CPU_FEATURE_AVX512VBMI            :uint64_t = 0x8000000000;
+pub const CPU_FEATURE_AVX512VBMI: uint64_t = 0x0080_0000_0000;
 
 // AVX512_4FMAPS: Single Precision FMA for multivector(4 vector) operand.
-pub const CPU_FEATURE_AVX512_4FMAPS         :uint64_t = 0x10000000000;
+pub const CPU_FEATURE_AVX512_4FMAPS: uint64_t = 0x0100_0000_0000;
 
 // AVX512_4VNNIW: Vector Neural Network Instructions for multivector(4 vector) operand with word elements.
-pub const CPU_FEATURE_AVX512_4VNNIW         :uint64_t = 0x20000000000;
+pub const CPU_FEATURE_AVX512_4VNNIW: uint64_t = 0x0200_0000_0000;
 
 // AVX512_VPOPCNTDQ: 512-bit vector POPCNT instruction.
-pub const CPU_FEATURE_AVX512_VPOPCNTDQ      :uint64_t = 0x40000000000;
+pub const CPU_FEATURE_AVX512_VPOPCNTDQ: uint64_t = 0x0400_0000_0000;
 
 // AVX512_BITALG: vector bit algebra in AVX512
-pub const CPU_FEATURE_AVX512_BITALG         :uint64_t = 0x80000000000;
+pub const CPU_FEATURE_AVX512_BITALG: uint64_t = 0x0800_0000_0000;
 
 // AVX512_VBMI2: additional byte, word, dword and qword capabilities
-pub const CPU_FEATURE_AVX512_VBMI2          :uint64_t = 0x100000000000;
+pub const CPU_FEATURE_AVX512_VBMI2: uint64_t = 0x1000_0000_0000;
 
 // GFNI: Galois Field New Instructions.
-pub const CPU_FEATURE_GFNI                  :uint64_t = 0x200000000000;
+pub const CPU_FEATURE_GFNI: uint64_t = 0x2000_0000_0000;
 
 // VAES: vector AES instructions
-pub const CPU_FEATURE_VAES                  :uint64_t = 0x400000000000;
+pub const CPU_FEATURE_VAES: uint64_t = 0x4000_0000_0000;
 
 // VPCLMULQDQ: Vector CLMUL instruction set.
-pub const CPU_FEATURE_VPCLMULQDQ            :uint64_t = 0x800000000000;
+pub const CPU_FEATURE_VPCLMULQDQ: uint64_t = 0x8000_0000_0000;
 
 // AVX512_VNNI: vector Neural Network Instructions.
-pub const CPU_FEATURE_AVX512_VNNI           :uint64_t = 0x1000000000000;
+pub const CPU_FEATURE_AVX512_VNNI: uint64_t = 0x0001_0000_0000_0000;
 
 // CLWB: Cache Line Write Back
-pub const CPU_FEATURE_CLWB                  :uint64_t = 0x2000000000000;
+pub const CPU_FEATURE_CLWB: uint64_t = 0x0002_0000_0000_0000;
 
 // RDPID: Read Processor ID.
-pub const CPU_FEATURE_RDPID                 :uint64_t = 0x4000000000000;
+pub const CPU_FEATURE_RDPID: uint64_t = 0x0004_0000_0000_0000;
 
 // IBT - Indirect branch tracking
-pub const CPU_FEATURE_IBT                   :uint64_t = 0x8000000000000;
+pub const CPU_FEATURE_IBT: uint64_t = 0x0008_0000_0000_0000;
 
 // Shadow stack
-pub const CPU_FEATURE_SHSTK                 :uint64_t = 0x10000000000000;
+pub const CPU_FEATURE_SHSTK: uint64_t = 0x0010_0000_0000_0000;
 
 // Intel Software Guard Extensions
-pub const CPU_FEATURE_SGX                   :uint64_t = 0x20000000000000;
+pub const CPU_FEATURE_SGX: uint64_t = 0x0020_0000_0000_0000;
 
 // Write back and do not invalidate cache
-pub const CPU_FEATURE_WBNOINVD              :uint64_t = 0x40000000000000;
+pub const CPU_FEATURE_WBNOINVD: uint64_t = 0x0040_0000_0000_0000;
 
 // Platform configuration - 1 << 55
-pub const CPU_FEATURE_PCONFIG               :uint64_t = 0x80000000000000;
-
+pub const CPU_FEATURE_PCONFIG: uint64_t = 0x0080_0000_0000_0000;
 
 // Reserved feature bits
-pub const RESERVED_CPU_FEATURE_BIT          :uint64_t = !(0x100000000000000 - 1);
+pub const RESERVED_CPU_FEATURE_BIT: uint64_t = !(0x0100_0000_0000_0000 - 1);
 
 // Incompatible bits which we should unset in trts
-pub const INCOMPAT_FEATURE_BIT              :uint64_t = (1 << 11) | (1 << 12) | (1 << 25) | (1 << 26) | (1 << 27) | (1 << 28);
-
-
+pub const INCOMPAT_FEATURE_BIT: uint64_t =
+    (1 << 11) | (1 << 12) | (1 << 25) | (1 << 26) | (1 << 27) | (1 << 28);
diff --git a/sgx_types/src/error.rs b/sgx_types/src/error.rs
index b951836..fda3c96 100644
--- a/sgx_types/src/error.rs
+++ b/sgx_types/src/error.rs
@@ -15,9 +15,9 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use core::result;
-use core::fmt;
 use crate::int32_t;
+use core::fmt;
+use core::result;
 
 //
 // sgx_error.h
@@ -298,9 +298,9 @@
             sgx_status_t::SGX_ERROR_WASM_BUFFER_TOO_SHORT => "SGX_ERROR_WASM_BUFFER_TOO_SHORT",
             sgx_status_t::SGX_ERROR_WASM_INTERPRETER_ERROR => "SGX_ERROR_WASM_INTERPRETER_ERROR",
             sgx_status_t::SGX_ERROR_WASM_LOAD_MODULE_ERROR => "SGX_ERROR_WASM_LOAD_MODULE_ERROR",
-            sgx_status_t::SGX_ERROR_WASM_TRY_LOAD_ERROR    => "SGX_ERROR_WASM_TRY_LOAD_ERROR",
-            sgx_status_t::SGX_ERROR_WASM_REGISTER_ERROR    => "SGX_ERROR_WASM_REGISTER_ERROR",
-            sgx_status_t::SGX_ERROR_FAAS_BUFFER_TOO_SHORT   => "SGX_ERROR_FAAS_BUFFER_TOO_SHORT",
+            sgx_status_t::SGX_ERROR_WASM_TRY_LOAD_ERROR => "SGX_ERROR_WASM_TRY_LOAD_ERROR",
+            sgx_status_t::SGX_ERROR_WASM_REGISTER_ERROR => "SGX_ERROR_WASM_REGISTER_ERROR",
+            sgx_status_t::SGX_ERROR_FAAS_BUFFER_TOO_SHORT => "SGX_ERROR_FAAS_BUFFER_TOO_SHORT",
             sgx_status_t::SGX_ERROR_FAAS_INTERNAL_ERROR => "SGX_ERROR_FAAS_INTERNAL_ERROR",
         }
     }
@@ -312,7 +312,6 @@
     }
 }
 
-
 impl_enum! {
     #[repr(u32)]
     #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
@@ -365,7 +364,6 @@
     }
 }
 
-
 impl_enum! {
     #[repr(u32)]
     #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
@@ -443,6 +441,9 @@
         SGX_QL_PERSISTENT_STORAGE_ERROR                     = 0x0000_E045,
         SGX_QL_ERROR_MESSAGE_PARSING_ERROR                  = 0x0000_E046,
         SGX_QL_PLATFORM_UNKNOWN                             = 0x0000_E047,
+        SGX_QL_QVEIDENTITY_MISMATCH                         = 0x0000_E050,
+        SGX_QL_QVE_OUT_OF_DATE                              = 0x0000_E051,
+        SGX_QL_PSW_NOT_AVAILABLE                            = 0x0000_E052,
         SGX_QL_ERROR_MAX                                    = 0x0000_E0FF,
     }
 }
@@ -522,6 +523,9 @@
             sgx_quote3_error_t::SGX_QL_PERSISTENT_STORAGE_ERROR => "Error storing the retrieved cached data in persistent memory.",
             sgx_quote3_error_t::SGX_QL_ERROR_MESSAGE_PARSING_ERROR => "Message parsing error.",
             sgx_quote3_error_t::SGX_QL_PLATFORM_UNKNOWN => "Platform was not found in the cache",
+            sgx_quote3_error_t::SGX_QL_QVEIDENTITY_MISMATCH => "QvE Identity is NOT match to Intel signed QvE identity.",
+            sgx_quote3_error_t::SGX_QL_QVE_OUT_OF_DATE => "QvE ISVSVN is smaller then the ISVSVN threshold.",
+            sgx_quote3_error_t::SGX_QL_PSW_NOT_AVAILABLE => "SGX PSW library cannot be loaded, could be due to file I/O error.",
             sgx_quote3_error_t::SGX_QL_ERROR_MAX => "Indicate max error to allow better translation.",
         }
     }
@@ -600,6 +604,9 @@
             sgx_quote3_error_t::SGX_QL_PERSISTENT_STORAGE_ERROR => "SGX_QL_PERSISTENT_STORAGE_ERROR",
             sgx_quote3_error_t::SGX_QL_ERROR_MESSAGE_PARSING_ERROR => "SGX_QL_ERROR_MESSAGE_PARSING_ERROR",
             sgx_quote3_error_t::SGX_QL_PLATFORM_UNKNOWN => "SGX_QL_PLATFORM_UNKNOWN",
+            sgx_quote3_error_t::SGX_QL_QVEIDENTITY_MISMATCH => "SGX_QL_QVEIDENTITY_MISMATCH",
+            sgx_quote3_error_t::SGX_QL_QVE_OUT_OF_DATE => "SGX_QL_QVE_OUT_OF_DATE",
+            sgx_quote3_error_t::SGX_QL_PSW_NOT_AVAILABLE => "SGX_QL_PSW_NOT_AVAILABLE",
             sgx_quote3_error_t::SGX_QL_ERROR_MAX => "SGX_QL_ERROR_MAX",
         }
     }
@@ -611,7 +618,6 @@
     }
 }
 
-
 impl_enum! {
     #[repr(u32)]
     #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
@@ -691,6 +697,62 @@
     }
 }
 
+impl_enum! {
+    #[repr(u32)]
+    #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
+    pub enum sgx_ql_qv_result_t {
+        SGX_QL_QV_RESULT_OK                                 = 0x0000_0000,
+        // SGX_QL_QV_RESULT_MIN                             = 0x0000_A001,
+        SGX_QL_QV_RESULT_CONFIG_NEEDED                      = 0x0000_A001,
+        SGX_QL_QV_RESULT_OUT_OF_DATE                        = 0x0000_A002,
+        SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED          = 0x0000_A003,
+        SGX_QL_QV_RESULT_INVALID_SIGNATURE                  = 0x0000_A004,
+        SGX_QL_QV_RESULT_REVOKED                            = 0x0000_A005,
+        SGX_QL_QV_RESULT_UNSPECIFIED                        = 0x0000_A006,
+        SGX_QL_QV_RESULT_SW_HARDENING_NEEDED                = 0x0000_A007,
+        SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED     = 0x0000_A008,
+        SGX_QL_QV_RESULT_MAX                                = 0x0000_A0FF,
+    }
+}
+
+impl sgx_ql_qv_result_t {
+    pub fn __description(&self) -> &str {
+        match *self {
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OK => "The Quote verification passed and is at the latest TCB level.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_CONFIG_NEEDED => "The Quote verification passed and the platform is patched to the latest TCB level but additional configuration of the SGX platform may be needed.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OUT_OF_DATE => "The Quote is good but TCB level of the platform is out of date, The platform needs patching to be at the latest TCB level.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED => "The Quote is good but the TCB level of the platform is out of date and additional configuration of the SGX Platform at its current patching level may be needed. The platform needs patching to be at the latest TCB level.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_INVALID_SIGNATURE => "The signature over the application report is invalid.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_REVOKED => "The attestation key or platform has been revoked.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_UNSPECIFIED => "The Quote verification failed due to an error in one of the input.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_SW_HARDENING_NEEDED => "The TCB level of the platform is up to date, but SGX SW Hardening is needed.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED => "The TCB level of the platform is up to date, but additional configuration of the platform at its current patching level may be needed. Moreove, SGX SW Hardening is also needed.",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_MAX => "Indicate max result to allow better translation.",
+        }
+    }
+
+    pub fn as_str(&self) -> &str {
+        match *self {
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OK => "SGX_QL_QV_RESULT_OK",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_CONFIG_NEEDED => "SGX_QL_QV_RESULT_CONFIG_NEEDED",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OUT_OF_DATE => "SGX_QL_QV_RESULT_OUT_OF_DATE",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED => "SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_INVALID_SIGNATURE => "SGX_QL_QV_RESULT_INVALID_SIGNATURE",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_REVOKED => "SGX_QL_QV_RESULT_REVOKED",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_UNSPECIFIED => "SGX_QL_QV_RESULT_UNSPECIFIED",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_SW_HARDENING_NEEDED => "SGX_QL_QV_RESULT_SW_HARDENING_NEEDED",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED => "SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED",
+            sgx_ql_qv_result_t::SGX_QL_QV_RESULT_MAX => "SGX_QL_QV_RESULT_MAX",
+        }
+    }
+}
+
+impl fmt::Display for sgx_ql_qv_result_t {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        write!(f, "{}", self.as_str())
+    }
+}
+
 pub type sys_error_t = int32_t;
 
 pub type SgxResult<T> = result::Result<T, sgx_status_t>;
diff --git a/sgx_types/src/function.rs b/sgx_types/src/function.rs
index 3c2db3a..b74afd7 100644
--- a/sgx_types/src/function.rs
+++ b/sgx_types/src/function.rs
@@ -53,6 +53,17 @@
     pub fn sgx_thread_self() -> sgx_thread_t;
     pub fn sgx_thread_equal(a: sgx_thread_t, b: sgx_thread_t) -> int32_t;
 
+    /* intel sgx sdk 2.11 */
+    pub fn sgx_thread_rwlock_init(rwlock: *mut sgx_thread_rwlock_t, unused: *const sgx_thread_rwlockattr_t) -> int32_t;
+    pub fn sgx_thread_rwlock_destroy(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+    pub fn sgx_thread_rwlock_rdlock(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+    pub fn sgx_thread_rwlock_tryrdlock(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+    pub fn sgx_thread_rwlock_wrlock(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+    pub fn sgx_thread_rwlock_trywrlock(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+    pub fn sgx_thread_rwlock_rdunlock(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+    pub fn sgx_thread_rwlock_wrunlock(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+    pub fn sgx_thread_rwlock_unlock(rwlock: *mut sgx_thread_rwlock_t) -> int32_t;
+
     /* intel sgx sdk 2.8 */
     //
     // sgx_rsrv_mem_mngr.h
@@ -60,6 +71,10 @@
     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: int32_t) -> sgx_status_t;
+
+    /* intel sgx sdk 2.11 */
+    pub fn sgx_get_rsrv_mem_info(start_addr: *mut *mut c_void, max_size: *mut size_t) -> sgx_status_t;
+    pub fn sgx_alloc_rsrv_mem_ex(desired_addr: *const c_void, length: size_t) -> *mut c_void;
 }
 
 //#[link(name = "sgx_tservice")]
@@ -257,8 +272,8 @@
     pub fn sgx_ecc256_create_key_pair(p_private: *mut sgx_ec256_private_t, p_public: *mut sgx_ec256_public_t, ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t;
     pub fn sgx_ecc256_check_point(p_point: *const sgx_ec256_public_t, ecc_handle: sgx_ecc_state_handle_t, p_valid: *mut int32_t) -> sgx_status_t;
 
-    pub fn sgx_ecc256_compute_shared_dhkey(p_private_b: *mut sgx_ec256_private_t,
-                                           p_public_ga: *mut sgx_ec256_public_t,
+    pub fn sgx_ecc256_compute_shared_dhkey(p_private_b: *const sgx_ec256_private_t,
+                                           p_public_ga: *const sgx_ec256_public_t,
                                            p_shared_key: *mut sgx_ec256_dh_shared_t,
                                            ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t;
     /* intel sgx sdk 1.8 */
@@ -271,21 +286,21 @@
 
     pub fn sgx_ecdsa_sign(p_data: *const uint8_t,
                           data_size: uint32_t,
-                          p_private: *mut sgx_ec256_private_t,
+                          p_private: *const sgx_ec256_private_t,
                           p_signature: *mut sgx_ec256_signature_t,
                           ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t;
 
     pub fn sgx_ecdsa_verify(p_data: *const uint8_t,
                             data_size:  uint32_t,
                             p_public: *const sgx_ec256_public_t,
-                            p_signature: *mut sgx_ec256_signature_t,
+                            p_signature: *const sgx_ec256_signature_t,
                             p_result: *mut uint8_t,
                             ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t;
 
     /* intel sgx sdk 2.4 */
     pub fn sgx_ecdsa_verify_hash(hash: *const uint8_t,
                                  p_public: *const sgx_ec256_public_t,
-                                 p_signature: *mut sgx_ec256_signature_t,
+                                 p_signature: *const sgx_ec256_signature_t,
                                  p_result: *mut uint8_t,
                                  ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t;
 
@@ -789,3 +804,20 @@
     /* intel DCAP 1.6 */
     pub fn sgx_qv_set_path(path_type: sgx_qv_path_type_t, p_path: *const char) -> sgx_quote3_error_t;
 }
+
+/* intel DCAP 1.7 */
+//#[link(name = "sgx_dcap_tvl")]
+extern "C" {
+    //
+    // sgx_dcap_tvl.h
+    //
+    pub fn sgx_tvl_verify_qve_report_and_identity(p_quote: *const uint8_t,
+                                                  quote_size: uint32_t,
+                                                  p_qve_report_info: *const sgx_ql_qe_report_info_t,
+                                                  expiration_check_date: time_t,
+                                                  collateral_expiration_status: uint32_t,
+                                                  quote_verification_result: sgx_ql_qv_result_t,
+                                                  p_supplemental_data: *const uint8_t,
+                                                  supplemental_data_size: uint32_t,
+                                                  qve_isvsvn_threshold: sgx_isv_svn_t) -> sgx_quote3_error_t;
+}
diff --git a/sgx_types/src/lib.rs b/sgx_types/src/lib.rs
index 8db5b8f..3f392cd 100644
--- a/sgx_types/src/lib.rs
+++ b/sgx_types/src/lib.rs
@@ -16,7 +16,6 @@
 // under the License..
 
 #![no_std]
-
 #![allow(non_camel_case_types)]
 #![allow(non_snake_case)]
 #![allow(improper_ctypes)]
@@ -75,6 +74,6 @@
 mod function;
 pub use self::function::*;
 
+pub mod cpu_feature;
 pub mod marker;
 pub mod metadata;
-pub mod cpu_feature;
diff --git a/sgx_types/src/macros.rs b/sgx_types/src/macros.rs
index 5857629..b1f8523 100644
--- a/sgx_types/src/macros.rs
+++ b/sgx_types/src/macros.rs
@@ -15,13 +15,13 @@
 // specific language governing permissions and limitations
 // under the License..
 
-pub use core::clone::Clone;
-pub use core::marker::Copy;
-pub use core::default::Default;
-pub use core::ptr;
-pub use core::mem::transmute;
-pub use core::mem::size_of;
 pub use crate::marker::ContiguousMemory;
+pub use core::clone::Clone;
+pub use core::default::Default;
+pub use core::marker::Copy;
+pub use core::mem::size_of;
+pub use core::mem::transmute;
+pub use core::ptr;
 
 #[macro_export]
 macro_rules! cfg_if {
@@ -81,7 +81,9 @@
 
 #[macro_export]
 macro_rules! __item {
-    ($i:item) => ($i)
+    ($i:item) => {
+        $i
+    };
 }
 
 macro_rules! impl_copy_clone{
@@ -204,25 +206,35 @@
 
 #[macro_export]
 macro_rules! meta_data_make_version {
-    ($major:ident, $minor:ident) => ( ($major as u64) << 32 | $minor as u64 )
+    ($major:ident, $minor:ident) => {
+        ($major as u64) << 32 | $minor as u64
+    };
 }
 
 #[macro_export]
 macro_rules! major_version_of_metadata {
-    ($version:ident) => ( ($version as u64) >> 32 )
+    ($version:ident) => {
+        ($version as u64) >> 32
+    };
 }
 
 #[macro_export]
 macro_rules! minor_version_of_metadata {
-    ($version:ident) => ( ($version as u64) & 0x0000_0000_FFFF_FFFF )
+    ($version:ident) => {
+        ($version as u64) & 0x0000_0000_FFFF_FFFF
+    };
 }
 
 #[macro_export]
 macro_rules! group_id {
-    ($gid:expr) => ( (GROUP_FLAG | $gid) )
+    ($gid:expr) => {
+        (GROUP_FLAG | $gid)
+    };
 }
 
 #[macro_export]
 macro_rules! is_group_id {
-    ($gid:expr) => ( (($gid & GROUP_FLAG) != 0) )
+    ($gid:expr) => {
+        (($gid & GROUP_FLAG) != 0)
+    };
 }
diff --git a/sgx_types/src/marker.rs b/sgx_types/src/marker.rs
index 3003506..118b09c 100644
--- a/sgx_types/src/marker.rs
+++ b/sgx_types/src/marker.rs
@@ -1,4 +1,3 @@
-
 // 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
@@ -50,13 +49,12 @@
 
 /// Trait implemented for types that can be compared for equality using their bytewise representation
 /// A type can implement BytewiseEquality if all of its components implement BytewiseEquality.
-pub trait BytewiseEquality { }
-
+pub trait BytewiseEquality {}
 
 impl_marker_for!(BytewiseEquality,
                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
 
-impl<T: BytewiseEquality> BytewiseEquality for [T] { }
+impl<T: BytewiseEquality> BytewiseEquality for [T] {}
 
 impl_marker_for_array! {BytewiseEquality,
      0  1  2  3  4  5  6  7  8  9
@@ -75,13 +73,12 @@
 /// a contiguous area of memory inside the enclave. Developer needs to
 /// implement this trait as a marker for the data structure he/she wants
 /// to feed into SGX apis.
-pub unsafe trait ContiguousMemory { }
+pub unsafe trait ContiguousMemory {}
 
 impl_unsafe_marker_for!(ContiguousMemory,
                  u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
 
-unsafe impl<T: ContiguousMemory> ContiguousMemory for [T] { }
-
+unsafe impl<T: ContiguousMemory> ContiguousMemory for [T] {}
 
 impl_unsafe_marker_for_array! {ContiguousMemory,
      0  1  2  3  4  5  6  7  8  9
diff --git a/sgx_types/src/metadata.rs b/sgx_types/src/metadata.rs
index f93be06..9ae8078 100644
--- a/sgx_types/src/metadata.rs
+++ b/sgx_types/src/metadata.rs
@@ -2,121 +2,121 @@
 use core::default::Default;
 
 /* arch .h*/
-pub const SE_PAGE_SIZE      :usize =  0x1000;
-pub const SE_KEY_SIZE       :usize =  384;
-pub const SE_EXPONENT_SIZE  :usize =  4;
+pub const SE_PAGE_SIZE: usize = 0x1000;
+pub const SE_KEY_SIZE: usize = 384;
+pub const SE_EXPONENT_SIZE: usize = 4;
 
 /* arch.h */
 #[repr(C, packed)]
 pub struct tcs_t {
-    pub reserved0      :u64,
-    pub flags          :u64,
-    pub ossa           :u64,
-    pub cssa           :u32,
-    pub nssa           :u32,
-    pub oentry         :u64,
-    pub reserved1      :u64,
-    pub ofs_base       :u64,
-    pub ogs_base       :u64,
-    pub ofs_limit      :u32,
-    pub ogs_limit      :u32,
-    pub reserved       :[u8; 4024],
+    pub reserved0: u64,
+    pub flags: u64,
+    pub ossa: u64,
+    pub cssa: u32,
+    pub nssa: u32,
+    pub oentry: u64,
+    pub reserved1: u64,
+    pub ofs_base: u64,
+    pub ogs_base: u64,
+    pub ofs_limit: u32,
+    pub ogs_limit: u32,
+    pub reserved: [u8; 4024],
 }
 
 /* arch.h */
 #[repr(C, packed)]
 pub struct css_header_t {
-    pub header          :[u8; 12],
-    pub css_type        :u32,  // type
-    pub module_vendor   :u32,
-    pub date            :u32,
-    pub header2         :[u8; 16],
-    pub hw_version      :u32,
-    pub reserved        :[u8; 84],
+    pub header: [u8; 12],
+    pub css_type: u32, // type
+    pub module_vendor: u32,
+    pub date: u32,
+    pub header2: [u8; 16],
+    pub hw_version: u32,
+    pub reserved: [u8; 84],
 }
 
 #[repr(C, packed)]
 pub struct css_key_t {
-    pub modulus         :[u8; SE_KEY_SIZE],
-    pub exponent        :[u8; SE_EXPONENT_SIZE],
-    pub signature       :[u8; SE_KEY_SIZE],
+    pub modulus: [u8; SE_KEY_SIZE],
+    pub exponent: [u8; SE_EXPONENT_SIZE],
+    pub signature: [u8; SE_KEY_SIZE],
 }
 
 #[repr(C, packed)]
 pub struct css_body_t {
-    pub misc_select     :sgx_misc_select_t,
-    pub misc_mask       :sgx_misc_select_t,
-    pub reserved        :[u8; 4],
-    pub isv_family_id   :sgx_isvfamily_id_t,
-    pub attributes      :sgx_attributes_t,
-    pub attribute_mask  :sgx_attributes_t,
-    pub enclave_hash    :sgx_measurement_t,
-    pub reserved2       :[u8; 16],
-    pub isvext_prod_id  :sgx_isvext_prod_id_t,
-    pub isv_prod_id     :u16,
-    pub isv_svn         :u16,
+    pub misc_select: sgx_misc_select_t,
+    pub misc_mask: sgx_misc_select_t,
+    pub reserved: [u8; 4],
+    pub isv_family_id: sgx_isvfamily_id_t,
+    pub attributes: sgx_attributes_t,
+    pub attribute_mask: sgx_attributes_t,
+    pub enclave_hash: sgx_measurement_t,
+    pub reserved2: [u8; 16],
+    pub isvext_prod_id: sgx_isvext_prod_id_t,
+    pub isv_prod_id: u16,
+    pub isv_svn: u16,
 }
 
 #[repr(C, packed)]
 pub struct css_buffer_t {
-    pub reserved        :[u8; 12],
-    pub q1              :[u8; SE_KEY_SIZE],
-    pub q2              :[u8; SE_KEY_SIZE],
+    pub reserved: [u8; 12],
+    pub q1: [u8; SE_KEY_SIZE],
+    pub q2: [u8; SE_KEY_SIZE],
 }
 
 #[repr(C, packed)]
 pub struct enclave_css_t {
-    pub header          :css_header_t,
-    pub key             :css_key_t,
-    pub body            :css_body_t,
-    pub buffer          :css_buffer_t,
+    pub header: css_header_t,
+    pub key: css_key_t,
+    pub body: css_body_t,
+    pub buffer: css_buffer_t,
 }
 
 /* version of metadata */
 /* based on 2.9.1 */
-pub const MAJOR_VERSION         :u32 = 2;
-pub const MINOR_VERSION         :u32 = 4;
-pub const SGX_2_1_MAJOR_VERSION :u32 = 2;   //MAJOR_VERSION should not larger than 0ffffffff
-pub const SGX_2_1_MINOR_VERSION :u32 = 2;   //MINOR_VERSION should not larger than 0ffffffff
-pub const SGX_2_0_MAJOR_VERSION :u32 = 2;   //MAJOR_VERSION should not larger than 0ffffffff
-pub const SGX_2_0_MINOR_VERSION :u32 = 1;   //MINOR_VERSION should not larger than 0ffffffff
-pub const SGX_1_9_MAJOR_VERSION :u32 = 1;   //MAJOR_VERSION should not larger than 0ffffffff
-pub const SGX_1_9_MINOR_VERSION :u32 = 4;   //MINOR_VERSION should not larger than 0ffffffff
-pub const SGX_1_5_MAJOR_VERSION :u32 = 1;   //MAJOR_VERSION should not larger than 0ffffffff
-pub const SGX_1_5_MINOR_VERSION :u32 = 3;   //MINOR_VERSION should not larger than 0ffffffff
+pub const MAJOR_VERSION: u32 = 2;
+pub const MINOR_VERSION: u32 = 4;
+pub const SGX_2_1_MAJOR_VERSION: u32 = 2; //MAJOR_VERSION should not larger than 0ffffffff
+pub const SGX_2_1_MINOR_VERSION: u32 = 2; //MINOR_VERSION should not larger than 0ffffffff
+pub const SGX_2_0_MAJOR_VERSION: u32 = 2; //MAJOR_VERSION should not larger than 0ffffffff
+pub const SGX_2_0_MINOR_VERSION: u32 = 1; //MINOR_VERSION should not larger than 0ffffffff
+pub const SGX_1_9_MAJOR_VERSION: u32 = 1; //MAJOR_VERSION should not larger than 0ffffffff
+pub const SGX_1_9_MINOR_VERSION: u32 = 4; //MINOR_VERSION should not larger than 0ffffffff
+pub const SGX_1_5_MAJOR_VERSION: u32 = 1; //MAJOR_VERSION should not larger than 0ffffffff
+pub const SGX_1_5_MINOR_VERSION: u32 = 3; //MINOR_VERSION should not larger than 0ffffffff
 
-pub const METADATA_MAGIC        :u64 = 0x86A80294635D0E4C;
-pub const METADATA_SIZE         :usize = 0x5000;
-pub const TCS_TEMPLATE_SIZE     :usize = 72;
+pub const METADATA_MAGIC: u64 = 0x86A8_0294_635D_0E4C;
+pub const METADATA_SIZE: usize = 0x5000;
+pub const TCS_TEMPLATE_SIZE: usize = 72;
 
-pub const TCS_POLICY_BIND       :u32 = 0x00000000;  /* If set, the TCS is bound to the application thread */
-pub const TCS_POLICY_UNBIND     :u32 = 0x00000001;
+pub const TCS_POLICY_BIND: u32 = 0x0000_0000; /* If set, the TCS is bound to the application thread */
+pub const TCS_POLICY_UNBIND: u32 = 0x0000_0001;
 
-pub const MAX_SAVE_BUF_SIZE     :u32 = 2632;
-pub const TCS_NUM_MIN           :u32 = 1;
-pub const SSA_NUM_MIN           :u32 = 2;
-pub const SSA_FRAME_SIZE_MIN    :u32 = 1;
-pub const SSA_FRAME_SIZE_MAX    :u32 = 2;
-pub const STACK_SIZE_MIN        :u32 = 0x0002000; /*   8 KB */
-pub const STACK_SIZE_MAX        :u32 = 0x0040000; /* 256 KB */
-pub const HEAP_SIZE_MIN         :u32 = 0x0001000; /*   4 KB */
-pub const HEAP_SIZE_MAX         :u32 = 0x1000000; /*  16 MB */
-pub const RSRV_SIZE_MIN         :u32 = 0x0000000; /*   0 KB */
-pub const RSRV_SIZE_MAX         :u32 = 0x0000000; /*   0 KB */
-pub const DEFAULT_MISC_SELECT   :u32 = 0;
-pub const DEFAULT_MISC_MASK     :u32 = 0xFFFFFFFF;
-pub const ISVFAMILYID_MAX       :u64 = 0xFFFFFFFFFFFFFFFF;
-pub const ISVEXTPRODID_MAX      :u64 = 0xFFFFFFFFFFFFFFFF;
+pub const MAX_SAVE_BUF_SIZE: u32 = 2632;
+pub const TCS_NUM_MIN: u32 = 1;
+pub const SSA_NUM_MIN: u32 = 2;
+pub const SSA_FRAME_SIZE_MIN: u32 = 1;
+pub const SSA_FRAME_SIZE_MAX: u32 = 2;
+pub const STACK_SIZE_MIN: u32 = 0x0000_2000; /*   8 KB */
+pub const STACK_SIZE_MAX: u32 = 0x0004_0000; /* 256 KB */
+pub const HEAP_SIZE_MIN: u32 = 0x0000_1000;  /*   4 KB */
+pub const HEAP_SIZE_MAX: u32 = 0x0100_0000;  /*  16 MB */
+pub const RSRV_SIZE_MIN: u32 = 0x0000_0000;  /*   0 KB */
+pub const RSRV_SIZE_MAX: u32 = 0x0000_0000;  /*   0 KB */
+pub const DEFAULT_MISC_SELECT: u32 = 0;
+pub const DEFAULT_MISC_MASK: u32 = 0xFFFF_FFFF;
+pub const ISVFAMILYID_MAX: u64 = 0xFFFF_FFFF_FFFF_FFFF;
+pub const ISVEXTPRODID_MAX: u64 = 0xFFFF_FFFF_FFFF_FFFF;
 
-pub const STATIC_STACK_SIZE     :usize = 688;
-pub const SE_GUARD_PAGE_SHIFT   :usize = 16;
-pub const SE_GUARD_PAGE_SIZE    :usize = 1 << SE_GUARD_PAGE_SHIFT;
+pub const STATIC_STACK_SIZE: usize = 688;
+pub const SE_GUARD_PAGE_SHIFT: usize = 16;
+pub const SE_GUARD_PAGE_SIZE: usize = 1 << SE_GUARD_PAGE_SHIFT;
 
 impl_struct! {
     #[repr(packed)]
     pub struct data_directory_t {
         pub offset :u32,
-        pub size   :u32,
+        pub size :u32,
     }
 }
 
@@ -130,121 +130,127 @@
     }
 }
 
-pub const GROUP_FLAG              :u32 = 1<<12;
-pub const LAYOUT_ID_HEAP_MIN      :u32 = 1;
-pub const LAYOUT_ID_HEAP_INIT     :u32 = 2;
-pub const LAYOUT_ID_HEAP_MAX      :u32 = 3;
-pub const LAYOUT_ID_TCS           :u32 = 4;
-pub const LAYOUT_ID_TD            :u32 = 5;
-pub const LAYOUT_ID_SSA           :u32 = 6;
-pub const LAYOUT_ID_STACK_MAX     :u32 = 7;
-pub const LAYOUT_ID_STACK_MIN     :u32 = 8;
-pub const LAYOUT_ID_THREAD_GROUP  :u32 = group_id!(9);
-pub const LAYOUT_ID_GUARD         :u32 = 10;
-pub const LAYOUT_ID_HEAP_DYN_MIN  :u32 = 11;
-pub const LAYOUT_ID_HEAP_DYN_INIT :u32 = 12;
-pub const LAYOUT_ID_HEAP_DYN_MAX  :u32 = 13;
-pub const LAYOUT_ID_TCS_DYN       :u32 = 14;
-pub const LAYOUT_ID_TD_DYN        :u32 = 15;
-pub const LAYOUT_ID_SSA_DYN       :u32 = 16;
-pub const LAYOUT_ID_STACK_DYN_MAX :u32 = 17;
-pub const LAYOUT_ID_STACK_DYN_MIN :u32 = 18;
-pub const LAYOUT_ID_THREAD_GROUP_DYN :u32 = group_id!(19);
-pub const LAYOUT_ID_RSRV_MIN      :u32 = 20;
-pub const LAYOUT_ID_RSRV_INIT     :u32 = 21;
-pub const LAYOUT_ID_RSRV_MAX      :u32 = 22;
+pub const GROUP_FLAG: u32 = 1 << 12;
+pub const LAYOUT_ID_HEAP_MIN: u32 = 1;
+pub const LAYOUT_ID_HEAP_INIT: u32 = 2;
+pub const LAYOUT_ID_HEAP_MAX: u32 = 3;
+pub const LAYOUT_ID_TCS: u32 = 4;
+pub const LAYOUT_ID_TD: u32 = 5;
+pub const LAYOUT_ID_SSA: u32 = 6;
+pub const LAYOUT_ID_STACK_MAX: u32 = 7;
+pub const LAYOUT_ID_STACK_MIN: u32 = 8;
+pub const LAYOUT_ID_THREAD_GROUP: u32 = group_id!(9);
+pub const LAYOUT_ID_GUARD: u32 = 10;
+pub const LAYOUT_ID_HEAP_DYN_MIN: u32 = 11;
+pub const LAYOUT_ID_HEAP_DYN_INIT: u32 = 12;
+pub const LAYOUT_ID_HEAP_DYN_MAX: u32 = 13;
+pub const LAYOUT_ID_TCS_DYN: u32 = 14;
+pub const LAYOUT_ID_TD_DYN: u32 = 15;
+pub const LAYOUT_ID_SSA_DYN: u32 = 16;
+pub const LAYOUT_ID_STACK_DYN_MAX: u32 = 17;
+pub const LAYOUT_ID_STACK_DYN_MIN: u32 = 18;
+pub const LAYOUT_ID_THREAD_GROUP_DYN: u32 = group_id!(19);
+pub const LAYOUT_ID_RSRV_MIN: u32 = 20;
+pub const LAYOUT_ID_RSRV_INIT: u32 = 21;
+pub const LAYOUT_ID_RSRV_MAX: u32 = 22;
 
 type si_flags_t = u64;
 
 impl_struct! {
     #[repr(packed)]
     pub struct layout_entry_t {
-        pub id             :u16,
-        pub attributes     :u16,
-        pub page_count     :u32,
-        pub rva            :u64,
-        pub content_size   :u32,
+        pub id :u16,
+        pub attributes :u16,
+        pub page_count :u32,
+        pub rva :u64,
+        pub content_size :u32,
         pub content_offset :u32,
-        pub si_flags       :si_flags_t,
+        pub si_flags :si_flags_t,
     }
 
     #[repr(packed)]
     pub struct layout_group_t {
-        pub id             :u16,
-        pub entry_count    :u16,
-        pub load_times     :u32,
-        pub load_step      :u64,
-        pub reserved       :[u32; 4],
+        pub id :u16,
+        pub entry_count :u16,
+        pub load_times :u32,
+        pub load_step :u64,
+        pub reserved :[u32; 4],
     }
 }
 
 #[allow(unused)]
 #[repr(C, packed)]
 pub union layout_t {
-    pub entry :layout_entry_t,
-    pub group :layout_group_t,
+    pub entry: layout_entry_t,
+    pub group: layout_group_t,
 }
 
 #[repr(C, packed)]
 pub struct patch_entry_t {
-    pub dst      :u64,
-    pub src      :u32,
-    pub size     :u32,
-    pub reserved :[u32; 4],
+    pub dst: u64,
+    pub src: u32,
+    pub size: u32,
+    pub reserved: [u32; 4],
 }
 
 #[repr(C, packed)]
 pub struct metadata_t {
-    pub magic_num               :u64,
-    pub version                 :u64,
-    pub size                    :u32,
-    pub tcs_policy              :u32,
-    pub ssa_frame_size          :u32,
-    pub max_save_buffer_size    :u32,
-    pub desired_misc_select     :u32,
-    pub tcs_min_pool            :u32,
-    pub enclave_size            :u64,
-    pub attributes              :sgx_attributes_t,
-    pub enclave_css             :enclave_css_t,
-    pub dirs                    :[data_directory_t; dir_index_t::DIR_NUM as usize],
-    pub data                    :[u8; 18592],
+    pub magic_num: u64,
+    pub version: u64,
+    pub size: u32,
+    pub tcs_policy: u32,
+    pub ssa_frame_size: u32,
+    pub max_save_buffer_size: u32,
+    pub desired_misc_select: u32,
+    pub tcs_min_pool: u32,
+    pub enclave_size: u64,
+    pub attributes: sgx_attributes_t,
+    pub enclave_css: enclave_css_t,
+    pub dirs: [data_directory_t; dir_index_t::DIR_NUM as usize],
+    pub data: [u8; 18592],
 }
 
 /* based on 2.9.1 */
 /* se_page_attr.h */
-pub const PAGE_ATTR_EADD        :u16 = 1<<0;
-pub const PAGE_ATTR_EEXTEND     :u16 = 1<<1;
-pub const PAGE_ATTR_EREMOVE     :u16 = 1<<2;
-pub const PAGE_ATTR_POST_ADD    :u16 = 1<<3;
-pub const PAGE_ATTR_POST_REMOVE :u16 = 1<<4;
-pub const PAGE_ATTR_DYN_THREAD  :u16 = 1<<5;
-pub const PAGE_DIR_GROW_DOWN    :u16 = 1<<6;
-pub const ADD_PAGE_ONLY         :u16 = PAGE_ATTR_EADD;
-pub const ADD_EXTEND_PAGE       :u16 = PAGE_ATTR_EADD | PAGE_ATTR_EEXTEND;
-pub const PAGE_ATTR_MASK        :u16 = !(PAGE_ATTR_EADD | PAGE_ATTR_EEXTEND | PAGE_ATTR_EREMOVE | PAGE_ATTR_POST_ADD | PAGE_ATTR_POST_REMOVE | PAGE_ATTR_DYN_THREAD | PAGE_DIR_GROW_DOWN);
+pub const PAGE_ATTR_EADD: u16 = 1 << 0;
+pub const PAGE_ATTR_EEXTEND: u16 = 1 << 1;
+pub const PAGE_ATTR_EREMOVE: u16 = 1 << 2;
+pub const PAGE_ATTR_POST_ADD: u16 = 1 << 3;
+pub const PAGE_ATTR_POST_REMOVE: u16 = 1 << 4;
+pub const PAGE_ATTR_DYN_THREAD: u16 = 1 << 5;
+pub const PAGE_DIR_GROW_DOWN: u16 = 1 << 6;
+pub const ADD_PAGE_ONLY: u16 = PAGE_ATTR_EADD;
+pub const ADD_EXTEND_PAGE: u16 = PAGE_ATTR_EADD | PAGE_ATTR_EEXTEND;
+pub const PAGE_ATTR_MASK: u16 = !(PAGE_ATTR_EADD
+    | PAGE_ATTR_EEXTEND
+    | PAGE_ATTR_EREMOVE
+    | PAGE_ATTR_POST_ADD
+    | PAGE_ATTR_POST_REMOVE
+    | PAGE_ATTR_DYN_THREAD
+    | PAGE_DIR_GROW_DOWN);
 
 /* based on 2.9.1 */
 /* arch.h */
-pub const SI_FLAG_NONE          :u64 = 0x0;
-pub const SI_FLAG_R             :u64 = 0x1;             /* Read Access */
-pub const SI_FLAG_W             :u64 = 0x2;             /* Write Access */
-pub const SI_FLAG_X             :u64 = 0x4;             /* Execute Access */
-pub const SI_FLAG_PT_LOW_BIT    :u64 = 0x8;                           /* PT low bit */
-pub const SI_FLAG_PT_MASK       :u64 = 0xFF<<SI_FLAG_PT_LOW_BIT ;     /* Page Type Mask [15:8] */
-pub const SI_FLAG_SECS          :u64 = 0x00<<SI_FLAG_PT_LOW_BIT;      /* SECS */
-pub const SI_FLAG_TCS           :u64 = 0x01<<SI_FLAG_PT_LOW_BIT;      /* TCS */
-pub const SI_FLAG_REG           :u64 = 0x02<<SI_FLAG_PT_LOW_BIT;      /* Regular Page */
-pub const SI_FLAG_TRIM          :u64 = 0x04<<SI_FLAG_PT_LOW_BIT;      /* Trim Page */
-pub const SI_FLAG_PENDING       :u64 = 0x8;
-pub const SI_FLAG_MODIFIED      :u64 = 0x10;
-pub const SI_FLAG_PR            :u64 = 0x20;
+pub const SI_FLAG_NONE: u64 = 0x0;
+pub const SI_FLAG_R: u64 = 0x1;                                 /* Read Access */
+pub const SI_FLAG_W: u64 = 0x2;                                 /* Write Access */
+pub const SI_FLAG_X: u64 = 0x4;                                 /* Execute Access */
+pub const SI_FLAG_PT_LOW_BIT: u64 = 0x8;                        /* PT low bit */
+pub const SI_FLAG_PT_MASK: u64 = 0xFF << SI_FLAG_PT_LOW_BIT;    /* Page Type Mask [15:8] */
+pub const SI_FLAG_SECS: u64 = 0x00 << SI_FLAG_PT_LOW_BIT;       /* SECS */
+pub const SI_FLAG_TCS: u64 = 0x01 << SI_FLAG_PT_LOW_BIT;        /* TCS */
+pub const SI_FLAG_REG: u64 = 0x02 << SI_FLAG_PT_LOW_BIT;        /* Regular Page */
+pub const SI_FLAG_TRIM: u64 = 0x04 << SI_FLAG_PT_LOW_BIT;       /* Trim Page */
+pub const SI_FLAG_PENDING: u64 = 0x8;
+pub const SI_FLAG_MODIFIED: u64 = 0x10;
+pub const SI_FLAG_PR: u64 = 0x20;
 
-pub const SI_FLAGS_EXTERNAL     :u64 = SI_FLAG_PT_MASK | SI_FLAG_R | SI_FLAG_W | SI_FLAG_X;   /* Flags visible/usable by instructions */
-pub const SI_FLAGS_R            :u64 = SI_FLAG_R|SI_FLAG_REG;
-pub const SI_FLAGS_RW           :u64 = SI_FLAG_R|SI_FLAG_W|SI_FLAG_REG;
-pub const SI_FLAGS_RX           :u64 = SI_FLAG_R|SI_FLAG_X|SI_FLAG_REG;
-pub const SI_FLAGS_RWX          :u64 = SI_FLAG_R|SI_FLAG_W|SI_FLAG_X|SI_FLAG_REG;
-pub const SI_FLAGS_TCS          :u64 = SI_FLAG_TCS;
-pub const SI_FLAGS_SECS         :u64 = SI_FLAG_SECS;
-pub const SI_MASK_TCS           :u64 = SI_FLAG_PT_MASK;
-pub const SI_MASK_MEM_ATTRIBUTE :u64 = 0x7;
+pub const SI_FLAGS_EXTERNAL: u64 = SI_FLAG_PT_MASK | SI_FLAG_R | SI_FLAG_W | SI_FLAG_X; /* Flags visible/usable by instructions */
+pub const SI_FLAGS_R: u64 = SI_FLAG_R | SI_FLAG_REG;
+pub const SI_FLAGS_RW: u64 = SI_FLAG_R | SI_FLAG_W | SI_FLAG_REG;
+pub const SI_FLAGS_RX: u64 = SI_FLAG_R | SI_FLAG_X | SI_FLAG_REG;
+pub const SI_FLAGS_RWX: u64 = SI_FLAG_R | SI_FLAG_W | SI_FLAG_X | SI_FLAG_REG;
+pub const SI_FLAGS_TCS: u64 = SI_FLAG_TCS;
+pub const SI_FLAGS_SECS: u64 = SI_FLAG_SECS;
+pub const SI_MASK_TCS: u64 = SI_FLAG_PT_MASK;
+pub const SI_MASK_MEM_ATTRIBUTE: u64 = 0x7;
diff --git a/sgx_types/src/types.rs b/sgx_types/src/types.rs
index 143e5a4..05cb12f 100644
--- a/sgx_types/src/types.rs
+++ b/sgx_types/src/types.rs
@@ -15,10 +15,10 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use core::default::Default;
 use crate::error::*;
 use crate::marker::ContiguousMemory;
 use crate::*;
+use core::default::Default;
 
 //
 // sgx_attributes.h
@@ -71,7 +71,7 @@
                                                    | SGX_FLAGS_INITTED
                                                    | SGX_FLAGS_DEBUG
                                                    | SGX_FLAGS_KSS);
-pub const MISC_NON_SECURITY_BITS: uint32_t     = 0x0FFFFFFF;
+pub const MISC_NON_SECURITY_BITS: uint32_t     = 0x0FFF_FFFF;
 pub const TSEAL_DEFAULT_MISCMASK: uint32_t     = !MISC_NON_SECURITY_BITS;
 
 
@@ -160,9 +160,9 @@
 //
 pub const SGX_FEBITSIZE: uint32_t = 256;
 
-impl_struct!{
+impl_struct! {
     #[repr(packed)]
-    pub struct ecc_param_t {
+    pub struct sgx_ecc_param_t {
         pub eccP: [uint32_t; SGX_NISTP_ECP256_KEY_SIZE],      /* EC prime field */
         pub eccA: [uint32_t; SGX_NISTP_ECP256_KEY_SIZE],      /* EC curve coefficient A */
         pub eccB: [uint32_t; SGX_NISTP_ECP256_KEY_SIZE],      /* EC curve coefficient B */
@@ -419,10 +419,10 @@
 //
 // sgx_report.h
 //
-pub const SGX_HASH_SIZE: size_t   = 32;
-pub const SGX_MAC_SIZE: size_t    = 16;
+pub const SGX_HASH_SIZE: size_t = 32;
+pub const SGX_MAC_SIZE: size_t = 16;
 
-pub const SGX_REPORT_DATA_SIZE: size_t   = 64;
+pub const SGX_REPORT_DATA_SIZE: size_t = 64;
 
 pub const SGX_ISVEXT_PROD_ID_SIZE: size_t = 16;
 pub const SGX_ISV_FAMILY_ID_SIZE: size_t  = 16;
@@ -518,7 +518,7 @@
 //
 pub type sgx_spinlock_t = uint32_t;
 
-pub const SGX_SPINLOCK_INITIALIZER: uint32_t    = 0;
+pub const SGX_SPINLOCK_INITIALIZER: uint32_t = 0;
 
 //
 // sgx_tae_service.h
@@ -663,13 +663,13 @@
 pub type sgx_sha1_hash_t = [uint8_t; SGX_SHA1_HASH_SIZE];
 pub type sgx_sha256_hash_t = [uint8_t; SGX_SHA256_HASH_SIZE];
 
-pub type sgx_aes_gcm_128bit_key_t   = [uint8_t; SGX_AESGCM_KEY_SIZE];
-pub type sgx_aes_gcm_128bit_tag_t   = [uint8_t; SGX_AESGCM_MAC_SIZE];
-pub type sgx_hmac_256bit_key_t      = [uint8_t; SGX_HMAC256_KEY_SIZE];
-pub type sgx_hmac_256bit_tag_t      = [uint8_t; SGX_HMAC256_MAC_SIZE];
-pub type sgx_cmac_128bit_key_t      = [uint8_t; SGX_CMAC_KEY_SIZE];
-pub type sgx_cmac_128bit_tag_t      = [uint8_t; SGX_CMAC_MAC_SIZE];
-pub type sgx_aes_ctr_128bit_key_t   = [uint8_t; SGX_AESCTR_KEY_SIZE];
+pub type sgx_aes_gcm_128bit_key_t = [uint8_t; SGX_AESGCM_KEY_SIZE];
+pub type sgx_aes_gcm_128bit_tag_t = [uint8_t; SGX_AESGCM_MAC_SIZE];
+pub type sgx_hmac_256bit_key_t = [uint8_t; SGX_HMAC256_KEY_SIZE];
+pub type sgx_hmac_256bit_tag_t = [uint8_t; SGX_HMAC256_MAC_SIZE];
+pub type sgx_cmac_128bit_key_t = [uint8_t; SGX_CMAC_KEY_SIZE];
+pub type sgx_cmac_128bit_tag_t = [uint8_t; SGX_CMAC_MAC_SIZE];
+pub type sgx_aes_ctr_128bit_key_t = [uint8_t; SGX_AESCTR_KEY_SIZE];
 
 impl_enum! {
     #[repr(u32)]
@@ -716,24 +716,24 @@
 }
 
 /* intel sgx sdk 2.1.3 */
-pub const N_SIZE_IN_BYTES: size_t     = 384;
-pub const E_SIZE_IN_BYTES: size_t     = 4;
-pub const D_SIZE_IN_BYTES: size_t     = 384;
-pub const P_SIZE_IN_BYTES: size_t     = 192;
-pub const Q_SIZE_IN_BYTES: size_t     = 192;
-pub const DMP1_SIZE_IN_BYTES: size_t  = 192;
-pub const DMQ1_SIZE_IN_BYTES: size_t  = 192;
-pub const IQMP_SIZE_IN_BYTES: size_t  = 192;
+pub const N_SIZE_IN_BYTES: size_t = 384;
+pub const E_SIZE_IN_BYTES: size_t = 4;
+pub const D_SIZE_IN_BYTES: size_t = 384;
+pub const P_SIZE_IN_BYTES: size_t = 192;
+pub const Q_SIZE_IN_BYTES: size_t = 192;
+pub const DMP1_SIZE_IN_BYTES: size_t = 192;
+pub const DMQ1_SIZE_IN_BYTES: size_t = 192;
+pub const IQMP_SIZE_IN_BYTES: size_t = 192;
 
 /* intel sgx sdk 2.1.3 */
-pub const N_SIZE_IN_UINT: size_t      = N_SIZE_IN_BYTES / 4;
-pub const E_SIZE_IN_UINT: size_t      = E_SIZE_IN_BYTES / 4;
-pub const D_SIZE_IN_UINT: size_t      = D_SIZE_IN_BYTES / 4;
-pub const P_SIZE_IN_UINT: size_t      = P_SIZE_IN_BYTES / 4;
-pub const Q_SIZE_IN_UINT: size_t      = Q_SIZE_IN_BYTES / 4;
-pub const DMP1_SIZE_IN_UINT: size_t   = DMP1_SIZE_IN_BYTES / 4;
-pub const DMQ1_SIZE_IN_UINT: size_t   = DMQ1_SIZE_IN_BYTES / 4;
-pub const IQMP_SIZE_IN_UINT: size_t   = IQMP_SIZE_IN_BYTES / 4;
+pub const N_SIZE_IN_UINT: size_t = N_SIZE_IN_BYTES / 4;
+pub const E_SIZE_IN_UINT: size_t = E_SIZE_IN_BYTES / 4;
+pub const D_SIZE_IN_UINT: size_t = D_SIZE_IN_BYTES / 4;
+pub const P_SIZE_IN_UINT: size_t = P_SIZE_IN_BYTES / 4;
+pub const Q_SIZE_IN_UINT: size_t = Q_SIZE_IN_BYTES / 4;
+pub const DMP1_SIZE_IN_UINT: size_t = DMP1_SIZE_IN_BYTES / 4;
+pub const DMQ1_SIZE_IN_UINT: size_t = DMQ1_SIZE_IN_BYTES / 4;
+pub const IQMP_SIZE_IN_UINT: size_t = IQMP_SIZE_IN_BYTES / 4;
 
 pub type sgx_rsa_key_t = *mut c_void;
 
@@ -787,10 +787,20 @@
     pub m_queue: sgx_thread_queue_t,
 }
 
-pub const SGX_THREAD_T_NULL: sgx_thread_t   = 0 ;
+#[repr(C)]
+pub struct sgx_thread_rwlock_t {
+    pub m_reader_count: uint32_t,
+    pub m_writers_waiting: uint32_t,
+    pub m_lock: uint32_t,
+    pub m_owner: sgx_thread_t,
+    pub m_reader_queue: sgx_thread_queue_t,
+    pub m_writer_queue: sgx_thread_queue_t,
+}
+
+pub const SGX_THREAD_T_NULL: sgx_thread_t = 0;
 
 pub const SGX_THREAD_MUTEX_NONRECURSIVE: uint32_t = 0x01;
-pub const SGX_THREAD_MUTEX_RECURSIVE: uint32_t    = 0x02;
+pub const SGX_THREAD_MUTEX_RECURSIVE: uint32_t = 0x02;
 
 pub const SGX_THREAD_NONRECURSIVE_MUTEX_INITIALIZER: sgx_thread_mutex_t = sgx_thread_mutex_t {
     m_refcount: 0,
@@ -799,9 +809,9 @@
     m_owner: SGX_THREAD_T_NULL,
     m_queue: sgx_thread_queue_t {
         m_first: SGX_THREAD_T_NULL,
-        m_last: SGX_THREAD_T_NULL
-        }
-    };
+        m_last: SGX_THREAD_T_NULL,
+    },
+};
 
 pub const SGX_THREAD_RECURSIVE_MUTEX_INITIALIZER: sgx_thread_mutex_t = sgx_thread_mutex_t {
     m_refcount: 0,
@@ -810,17 +820,37 @@
     m_owner: SGX_THREAD_T_NULL,
     m_queue: sgx_thread_queue_t {
         m_first: SGX_THREAD_T_NULL,
-        m_last: SGX_THREAD_T_NULL
-        }
-    };
+        m_last: SGX_THREAD_T_NULL,
+    },
+};
 
-pub const SGX_THREAD_MUTEX_INITIALIZER: sgx_thread_mutex_t = SGX_THREAD_NONRECURSIVE_MUTEX_INITIALIZER;
+pub const SGX_THREAD_MUTEX_INITIALIZER: sgx_thread_mutex_t =
+    SGX_THREAD_NONRECURSIVE_MUTEX_INITIALIZER;
+
+pub const SGX_THREAD_LOCK_INITIALIZER: sgx_thread_rwlock_t = sgx_thread_rwlock_t {
+    m_reader_count: 0,
+    m_writers_waiting: 0,
+    m_lock: 0,
+    m_owner: SGX_THREAD_T_NULL,
+    m_reader_queue: sgx_thread_queue_t {
+        m_first: SGX_THREAD_T_NULL,
+        m_last: SGX_THREAD_T_NULL,
+    },
+    m_writer_queue: sgx_thread_queue_t {
+        m_first: SGX_THREAD_T_NULL,
+        m_last: SGX_THREAD_T_NULL,
+    },
+};
 
 impl_struct! {
     pub struct sgx_thread_mutex_attr_t {
         pub m_dummy: c_uchar,
     }
 
+    pub struct sgx_thread_rwlockattr_t {
+        pub m_dummy: c_uchar,
+    }
+
     pub struct sgx_thread_cond_attr_t {
         pub m_dummy: c_uchar,
     }
@@ -836,25 +866,27 @@
     m_lock: 0,
     m_queue: sgx_thread_queue_t {
         m_first: SGX_THREAD_T_NULL,
-        m_last: SGX_THREAD_T_NULL
-    }
+        m_last: SGX_THREAD_T_NULL,
+    },
 };
 
 //
 // sgx_tkey_exchange.h
 //
-pub type sgx_ra_derive_secret_keys_t = extern "C" fn(p_shared_key: *const sgx_ec256_dh_shared_t,
-                                                     kdf_id: uint16_t,
-                                                     p_smk_key: *mut sgx_ec_key_128bit_t,
-                                                     p_sk_key: *mut sgx_ec_key_128bit_t,
-                                                     p_mk_key: *mut sgx_ec_key_128bit_t,
-                                                     p_vk_key: *mut sgx_ec_key_128bit_t) -> sgx_status_t;
+pub type sgx_ra_derive_secret_keys_t = extern "C" fn(
+    p_shared_key: *const sgx_ec256_dh_shared_t,
+    kdf_id: uint16_t,
+    p_smk_key: *mut sgx_ec_key_128bit_t,
+    p_sk_key: *mut sgx_ec_key_128bit_t,
+    p_mk_key: *mut sgx_ec_key_128bit_t,
+    p_vk_key: *mut sgx_ec_key_128bit_t,
+) -> sgx_status_t;
 
 //
 // sgx_trts_exception.h
 //
-pub const EXCEPTION_CONTINUE_SEARCH: int32_t      = 0;
-pub const EXCEPTION_CONTINUE_EXECUTION: int32_t   = -1;
+pub const EXCEPTION_CONTINUE_SEARCH: int32_t = 0;
+pub const EXCEPTION_CONTINUE_EXECUTION: int32_t = -1;
 
 impl_enum! {
     #[repr(u32)]
@@ -874,7 +906,7 @@
     }
 }
 
-impl_enum!{
+impl_enum! {
     #[repr(u32)]
     #[derive(Copy, Clone, PartialEq, Eq)]
     pub enum sgx_exception_type_t {
@@ -938,8 +970,8 @@
 //
 // sgx_tseal.h
 //
-pub const SGX_SEAL_TAG_SIZE: size_t  = SGX_AESGCM_MAC_SIZE;
-pub const SGX_SEAL_IV_SIZE: size_t   = 12;
+pub const SGX_SEAL_TAG_SIZE: size_t = SGX_AESGCM_MAC_SIZE;
+pub const SGX_SEAL_IV_SIZE: size_t = 12;
 
 impl_struct! {
     pub struct sgx_aes_gcm_data_t {
@@ -960,8 +992,8 @@
 //
 // sgx_uae_platform.h
 //
-pub const PS_CAP_TRUSTED_TIME: size_t        = 0x1;
-pub const PS_CAP_MONOTONIC_COUNTER: size_t   = 0x2;
+pub const PS_CAP_TRUSTED_TIME: size_t = 0x1;
+pub const PS_CAP_MONOTONIC_COUNTER: size_t = 0x2;
 
 impl_struct! {
     pub struct sgx_ps_cap_t {
@@ -973,26 +1005,32 @@
 //
 // sgx_ukey_exchange.h
 //
-pub type sgx_ecall_get_ga_trusted_t = unsafe extern "C" fn(eid: sgx_enclave_id_t,
-                                                           retval: *mut sgx_status_t,
-                                                           context: sgx_ra_context_t,
-                                                           g_a: *mut sgx_ec256_public_t) -> sgx_status_t;
+pub type sgx_ecall_get_ga_trusted_t = unsafe extern "C" fn(
+    eid: sgx_enclave_id_t,
+    retval: *mut sgx_status_t,
+    context: sgx_ra_context_t,
+    g_a: *mut sgx_ec256_public_t,
+) -> sgx_status_t;
 
-pub type sgx_ecall_proc_msg2_trusted_t = unsafe extern "C" fn(eid: sgx_enclave_id_t,
-                                                              retval: *mut sgx_status_t,
-                                                              context: sgx_ra_context_t,
-                                                              p_msg2: *const sgx_ra_msg2_t,
-                                                              p_qe_target: *const sgx_target_info_t,
-                                                              p_report: *mut sgx_report_t,
-                                                              nonce: *mut sgx_quote_nonce_t) -> sgx_status_t;
+pub type sgx_ecall_proc_msg2_trusted_t = unsafe extern "C" fn(
+    eid: sgx_enclave_id_t,
+    retval: *mut sgx_status_t,
+    context: sgx_ra_context_t,
+    p_msg2: *const sgx_ra_msg2_t,
+    p_qe_target: *const sgx_target_info_t,
+    p_report: *mut sgx_report_t,
+    nonce: *mut sgx_quote_nonce_t,
+) -> sgx_status_t;
 
-pub type sgx_ecall_get_msg3_trusted_t = unsafe extern "C" fn(eid: sgx_enclave_id_t,
-                                                             retval: *mut sgx_status_t,
-                                                             context: sgx_ra_context_t,
-                                                             quote_size: uint32_t,
-                                                             qe_report: *mut sgx_report_t,
-                                                             p_msg3: *mut sgx_ra_msg3_t,
-                                                             msg3_size: uint32_t) -> sgx_status_t;
+pub type sgx_ecall_get_msg3_trusted_t = unsafe extern "C" fn(
+    eid: sgx_enclave_id_t,
+    retval: *mut sgx_status_t,
+    context: sgx_ra_context_t,
+    quote_size: uint32_t,
+    qe_report: *mut sgx_report_t,
+    p_msg3: *mut sgx_ra_msg3_t,
+    msg3_size: uint32_t,
+) -> sgx_status_t;
 
 //
 // sgx_urts.h
@@ -1004,13 +1042,15 @@
 pub const SGX_CREATE_ENCLAVE_EX_PCL_BIT_IDX: size_t = 0;
 pub const SGX_CREATE_ENCLAVE_EX_PCL: uint32_t = 1 << SGX_CREATE_ENCLAVE_EX_PCL_BIT_IDX as uint32_t;
 pub const SGX_CREATE_ENCLAVE_EX_SWITCHLESS_BIT_IDX: size_t = 1;
-pub const SGX_CREATE_ENCLAVE_EX_SWITCHLESS: uint32_t = 1 << SGX_CREATE_ENCLAVE_EX_SWITCHLESS_BIT_IDX as uint32_t;
+pub const SGX_CREATE_ENCLAVE_EX_SWITCHLESS: uint32_t =
+    1 << SGX_CREATE_ENCLAVE_EX_SWITCHLESS_BIT_IDX as uint32_t;
 /* intel sgx sdk 2.4 */
 pub const SGX_CREATE_ENCLAVE_EX_KSS_BIT_IDX: size_t = 2;
 pub const SGX_CREATE_ENCLAVE_EX_KSS: uint32_t = 1 << SGX_CREATE_ENCLAVE_EX_KSS_BIT_IDX as uint32_t;
 
 pub const _SGX_LAST_EX_FEATURE_IDX_: uint32_t = SGX_CREATE_ENCLAVE_EX_KSS_BIT_IDX as uint32_t;
-pub const _SGX_EX_FEATURES_MASK_: uint32_t = 0xFFFF_FFFF_u32 >> (MAX_EX_FEATURES_COUNT as uint32_t - 1 - _SGX_LAST_EX_FEATURE_IDX_);
+pub const _SGX_EX_FEATURES_MASK_: uint32_t =
+    0xFFFF_FFFF_u32 >> (MAX_EX_FEATURES_COUNT as uint32_t - 1 - _SGX_LAST_EX_FEATURE_IDX_);
 
 /* intel sgx sdk 2.4 */
 impl_copy_clone! {
@@ -1034,8 +1074,8 @@
 //
 pub const ENCLAVE_INIT_NOT_STARTED: uint32_t = 0;
 pub const ENCLAVE_INIT_IN_PROGRESS: uint32_t = 1;
-pub const ENCLAVE_INIT_DONE: uint32_t        = 2;
-pub const ENCLAVE_CRASHED: uint32_t          = 3;
+pub const ENCLAVE_INIT_DONE: uint32_t = 2;
+pub const ENCLAVE_CRASHED: uint32_t = 3;
 
 //
 // sgx_cpuid.h
@@ -1054,13 +1094,12 @@
 //    }
 //}
 
-
 //
 // sgx_tprotected_fs.h
 //
 pub type SGX_FILE = *mut c_void;
 pub const FILENAME_MAX: c_uint = 260; //define in sgx_tprotected_fs.h
-pub const FOPEN_MAX: c_uint = 20;     //define in sgx_tprotected_fs.h
+pub const FOPEN_MAX: c_uint = 20; //define in sgx_tprotected_fs.h
 
 /* intel sgx sdk 2.0 */
 //
@@ -1085,10 +1124,10 @@
 //
 // sgx_pcl_guid.h
 //
-pub const SGX_PCL_GUID_SIZE: size_t   = 16;
-pub const SGX_PCL_GUID: [uint8_t; SGX_PCL_GUID_SIZE] =
-    [0x95, 0x48, 0x6e, 0x8f, 0x8f, 0x4a, 0x41, 0x4f, 0xb1, 0x27, 0x46, 0x21, 0xa8, 0x59, 0xa8, 0xac];
-
+pub const SGX_PCL_GUID_SIZE: size_t = 16;
+pub const SGX_PCL_GUID: [uint8_t; SGX_PCL_GUID_SIZE] = [
+    0x95, 0x48, 0x6e, 0x8f, 0x8f, 0x4a, 0x41, 0x4f, 0xb1, 0x27, 0x46, 0x21, 0xa8, 0x59, 0xa8, 0xac,
+];
 
 /* intel sgx sdk 2.2 */
 //
@@ -1122,9 +1161,11 @@
     }
 }
 
-pub type sgx_uswitchless_worker_callback_t = extern "C" fn(worker_type: sgx_uswitchless_worker_type_t,
-                                                           worker_event: sgx_uswitchless_worker_event_t,
-                                                           worker_stats: *const sgx_uswitchless_worker_stats_t);
+pub type sgx_uswitchless_worker_callback_t = extern "C" fn(
+    worker_type: sgx_uswitchless_worker_type_t,
+    worker_event: sgx_uswitchless_worker_event_t,
+    worker_stats: *const sgx_uswitchless_worker_stats_t,
+);
 
 pub const SL_DEFAULT_FALLBACK_RETRIES: uint32_t = 20000;
 pub const SL_DEFAULT_SLEEP_RETRIES: uint32_t = 20000;
@@ -1145,7 +1186,7 @@
 
 impl Default for sgx_uswitchless_config_t {
     fn default() -> sgx_uswitchless_config_t {
-        let mut config: sgx_uswitchless_config_t = unsafe{ core::mem::zeroed() };
+        let mut config: sgx_uswitchless_config_t = unsafe { core::mem::zeroed() };
         config.num_uworkers = 1;
         config.num_tworkers = 1;
         config
@@ -1221,20 +1262,20 @@
 
 #[repr(C)]
 pub struct sgx_ql_qve_collateral_t {
-    pub version: uint32_t,                  // version = 1.  PCK Cert chain is in the Quote.
+    pub version: uint32_t, // version = 1.  PCK Cert chain is in the Quote.
     pub pck_crl_issuer_chain: *mut char,
     pub pck_crl_issuer_chain_size: uint32_t,
-    pub root_ca_crl: *mut char,            // Root CA CRL
+    pub root_ca_crl: *mut char, // Root CA CRL
     pub root_ca_crl_size: uint32_t,
-    pub pck_crl: *mut char,                // PCK Cert CRL
+    pub pck_crl: *mut char, // PCK Cert CRL
     pub pck_crl_size: uint32_t,
     pub tcb_info_issuer_chain: *mut char,
     pub tcb_info_issuer_chain_size: uint32_t,
-    pub tcb_info: *mut char,               // TCB Info structure
+    pub tcb_info: *mut char, // TCB Info structure
     pub tcb_info_size: uint32_t,
     pub qe_identity_issuer_chain: *mut char,
     pub qe_identity_issuer_chain_size: uint32_t,
-    pub qe_identity: *mut char,            // QE Identity Structure
+    pub qe_identity: *mut char, // QE Identity Structure
     pub qe_identity_size: uint32_t,
 }
 
@@ -1379,63 +1420,63 @@
     #[repr(u32)]
     #[derive(Copy, Clone, PartialEq, Eq)]
     pub enum sgx_ql_path_type_t {
-        SGX_QL_QE3_PATH  = 0,
-        SGX_QL_PCE_PATH  = 1,
-        SGX_QL_QPL_PATH  = 2,
+        SGX_QL_QE3_PATH = 0,
+        SGX_QL_PCE_PATH = 1,
+        SGX_QL_QPL_PATH = 2,
     }
 }
 
-
 //
 // qve_header.h
 //
-// latest_issue_date and earliest_expiration_date is as of DCAP_1.5
+
+pub const ROOT_KEY_ID_SIZE: usize = 48;
+pub const PLATFORM_INSTANCE_ID_SIZE: usize = 16;
+
+/* intel DCAP 1.7 */
+impl_enum! {
+    #[repr(u32)]
+    #[derive(Copy, Clone, PartialEq, Eq)]
+    pub enum pck_cert_flag_enum_t {
+        PCK_FLAG_FALSE = 0,
+        PCK_FLAG_TRUE = 1,
+        PCK_FLAG_UNDEFINED = 2,
+    }
+}
+
 impl_copy_clone! {
     pub struct sgx_ql_qv_supplemental_t {
         pub version: uint32_t,
-
         pub earliest_issue_date: time_t,
         pub latest_issue_date: time_t,
         pub earliest_expiration_date: time_t,
         pub tcb_level_date_tag: time_t,
-
         pub pck_crl_num: uint32_t,
         pub root_ca_crl_num: uint32_t,
         pub tcb_eval_ref_num: uint32_t,
-        pub root_key_id: [uint8_t; 48],
+        pub root_key_id: [uint8_t; ROOT_KEY_ID_SIZE],
         pub pck_ppid: sgx_key_128bit_t,
         pub tcb_cpusvn: sgx_cpu_svn_t,
         pub tcb_pce_isvsvn: sgx_isv_svn_t,
         pub pce_id: uint16_t,
+        /* intel DCAP 1.7 */
+        pub sgx_type: uint8_t,
+
+        pub platform_instance_id: [uint8_t; PLATFORM_INSTANCE_ID_SIZE],
+        pub dynamic_platform: pck_cert_flag_enum_t,
+        pub cached_keys: pck_cert_flag_enum_t,
+        pub smt_enabled: pck_cert_flag_enum_t,
     }
 }
 
 impl_struct_default! {
-    sgx_ql_qv_supplemental_t; //104
+    sgx_ql_qv_supplemental_t; //168
 }
 
 impl_struct_ContiguousMemory! {
     sgx_ql_qv_supplemental_t;
 }
 
-impl_enum! {
-    #[repr(u32)]
-    #[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Debug)]
-    pub enum sgx_ql_qv_result_t {
-        SGX_QL_QV_RESULT_OK                                 = 0x0000_0000,
-        // SGX_QL_QV_RESULT_MIN                             = 0x0000_A001,
-        SGX_QL_QV_RESULT_CONFIG_NEEDED                      = 0x0000_A001,
-        SGX_QL_QV_RESULT_OUT_OF_DATE                        = 0x0000_A002,
-        SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED          = 0x0000_A003,
-        SGX_QL_QV_RESULT_INVALID_SIGNATURE                  = 0x0000_A004,
-        SGX_QL_QV_RESULT_REVOKED                            = 0x0000_A005,
-        SGX_QL_QV_RESULT_UNSPECIFIED                        = 0x0000_A006,
-        SGX_QL_QV_RESULT_SW_HARDENING_NEEDED                = 0x0000_A007,
-        SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED     = 0x0000_A008,
-        SGX_QL_QV_RESULT_MAX                                = 0x0000_A0FF,
-    }
-}
-
 /* intel DCAP 1.6 */
 //
 // sgx_dcap_quoteverify.h
@@ -1518,7 +1559,7 @@
 //
 // sgx_rsrv_mem_mngr.h
 //
-pub const SGX_PROT_READ:  uint32_t = 0x1; /* page can be read */
+pub const SGX_PROT_READ: uint32_t = 0x1; /* page can be read */
 pub const SGX_PROT_WRITE: uint32_t = 0x2; /* page can be written */
-pub const SGX_PROT_EXEC:  uint32_t = 0x4; /* page can be executed */
-pub const SGX_PROT_NONE:  uint32_t = 0x0; /* page can not be accessed */
+pub const SGX_PROT_EXEC: uint32_t = 0x4; /* page can be executed */
+pub const SGX_PROT_NONE: uint32_t = 0x0; /* page can not be accessed */
diff --git a/sgx_ucrypto/build.rs b/sgx_ucrypto/build.rs
index 9714041..f796bbf 100644
--- a/sgx_ucrypto/build.rs
+++ b/sgx_ucrypto/build.rs
@@ -17,9 +17,8 @@
 
 use std::env;
 
-fn main () {
-    let sdk_dir = env::var("SGX_SDK")
-                    .unwrap_or_else(|_| "/opt/intel/sgxsdk".to_string());
+fn main() {
+    let sdk_dir = env::var("SGX_SDK").unwrap_or_else(|_| "/opt/intel/sgxsdk".to_string());
 
     println!("cargo:rustc-link-search=native={}/lib64", sdk_dir);
     println!("cargo:rustc-link-lib=static=sgx_tcrypto");
diff --git a/sgx_ucrypto/src/crypto.rs b/sgx_ucrypto/src/crypto.rs
index 79876cd..5bc3d4d 100644
--- a/sgx_ucrypto/src/crypto.rs
+++ b/sgx_ucrypto/src/crypto.rs
@@ -18,12 +18,12 @@
 //!
 //! Cryptographic Functions
 //!
-use sgx_types::*;
 use sgx_types::marker::ContiguousMemory;
-use std::ops::{Drop, DerefMut};
-use std::ptr;
-use std::mem;
+use sgx_types::*;
 use std::cell::{Cell, RefCell};
+use std::mem;
+use std::ops::{DerefMut, Drop};
+use std::ptr;
 
 ///
 /// The rsgx_sha256_msg function performs a standard SHA256 hash over the input data buffer.
@@ -74,12 +74,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha256_hash_t::default();
-    let ret = unsafe { sgx_sha256_msg(src as *const _ as *const u8, size as u32, &mut hash as *mut sgx_sha256_hash_t) };
+    let ret = unsafe {
+        sgx_sha256_msg(
+            src as *const _ as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha256_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -97,12 +103,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha256_hash_t::default();
-    let ret = unsafe { sgx_sha256_msg(src.as_ptr() as *const u8, size as u32, &mut hash as *mut sgx_sha256_hash_t) };
+    let ret = unsafe {
+        sgx_sha256_msg(
+            src.as_ptr() as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha256_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -110,9 +122,7 @@
 }
 
 fn rsgx_sha256_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-    unsafe {
-        sgx_sha256_init(sha_handle as *mut sgx_sha_state_handle_t)
-    }
+    unsafe { sgx_sha256_init(sha_handle as *mut sgx_sha_state_handle_t) }
 }
 
 fn rsgx_sha256_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -123,13 +133,11 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    unsafe {
-        sgx_sha256_update(src as *const _ as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha256_update(src as *const _ as *const u8, size as u32, sha_handle) }
 }
 
 fn rsgx_sha256_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -140,20 +148,21 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_sha256_update(src.as_ptr() as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha256_update(src.as_ptr() as *const u8, size as u32, sha_handle) }
 }
 
-fn rsgx_sha256_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha256_hash_t) -> sgx_status_t {
+fn rsgx_sha256_get_hash(
+    sha_handle: sgx_sha_state_handle_t,
+    hash: &mut sgx_sha256_hash_t,
+) -> sgx_status_t {
     unsafe { sgx_sha256_get_hash(sha_handle, hash as *mut sgx_sha256_hash_t) }
 }
 
 fn rsgx_sha256_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-     unsafe { sgx_sha256_close(sha_handle) }
+    unsafe { sgx_sha256_close(sha_handle) }
 }
 
 pub fn rsgx_sha1_msg<T>(src: &T) -> SgxResult<sgx_sha1_hash_t>
@@ -164,12 +173,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha1_hash_t::default();
-    let ret = unsafe { sgx_sha1_msg(src as *const _ as *const u8, size as u32, &mut hash as *mut sgx_sha1_hash_t) };
+    let ret = unsafe {
+        sgx_sha1_msg(
+            src as *const _ as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha1_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -184,12 +199,18 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
     let mut hash = sgx_sha1_hash_t::default();
-    let ret = unsafe { sgx_sha1_msg(src.as_ptr() as *const u8, size as u32, &mut hash as *mut sgx_sha1_hash_t) };
+    let ret = unsafe {
+        sgx_sha1_msg(
+            src.as_ptr() as *const u8,
+            size as u32,
+            &mut hash as *mut sgx_sha1_hash_t,
+        )
+    };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(hash),
         _ => Err(ret),
@@ -197,9 +218,7 @@
 }
 
 fn rsgx_sha1_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-    unsafe {
-        sgx_sha1_init(sha_handle as *mut sgx_sha_state_handle_t)
-    }
+    unsafe { sgx_sha1_init(sha_handle as *mut sgx_sha_state_handle_t) }
 }
 
 fn rsgx_sha1_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -210,13 +229,11 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    unsafe {
-        sgx_sha1_update(src as *const _ as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha1_update(src as *const _ as *const u8, size as u32, sha_handle) }
 }
 
 fn rsgx_sha1_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> sgx_status_t
@@ -227,20 +244,21 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_sha1_update(src.as_ptr() as *const u8, size as u32, sha_handle)
-    }
+    unsafe { sgx_sha1_update(src.as_ptr() as *const u8, size as u32, sha_handle) }
 }
 
-fn rsgx_sha1_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha1_hash_t) -> sgx_status_t {
+fn rsgx_sha1_get_hash(
+    sha_handle: sgx_sha_state_handle_t,
+    hash: &mut sgx_sha1_hash_t,
+) -> sgx_status_t {
     unsafe { sgx_sha1_get_hash(sha_handle, hash as *mut sgx_sha1_hash_t) }
 }
 
 fn rsgx_sha1_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-     unsafe { sgx_sha1_close(sha_handle) }
+    unsafe { sgx_sha1_close(sha_handle) }
 }
 
 ///
@@ -255,12 +273,11 @@
 }
 
 impl SgxShaHandle {
-
     ///
     /// Constructs a new, empty SgxShaHandle.
     ///
     pub fn new() -> SgxShaHandle {
-        SgxShaHandle{
+        SgxShaHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_sha_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -479,7 +496,6 @@
 }
 
 impl Drop for SgxShaHandle {
-
     ///
     /// drop cleans up and deallocates the SHA256 state that was allocated in function init.
     ///
@@ -495,7 +511,7 @@
 
 impl SgxSha1Handle {
     pub fn new() -> SgxSha1Handle {
-        SgxSha1Handle{
+        SgxSha1Handle {
             handle: RefCell::new(ptr::null_mut() as sgx_sha_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -591,7 +607,6 @@
 }
 
 impl Drop for SgxSha1Handle {
-
     ///
     /// drop cleans up and deallocates the SHA256 state that was allocated in function init.
     ///
@@ -682,7 +697,7 @@
     mac: &mut sgx_aes_gcm_128bit_tag_t,
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let iv_len = iv.len();
@@ -690,11 +705,11 @@
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let aad_len = aad.len();
-    if aad_len > u32::max_value() as usize {
+    if aad_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -702,7 +717,11 @@
     }
 
     let ret = unsafe {
-        let p_aad = if aad_len != 0 { aad.as_ptr() } else { ptr::null() };
+        let p_aad = if aad_len != 0 {
+            aad.as_ptr()
+        } else {
+            ptr::null()
+        };
 
         let (p_src, p_dst) = if src_len != 0 {
             (src.as_ptr(), dst.as_mut_ptr())
@@ -813,7 +832,7 @@
     dst: &mut [u8],
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let iv_len = iv.len();
@@ -821,11 +840,11 @@
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let aad_len = aad.len();
-    if aad_len > u32::max_value() as usize {
+    if aad_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -833,7 +852,11 @@
     }
 
     let ret = unsafe {
-        let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
+        let p_aad = if !aad.is_empty() {
+            aad.as_ptr()
+        } else {
+            ptr::null()
+        };
 
         let (p_src, p_dst) = if src_len != 0 {
             (src.as_ptr(), dst.as_mut_ptr())
@@ -903,7 +926,10 @@
 ///
 /// 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>
+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,
 {
@@ -911,7 +937,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -933,7 +959,10 @@
 ///
 /// 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>
+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,
 {
@@ -941,7 +970,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -960,7 +989,10 @@
     }
 }
 
-fn rsgx_cmac128_init(key: &sgx_cmac_128bit_key_t, cmac_handle: &mut sgx_cmac_state_handle_t) -> sgx_status_t {
+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,
@@ -977,12 +1009,10 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_cmac128_update(src as *const _ as *const u8, size as u32, cmac_handle)
-    }
+    unsafe { sgx_cmac128_update(src as *const _ as *const u8, size as u32, cmac_handle) }
 }
 
 fn rsgx_cmac128_update_slice<T>(src: &[T], cmac_handle: sgx_cmac_state_handle_t) -> sgx_status_t
@@ -993,15 +1023,22 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_cmac128_update(src.as_ptr() as *const _ as *const u8, size as u32, cmac_handle)
+        sgx_cmac128_update(
+            src.as_ptr() as *const _ as *const u8,
+            size as u32,
+            cmac_handle,
+        )
     }
 }
 
-fn rsgx_cmac128_final(cmac_handle: sgx_cmac_state_handle_t, hash: &mut sgx_cmac_128bit_tag_t) -> sgx_status_t {
+fn rsgx_cmac128_final(
+    cmac_handle: sgx_cmac_state_handle_t,
+    hash: &mut sgx_cmac_128bit_tag_t,
+) -> sgx_status_t {
     unsafe { sgx_cmac128_final(cmac_handle, hash as *mut sgx_cmac_128bit_tag_t) }
 }
 
@@ -1261,11 +1298,14 @@
     /// drop cleans up and deallocates the CMAC algorithm context state that was allocated in function init.
     ///
     fn drop(&mut self) {
-       let _ = self.close();
+        let _ = self.close();
     }
 }
 
-pub fn rsgx_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResult<sgx_hmac_256bit_tag_t>
+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,
 {
@@ -1273,7 +1313,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -1294,7 +1334,10 @@
     }
 }
 
-pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxResult<sgx_hmac_256bit_tag_t>
+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,
 {
@@ -1302,7 +1345,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -1323,7 +1366,10 @@
     }
 }
 
-fn rsgx_hmac256_init(key: &sgx_hmac_256bit_key_t, hmac_handle: &mut sgx_hmac_state_handle_t) -> sgx_status_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,
@@ -1341,12 +1387,10 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    unsafe {
-        sgx_hmac256_update(src as *const _ as *const u8, size as i32, hmac_handle)
-    }
+    unsafe { sgx_hmac256_update(src as *const _ as *const u8, size as i32, hmac_handle) }
 }
 
 fn rsgx_hmac256_update_slice<T>(src: &[T], hmac_handle: sgx_hmac_state_handle_t) -> sgx_status_t
@@ -1357,15 +1401,22 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_hmac256_update(src.as_ptr() as *const _ as *const u8, size as i32, hmac_handle)
+        sgx_hmac256_update(
+            src.as_ptr() as *const _ as *const u8,
+            size as i32,
+            hmac_handle,
+        )
     }
 }
 
-fn rsgx_hmac256_final(hmac_handle: sgx_hmac_state_handle_t, hash: &mut sgx_hmac_256bit_tag_t) -> sgx_status_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,
@@ -1386,7 +1437,7 @@
 
 impl SgxHmacHandle {
     pub fn new() -> SgxHmacHandle {
-        SgxHmacHandle{
+        SgxHmacHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_hmac_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -1483,7 +1534,7 @@
 
 impl Drop for SgxHmacHandle {
     fn drop(&mut self) {
-       let _ = self.close();
+        let _ = self.close();
     }
 }
 
@@ -1556,14 +1607,14 @@
     dst: &mut [u8],
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if src_len < 1 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -1652,14 +1703,14 @@
     dst: &mut [u8],
 ) -> SgxError {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if src_len < 1 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
     if dst_len < src_len {
@@ -1704,8 +1755,18 @@
     }
 }
 
-fn rsgx_ecc256_check_point(point: &sgx_ec256_public_t, ecc_handle: sgx_ecc_state_handle_t, valid: &mut i32) -> sgx_status_t {
-    unsafe { sgx_ecc256_check_point(point as *const sgx_ec256_public_t, ecc_handle, valid as *mut i32) }
+fn rsgx_ecc256_check_point(
+    point: &sgx_ec256_public_t,
+    ecc_handle: sgx_ecc_state_handle_t,
+    valid: &mut i32,
+) -> sgx_status_t {
+    unsafe {
+        sgx_ecc256_check_point(
+            point as *const sgx_ec256_public_t,
+            ecc_handle,
+            valid as *mut i32,
+        )
+    }
 }
 
 fn rsgx_ecc256_compute_shared_dhkey(
@@ -1716,8 +1777,8 @@
 ) -> 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,
+            private_b as *const sgx_ec256_private_t,
+            public_ga as *const sgx_ec256_public_t,
             shared_key as *mut sgx_ec256_dh_shared_t,
             ecc_handle,
         )
@@ -1755,16 +1816,18 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
     unsafe {
-        sgx_ecdsa_sign(data 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)
+        sgx_ecdsa_sign(
+            data as *const _ as *const u8,
+            size as u32,
+            private as *const sgx_ec256_private_t,
+            signature as *mut sgx_ec256_signature_t,
+            ecc_handle,
+        )
     }
 }
 
@@ -1781,15 +1844,15 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
     unsafe {
         sgx_ecdsa_sign(
-            data.as_ptr() as *const _  as *const u8,
+            data.as_ptr() as *const _ as *const u8,
             size as u32,
-            private as *const _ as *mut sgx_ec256_private_t,
+            private as *const sgx_ec256_private_t,
             signature as *mut sgx_ec256_signature_t,
             ecc_handle,
         )
@@ -1810,7 +1873,7 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -1820,15 +1883,18 @@
             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,
+            signature as *const sgx_ec256_signature_t,
             &mut verify as *mut u8,
-            ecc_handle);
+            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
     }
@@ -1848,7 +1914,7 @@
     if size == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -1858,7 +1924,7 @@
             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,
+            signature as *const sgx_ec256_signature_t,
             &mut verify as *mut u8,
             ecc_handle,
         );
@@ -1867,7 +1933,9 @@
                 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
     }
@@ -1885,7 +1953,7 @@
         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,
+            signature as *const sgx_ec256_signature_t,
             &mut verify as *mut u8,
             ecc_handle,
         );
@@ -1894,13 +1962,14 @@
                 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
     }
 }
 
-
 ///
 /// ECC GF(p) context state.
 ///
@@ -1908,7 +1977,7 @@
 /// elliptic curve cryptosystem standard functions. The algorithm stores the intermediate results
 /// of calculations performed using this context.
 ///
-pub struct SgxEccHandle{
+pub struct SgxEccHandle {
     handle: RefCell<sgx_ecc_state_handle_t>,
     initflag: Cell<bool>,
 }
@@ -2221,13 +2290,22 @@
     ///
     /// The key creation process failed due to an internal cryptography library failure.
     ///
-    pub fn compute_shared_dhkey(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_ec256_dh_shared_t> {
+    pub fn compute_shared_dhkey(
+        &self,
+        private_b: &sgx_ec256_private_t,
+        public_ga: &sgx_ec256_public_t,
+    ) -> SgxResult<sgx_ec256_dh_shared_t> {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
 
         let mut shared_key = sgx_ec256_dh_shared_t::default();
-        let ret = rsgx_ecc256_compute_shared_dhkey(private_b, public_ga, &mut shared_key, *self.handle.borrow());
+        let ret = rsgx_ecc256_compute_shared_dhkey(
+            private_b,
+            public_ga,
+            &mut shared_key,
+            *self.handle.borrow(),
+        );
         match ret {
             sgx_status_t::SGX_SUCCESS => Ok(shared_key),
             _ => Err(ret),
@@ -2309,7 +2387,11 @@
     ///
     /// 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>
+    pub fn ecdsa_sign_msg<T>(
+        &self,
+        data: &T,
+        private: &sgx_ec256_private_t,
+    ) -> SgxResult<sgx_ec256_signature_t>
     where
         T: Copy + ContiguousMemory,
     {
@@ -2328,7 +2410,11 @@
     ///
     /// 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>
+    pub fn ecdsa_sign_slice<T>(
+        &self,
+        data: &[T],
+        private: &sgx_ec256_private_t,
+    ) -> SgxResult<sgx_ec256_signature_t>
     where
         T: Copy + ContiguousMemory,
     {
@@ -2418,14 +2504,13 @@
         }
 
         let mut result = sgx_generic_ecresult_t::default();
-        let ret = rsgx_ecdsa_verify_msg(data, public, signature, &mut result, *self.handle.borrow());
+        let ret =
+            rsgx_ecdsa_verify_msg(data, public, signature, &mut result, *self.handle.borrow());
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                match result {
-                    sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
-                    _ => Ok(false),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match result {
+                sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2447,14 +2532,13 @@
         }
 
         let mut result = sgx_generic_ecresult_t::default();
-        let ret = rsgx_ecdsa_verify_slice(data, public, signature, &mut result, *self.handle.borrow());
+        let ret =
+            rsgx_ecdsa_verify_slice(data, public, signature, &mut result, *self.handle.borrow());
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                match result {
-                    sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
-                    _ => Ok(false),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match result {
+                sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2470,14 +2554,13 @@
         }
 
         let mut result = sgx_generic_ecresult_t::default();
-        let ret = rsgx_ecdsa_verify_hash(hash, public, signature, &mut result, *self.handle.borrow());
+        let ret =
+            rsgx_ecdsa_verify_hash(hash, public, signature, &mut result, *self.handle.borrow());
         match ret {
-            sgx_status_t::SGX_SUCCESS => {
-                match result {
-                    sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
-                    _ => Ok(false),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match result {
+                sgx_generic_ecresult_t::SGX_EC_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2586,7 +2669,10 @@
 ///
 /// 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>
+pub fn rsgx_rsa3072_sign_msg<T>(
+    data: &T,
+    key: &sgx_rsa3072_key_t,
+) -> SgxResult<sgx_rsa3072_signature_t>
 where
     T: Copy + ContiguousMemory,
 {
@@ -2594,7 +2680,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2616,7 +2702,10 @@
 ///
 /// 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>
+pub fn rsgx_rsa3072_sign_slice<T>(
+    data: &[T],
+    key: &sgx_rsa3072_key_t,
+) -> SgxResult<sgx_rsa3072_signature_t>
 where
     T: Copy + ContiguousMemory,
 {
@@ -2624,7 +2713,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2707,7 +2796,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2721,12 +2810,10 @@
             &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),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match verify {
+                sgx_rsa_result_t::SGX_RSA_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2747,7 +2834,7 @@
     if size == 0 {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if size > u32::max_value() as usize {
+    if size > u32::MAX as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2761,12 +2848,10 @@
             &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),
-                }
-            }
+            sgx_status_t::SGX_SUCCESS => match verify {
+                sgx_rsa_result_t::SGX_RSA_VALID => Ok(true),
+                _ => Ok(false),
+            },
             _ => Err(ret),
         }
     }
@@ -2788,28 +2873,28 @@
     if (n_byte_size <= 0) || (e_byte_size <= 0) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (n.is_empty()) || (n.len() > i32::max_value() as usize) {
+    if (n.is_empty()) || (n.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (d.is_empty()) || (d.len() > i32::max_value() as usize) {
+    if (d.is_empty()) || (d.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (p.is_empty()) || (p.len() > i32::max_value() as usize) {
+    if (p.is_empty()) || (p.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (q.is_empty()) || (q.len() > i32::max_value() as usize) {
+    if (q.is_empty()) || (q.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (dmp1.is_empty()) || (dmp1.len() > i32::max_value() as usize) {
+    if (dmp1.is_empty()) || (dmp1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (dmq1.is_empty()) || (dmq1.len() > i32::max_value() as usize) {
+    if (dmq1.is_empty()) || (dmq1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (iqmp.is_empty()) || (iqmp.len() > i32::max_value() as usize) {
+    if (iqmp.is_empty()) || (iqmp.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -2847,22 +2932,22 @@
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (p.is_empty()) || (p.len() > i32::max_value() as usize) {
+    if (p.is_empty()) || (p.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (q.is_empty()) || (q.len() > i32::max_value() as usize) {
+    if (q.is_empty()) || (q.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (dmp1.is_empty()) || (dmp1.len() > i32::max_value() as usize) {
+    if (dmp1.is_empty()) || (dmp1.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (dmq1.is_empty()) || (dmq1.len() > i32::max_value() as usize) {
+    if (dmq1.is_empty()) || (dmq1.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (iqmp.is_empty()) || (iqmp.len() > i32::max_value() as usize) {
+    if (iqmp.is_empty()) || (iqmp.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -2893,13 +2978,13 @@
     if (n_size <= 0) || (e_size <= 0) || (d_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (n.is_empty()) || (n.len() > i32::max_value() as usize) {
+    if (n.is_empty()) || (n.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (d.is_empty()) || (d.len() > i32::max_value() as usize) {
+    if (d.is_empty()) || (d.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -2926,10 +3011,10 @@
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (n.is_empty()) || (n.len() > i32::max_value() as usize) {
+    if (n.is_empty()) || (n.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if (e.is_empty()) || (e.len() > i32::max_value() as usize) {
+    if (e.is_empty()) || (e.len() > i32::MAX as usize) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -2953,9 +3038,7 @@
     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)
-    }
+    unsafe { sgx_free_rsa_key(rsa_key, key_type, mod_size, exp_size) }
 }
 
 fn rsgx_rsa_priv_decrypt_sha256(
@@ -2967,7 +3050,7 @@
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if * out_len != 0 && out_data.len() != * out_len {
+    if *out_len != 0 && out_data.len() != *out_len {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -2996,7 +3079,7 @@
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
-    if * out_len != 0 && out_data.len() != * out_len {
+    if *out_len != 0 && out_data.len() != *out_len {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
@@ -3128,12 +3211,7 @@
             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(()),
             _ => Err(ret),
@@ -3199,24 +3277,13 @@
         }
     }
 
-    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);
@@ -3238,12 +3305,7 @@
             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(()),
             _ => Err(ret),
@@ -3332,13 +3394,13 @@
     sgx_nistp256_r_m1: &[u8],
     out_key: &mut [u8],
 ) -> SgxError {
-    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (out_key.is_empty()) || (out_key.len() > i32::max_value() as usize) {
+    if (out_key.is_empty()) || (out_key.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -3374,11 +3436,14 @@
     }
 }
 
-pub fn rsgx_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxResult<sgx_ec256_private_t> {
-    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+pub fn rsgx_ecc256_priv_key(
+    hash_drg: &[u8],
+    sgx_nistp256_r_m1: &[u8],
+) -> SgxResult<sgx_ec256_private_t> {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
-    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::MAX as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
 
@@ -3424,12 +3489,16 @@
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let aad_len = aad.len();
-    if aad_len > u32::max_value() as usize {
+    if aad_len > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
     unsafe {
-        let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
+        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(),
@@ -3447,14 +3516,14 @@
     aes_gcm_state: sgx_aes_state_handle_t,
 ) -> sgx_status_t {
     let src_len = src.len();
-    if src_len > u32::max_value() as usize {
+    if src_len > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if src_len == 0 {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let dst_len = dst.len();
-    if dst_len > u32::max_value() as usize {
+    if dst_len > u32::MAX as usize {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if dst_len == 0 || dst_len < src_len {
@@ -3476,7 +3545,10 @@
     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)
+        sgx_aes_gcm128_enc_get_mac(
+            mac as *mut sgx_aes_gcm_128bit_tag_t as *mut u8,
+            aes_gcm_state,
+        )
     }
 }
 
@@ -3491,7 +3563,7 @@
 
 impl SgxAesHandle {
     pub fn new() -> SgxAesHandle {
-        SgxAesHandle{
+        SgxAesHandle {
             handle: RefCell::new(ptr::null_mut() as sgx_aes_state_handle_t),
             initflag: Cell::new(false),
         }
@@ -3563,7 +3635,6 @@
 
 impl Drop for SgxAesHandle {
     fn drop(&mut self) {
-       let _ = self.close();
+        let _ = self.close();
     }
 }
-
diff --git a/sgx_ucrypto/src/lib.rs b/sgx_ucrypto/src/lib.rs
index ff4de82..e84be24 100644
--- a/sgx_ucrypto/src/lib.rs
+++ b/sgx_ucrypto/src/lib.rs
@@ -25,10 +25,10 @@
 #![allow(non_snake_case)]
 #![allow(clippy::too_many_arguments)]
 
-extern crate sgx_types;
 extern crate libc;
-extern crate rdrand;
 extern crate rand_core;
+extern crate rdrand;
+extern crate sgx_types;
 
 mod util;
 pub use util::*;
diff --git a/sgx_ucrypto/src/util.rs b/sgx_ucrypto/src/util.rs
index a7ea69b..ee4ebcd 100644
--- a/sgx_ucrypto/src/util.rs
+++ b/sgx_ucrypto/src/util.rs
@@ -1,9 +1,9 @@
-use libc::{size_t, c_int, c_void};
-use libc::{EINVAL, E2BIG, EOVERFLOW};
 use libc::memset;
-use sgx_types::sgx_status_t;
+use libc::{c_int, c_void, size_t};
+use libc::{E2BIG, EINVAL, EOVERFLOW};
 use rand_core::RngCore;
 use rdrand;
+use sgx_types::sgx_status_t;
 use std::ptr::copy_nonoverlapping;
 use std::slice;
 
@@ -42,11 +42,7 @@
 }
 
 #[no_mangle]
-pub unsafe extern "C" fn consttime_memequal(
-    b1: *const u8,
-    b2: *const u8,
-    l: usize,
-) -> i32 {
+pub unsafe extern "C" fn consttime_memequal(b1: *const u8, b2: *const u8, l: usize) -> i32 {
     let mut res: i32 = 0;
     let mut len = l;
     let p1 = slice::from_raw_parts(b1, l);
@@ -68,7 +64,6 @@
     1 & ((res - 1) >> 8)
 }
 
-
 #[no_mangle]
 pub unsafe extern "C" fn sgx_read_rand(rand: *mut u8, len: size_t) -> sgx_status_t {
     if rand.is_null() || len == 0 || len > std::u32::MAX as usize {
@@ -85,9 +80,12 @@
 pub fn hex_to_bytes(hex_string: &str) -> Vec<u8> {
     let input_chars: Vec<_> = hex_string.chars().collect();
 
-    input_chars.chunks(2).map(|chunk| {
-        let first_byte = chunk[0].to_digit(16).unwrap();
-        let second_byte = chunk[1].to_digit(16).unwrap();
-        ((first_byte << 4) | second_byte) as u8
-    }).collect()
+    input_chars
+        .chunks(2)
+        .map(|chunk| {
+            let first_byte = chunk[0].to_digit(16).unwrap();
+            let second_byte = chunk[1].to_digit(16).unwrap();
+            ((first_byte << 4) | second_byte) as u8
+        })
+        .collect()
 }
diff --git a/sgx_unwind/libunwind/autogen-linux.sh b/sgx_unwind/libunwind/autogen-linux.sh
old mode 100755
new mode 100644
diff --git a/sgx_urts/src/asyncio.rs b/sgx_urts/src/asyncio.rs
index ab68969..80254a0 100644
--- a/sgx_urts/src/asyncio.rs
+++ b/sgx_urts/src/asyncio.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use libc::{self, c_int, epoll_event, nfds_t, pollfd};
 use std::io::Error;
-use libc::{self, c_int, pollfd, nfds_t, epoll_event};
 
 #[no_mangle]
 pub extern "C" fn u_poll_ocall(
@@ -31,7 +31,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -44,7 +46,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -63,20 +67,30 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_epoll_wait_ocall(error: *mut c_int, epfd: c_int, events: *mut epoll_event, maxevents: c_int, timeout: c_int) -> c_int {
+pub extern "C" fn u_epoll_wait_ocall(
+    error: *mut c_int,
+    epfd: c_int,
+    events: *mut epoll_event,
+    maxevents: c_int,
+    timeout: c_int,
+) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::epoll_wait(epfd, events, maxevents, timeout) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
diff --git a/sgx_urts/src/enclave.rs b/sgx_urts/src/enclave.rs
index e4f3502..704ceb6 100644
--- a/sgx_urts/src/enclave.rs
+++ b/sgx_urts/src/enclave.rs
@@ -16,11 +16,11 @@
 // under the License..
 
 use sgx_types::*;
-use std::ptr;
-use std::path::{Path, PathBuf};
-use std::ffi::{CString, CStr};
+use std::ffi::{CStr, CString};
 use std::io;
 use std::os::unix::ffi::OsStrExt;
+use std::path::{Path, PathBuf};
+use std::ptr;
 
 ///
 /// Loads the enclave using its file name and initializes it using a launch token.
@@ -438,8 +438,9 @@
     let mut us_config = sgx_uswitchless_config_t::default();
     us_config.num_tworkers = num_tworkers;
     us_config.num_uworkers = num_uworkers;
-    let mut enclave_ex_p : [*const c_void ;32] = [ptr::null(); 32];
-    enclave_ex_p[SGX_CREATE_ENCLAVE_EX_SWITCHLESS_BIT_IDX] = &us_config as *const sgx_uswitchless_config_t as *const c_void;
+    let mut enclave_ex_p: [*const c_void; 32] = [ptr::null(); 32];
+    enclave_ex_p[SGX_CREATE_ENCLAVE_EX_SWITCHLESS_BIT_IDX] =
+        &us_config as *const sgx_uswitchless_config_t as *const c_void;
 
     let mut enclave_id: sgx_enclave_id_t = 0;
     let ret = unsafe {
@@ -536,7 +537,8 @@
 
 pub fn rsgx_get_target_info(enclave_id: sgx_enclave_id_t) -> SgxResult<sgx_target_info_t> {
     let mut target_info = sgx_target_info_t::default();
-    let ret = unsafe { sgx_get_target_info(enclave_id, &mut target_info as *mut sgx_target_info_t) };
+    let ret =
+        unsafe { sgx_get_target_info(enclave_id, &mut target_info as *mut sgx_target_info_t) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(target_info),
         _ => Err(ret),
@@ -564,19 +566,18 @@
     ) -> SgxResult<SgxEnclave> {
         let path: CString =
             cstr(file_name.as_ref()).map_err(|_| sgx_status_t::SGX_ERROR_INVALID_ENCLAVE)?;
-        let enclave =
-            rsgx_create_enclave(
-                path.as_c_str(),
-                debug,
-                launch_token,
-                launch_token_updated,
-                misc_attr,
-            )
-            .map(|eid| SgxEnclave {
-                id: eid,
-                debug,
-                path: file_name.as_ref().to_owned()
-            })?;
+        let enclave = rsgx_create_enclave(
+            path.as_c_str(),
+            debug,
+            launch_token,
+            launch_token_updated,
+            misc_attr,
+        )
+        .map(|eid| SgxEnclave {
+            id: eid,
+            debug,
+            path: file_name.as_ref().to_owned(),
+        })?;
 
         enclave.init();
         Ok(enclave)
@@ -591,21 +592,20 @@
         sealed_key: *const sgx_sealed_data_t,
     ) -> SgxResult<SgxEnclave> {
         let path: CString =
-            cstr(file_name.as_ref()) .map_err(|_| sgx_status_t::SGX_ERROR_INVALID_ENCLAVE)?;
-        let enclave =
-            rsgx_create_encrypted_enclave(
-                path.as_c_str(),
-                debug,
-                launch_token,
-                launch_token_updated,
-                misc_attr,
-                sealed_key,
-            )
-            .map(|eid| SgxEnclave {
-                id: eid,
-                debug,
-                path: file_name.as_ref().to_owned()
-            })?;
+            cstr(file_name.as_ref()).map_err(|_| sgx_status_t::SGX_ERROR_INVALID_ENCLAVE)?;
+        let enclave = rsgx_create_encrypted_enclave(
+            path.as_c_str(),
+            debug,
+            launch_token,
+            launch_token_updated,
+            misc_attr,
+            sealed_key,
+        )
+        .map(|eid| SgxEnclave {
+            id: eid,
+            debug,
+            path: file_name.as_ref().to_owned(),
+        })?;
 
         enclave.init();
         Ok(enclave)
@@ -622,21 +622,20 @@
     ) -> SgxResult<SgxEnclave> {
         let path: CString =
             cstr(file_name.as_ref()).map_err(|_| sgx_status_t::SGX_ERROR_INVALID_ENCLAVE)?;
-        let enclave =
-            rsgx_create_enclave_with_workers(
-                path.as_c_str(),
-                debug,
-                launch_token,
-                launch_token_updated,
-                misc_attr,
-                num_uworkers,
-                num_tworkers,
-            )
-            .map(|eid| SgxEnclave {
-                id: eid,
-                debug,
-                path: file_name.as_ref().to_owned()
-            })?;
+        let enclave = rsgx_create_enclave_with_workers(
+            path.as_c_str(),
+            debug,
+            launch_token,
+            launch_token_updated,
+            misc_attr,
+            num_uworkers,
+            num_tworkers,
+        )
+        .map(|eid| SgxEnclave {
+            id: eid,
+            debug,
+            path: file_name.as_ref().to_owned(),
+        })?;
 
         enclave.init();
         Ok(enclave)
@@ -649,19 +648,18 @@
         ex_features: u32,
         ex_features_p: &[*const c_void; 32],
     ) -> SgxResult<SgxEnclave> {
-        let enclave =
-            rsgx_create_enclave_from_buffer_ex(
-                buffer,
-                debug,
-                misc_attr,
-                ex_features,
-                ex_features_p,
-            )
-            .map(|eid| SgxEnclave {
-                id: eid,
-                debug,
-                path: PathBuf::new()
-            })?;
+        let enclave = rsgx_create_enclave_from_buffer_ex(
+            buffer,
+            debug,
+            misc_attr,
+            ex_features,
+            ex_features_p,
+        )
+        .map(|eid| SgxEnclave {
+            id: eid,
+            debug,
+            path: PathBuf::new(),
+        })?;
 
         enclave.init();
         Ok(enclave)
@@ -687,7 +685,9 @@
             extern "C" {
                 fn t_global_exit_ecall(eid: sgx_enclave_id_t) -> sgx_status_t;
             }
-            unsafe { let _ = t_global_exit_ecall(self.id); }
+            unsafe {
+                let _ = t_global_exit_ecall(self.id);
+            }
         }
     }
 
@@ -695,7 +695,12 @@
         #[cfg(feature = "global_init")]
         {
             extern "C" {
-                fn t_global_init_ecall(eid: sgx_enclave_id_t, id: u64, path: *const u8, len: usize) -> sgx_status_t;
+                fn t_global_init_ecall(
+                    eid: sgx_enclave_id_t,
+                    id: u64,
+                    path: *const u8,
+                    len: usize,
+                ) -> sgx_status_t;
             }
             unsafe {
                 let _ = t_global_init_ecall(
diff --git a/sgx_urts/src/env.rs b/sgx_urts/src/env.rs
index fc8199d..3816d3f 100644
--- a/sgx_urts/src/env.rs
+++ b/sgx_urts/src/env.rs
@@ -15,17 +15,19 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use libc::{self, c_char, c_int, passwd, size_t, uid_t};
 use std::io::Error;
-use libc::{self, c_char, c_int, uid_t, size_t, passwd};
 
 #[no_mangle]
 pub extern "C" fn u_getuid_ocall() -> uid_t {
-     unsafe { libc::getuid()}
+    unsafe { libc::getuid() }
 }
 
 #[no_mangle]
 pub extern "C" fn u_environ_ocall() -> *const *const c_char {
-    extern { static environ: *const *const c_char; }
+    extern "C" {
+        static environ: *const *const c_char;
+    }
     unsafe { environ }
 }
 
@@ -47,7 +49,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -60,20 +64,24 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn  u_getcwd_ocall(error: *mut c_int, buf: *mut c_char, size: size_t) -> *mut c_char {
+pub extern "C" fn u_getcwd_ocall(error: *mut c_int, buf: *mut c_char, size: size_t) -> *mut c_char {
     let mut errno = 0;
     let ret = unsafe { libc::getcwd(buf, size) };
     if ret.is_null() {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
-     if !error.is_null() {
-        unsafe { *error = errno; }
+    if !error.is_null() {
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -85,8 +93,10 @@
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
-     if !error.is_null() {
-        unsafe { *error = errno; }
+    if !error.is_null() {
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -107,27 +117,32 @@
                 let mut temp_pwd = &mut *pwd;
                 let p = -1_isize as usize;
                 if !temp_pwd.pw_name.is_null() {
-                    temp_pwd.pw_name = usize::checked_sub(temp_pwd.pw_name as _, buf as _).unwrap_or(p) as *mut c_char;
+                    temp_pwd.pw_name = usize::checked_sub(temp_pwd.pw_name as _, buf as _)
+                        .unwrap_or(p) as *mut c_char;
                 } else {
                     temp_pwd.pw_name = p as *mut c_char;
                 }
                 if !temp_pwd.pw_passwd.is_null() {
-                    temp_pwd.pw_passwd = usize::checked_sub(temp_pwd.pw_passwd as _, buf as _).unwrap_or(p) as *mut c_char;
+                    temp_pwd.pw_passwd = usize::checked_sub(temp_pwd.pw_passwd as _, buf as _)
+                        .unwrap_or(p) as *mut c_char;
                 } else {
                     temp_pwd.pw_passwd = p as *mut c_char;
                 }
                 if !temp_pwd.pw_gecos.is_null() {
-                    temp_pwd.pw_gecos = usize::checked_sub(temp_pwd.pw_gecos as _, buf as _).unwrap_or(p) as *mut c_char;
+                    temp_pwd.pw_gecos = usize::checked_sub(temp_pwd.pw_gecos as _, buf as _)
+                        .unwrap_or(p) as *mut c_char;
                 } else {
                     temp_pwd.pw_gecos = p as *mut c_char;
                 }
                 if !temp_pwd.pw_dir.is_null() {
-                    temp_pwd.pw_dir = usize::checked_sub(temp_pwd.pw_dir as _, buf as _).unwrap_or(p) as *mut c_char;
+                    temp_pwd.pw_dir = usize::checked_sub(temp_pwd.pw_dir as _, buf as _)
+                        .unwrap_or(p) as *mut c_char;
                 } else {
                     temp_pwd.pw_dir = p as *mut c_char;
                 }
                 if !temp_pwd.pw_shell.is_null() {
-                    temp_pwd.pw_shell = usize::checked_sub(temp_pwd.pw_shell as _, buf as _).unwrap_or(p) as *mut c_char;
+                    temp_pwd.pw_shell = usize::checked_sub(temp_pwd.pw_shell as _, buf as _)
+                        .unwrap_or(p) as *mut c_char;
                 } else {
                     temp_pwd.pw_shell = p as *mut c_char;
                 }
diff --git a/sgx_urts/src/event.rs b/sgx_urts/src/event.rs
index 61199a0..8b1f06e 100644
--- a/sgx_urts/src/event.rs
+++ b/sgx_urts/src/event.rs
@@ -1,10 +1,10 @@
-use std::sync::Mutex;
-use std::sync::atomic::{AtomicI32, Ordering};
+use libc::timespec;
 use libc::{self, c_int, c_void};
 use std::io::Error;
 use std::slice;
+use std::sync::atomic::{AtomicI32, Ordering};
+use std::sync::Mutex;
 use std::sync::Once;
-use libc::timespec;
 
 static mut GLOBAL_TCS_CACHE: Option<SgxTcsInfoCache> = None;
 static INIT: Once = Once::new();
@@ -18,7 +18,7 @@
 
 impl SeEvent {
     pub fn new() -> SeEvent {
-        SeEvent{
+        SeEvent {
             event: AtomicI32::new(0),
         }
     }
@@ -49,17 +49,7 @@
 
     pub fn wait(&self) -> i32 {
         if self.event.fetch_add(-1, Ordering::SeqCst) == 0 {
-            let ret = unsafe {
-                libc::syscall(
-                    libc::SYS_futex,
-                    self,
-                    FUTEX_WAIT,
-                    -1,
-                    0,
-                    0,
-                    0,
-                )
-            };
+            let ret = unsafe { libc::syscall(libc::SYS_futex, self, FUTEX_WAIT, -1, 0, 0, 0) };
             if ret < 0 {
                 let _err = Error::last_os_error().raw_os_error().unwrap_or(0);
             }
@@ -69,17 +59,7 @@
 
     pub fn wake(&self) -> i32 {
         if self.event.fetch_add(1, Ordering::SeqCst) != 0 {
-           unsafe {
-               libc::syscall(
-                   libc::SYS_futex,
-                    self,
-                    FUTEX_WAKE,
-                    1,
-                    0,
-                    0,
-                    0,
-                )
-            };
+            unsafe { libc::syscall(libc::SYS_futex, self, FUTEX_WAKE, 1, 0, 0, 0) };
         }
         0
     }
@@ -91,7 +71,7 @@
 }
 
 struct SgxTcsInfoCache<'a> {
-    cache: Mutex<Vec<SgxTcsInfo<'a>>>
+    cache: Mutex<Vec<SgxTcsInfo<'a>>>,
 }
 
 impl<'a> SgxTcsInfoCache<'a> {
@@ -113,8 +93,8 @@
                     se_event: event,
                 });
                 let len = v.len();
-                v[len -1].se_event
-            },
+                v[len - 1].se_event
+            }
         }
     }
 }
@@ -135,29 +115,41 @@
 pub extern "C" fn u_thread_set_event_ocall(error: *mut c_int, tcs: *const c_void) -> c_int {
     if tcs.is_null() {
         if !error.is_null() {
-            unsafe { *error = libc::EINVAL; }
+            unsafe {
+                *error = libc::EINVAL;
+            }
         }
         return -1;
     }
     let result = get_tcs_event(tcs as usize).wake();
     if result != 0 {
         if !error.is_null() {
-            unsafe { *error = Error::last_os_error().raw_os_error().unwrap_or(0); }
+            unsafe {
+                *error = Error::last_os_error().raw_os_error().unwrap_or(0);
+            }
         }
         -1
     } else {
         if !error.is_null() {
-            unsafe { *error = 0; }
+            unsafe {
+                *error = 0;
+            }
         }
         result as c_int
     }
 }
 
 #[no_mangle]
-pub extern "C" fn u_thread_wait_event_ocall(error: *mut c_int, tcs: *const c_void, timeout: *const timespec) -> c_int {
+pub extern "C" fn u_thread_wait_event_ocall(
+    error: *mut c_int,
+    tcs: *const c_void,
+    timeout: *const timespec,
+) -> c_int {
     if tcs.is_null() {
         if !error.is_null() {
-            unsafe { *error = libc::EINVAL; }
+            unsafe {
+                *error = libc::EINVAL;
+            }
         }
         return -1;
     }
@@ -165,16 +157,20 @@
     let result = if timeout.is_null() {
         get_tcs_event(tcs as usize).wait()
     } else {
-        get_tcs_event(tcs as usize).wait_timeout(unsafe{&*timeout})
+        get_tcs_event(tcs as usize).wait_timeout(unsafe { &*timeout })
     };
     if result != 0 {
         if !error.is_null() {
-            unsafe { *error = Error::last_os_error().raw_os_error().unwrap_or(0); }
+            unsafe {
+                *error = Error::last_os_error().raw_os_error().unwrap_or(0);
+            }
         }
         -1
     } else {
         if !error.is_null() {
-            unsafe { *error = 0; }
+            unsafe {
+                *error = 0;
+            }
         }
         result as c_int
     }
@@ -188,7 +184,9 @@
 ) -> c_int {
     if tcss.is_null() {
         if !error.is_null() {
-            unsafe { *error = libc::EINVAL; }
+            unsafe {
+                *error = libc::EINVAL;
+            }
         }
         return -1;
     }
@@ -199,14 +197,18 @@
         result = get_tcs_event(*tcs as usize).wake();
         if result != 0 {
             if !error.is_null() {
-                unsafe { *error = Error::last_os_error().raw_os_error().unwrap_or(0); }
+                unsafe {
+                    *error = Error::last_os_error().raw_os_error().unwrap_or(0);
+                }
             }
             return -1;
         }
     }
 
     if !error.is_null() {
-        unsafe { *error = 0; }
+        unsafe {
+            *error = 0;
+        }
     }
     result as c_int
 }
diff --git a/sgx_urts/src/fd.rs b/sgx_urts/src/fd.rs
index dcef198..cfbf5a3 100644
--- a/sgx_urts/src/fd.rs
+++ b/sgx_urts/src/fd.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use libc::{self, c_int, c_ulong, c_void, iovec, off64_t, size_t, ssize_t};
 use std::io::Error;
-use libc::{self, c_int, c_void, size_t, ssize_t, off64_t, c_ulong, iovec};
 
 #[no_mangle]
 pub extern "C" fn u_read_ocall(
@@ -31,7 +31,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -50,7 +52,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -68,7 +72,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -87,7 +93,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -105,7 +113,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -124,7 +134,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -142,7 +154,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -161,24 +175,24 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_fcntl_arg0_ocall(
-    error: *mut c_int,
-    fd: c_int,
-    cmd: c_int,
-) -> c_int {
+pub extern "C" fn u_fcntl_arg0_ocall(error: *mut c_int, fd: c_int, cmd: c_int) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::fcntl(fd, cmd) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -196,24 +210,24 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_ioctl_arg0_ocall(
-    error: *mut c_int,
-    fd: c_int,
-    request: c_int,
-) -> c_int {
+pub extern "C" fn u_ioctl_arg0_ocall(error: *mut c_int, fd: c_int, request: c_int) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::ioctl(fd, request as c_ulong) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -231,7 +245,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -244,7 +260,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
diff --git a/sgx_urts/src/file.rs b/sgx_urts/src/file.rs
index 4cb22a9..85edd82 100644
--- a/sgx_urts/src/file.rs
+++ b/sgx_urts/src/file.rs
@@ -15,23 +15,23 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use std::ptr;
+use libc::{
+    self, c_char, c_int, dirent64, mode_t, off64_t, off_t, size_t, ssize_t, stat, stat64, DIR,
+};
 use std::io::Error;
-use libc::{self, c_int, c_char, size_t, ssize_t, off_t, off64_t, mode_t, stat, stat64, DIR, dirent64};
+use std::ptr;
 
 #[no_mangle]
-pub extern "C" fn u_open_ocall(
-    error: *mut c_int,
-    pathname: *const c_char,
-    flags: c_int,
-) -> c_int {
+pub extern "C" fn u_open_ocall(error: *mut c_int, pathname: *const c_char, flags: c_int) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::open(pathname, flags) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -49,58 +49,54 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_fstat_ocall(
-    error: *mut c_int,
-    fd: c_int,
-    buf: *mut stat,
-) -> c_int {
+pub extern "C" fn u_fstat_ocall(error: *mut c_int, fd: c_int, buf: *mut stat) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::fstat(fd, buf) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_fstat64_ocall(
-    error: *mut c_int,
-    fd: c_int,
-    buf: *mut stat64,
-) -> c_int {
+pub extern "C" fn u_fstat64_ocall(error: *mut c_int, fd: c_int, buf: *mut stat64) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::fstat64(fd, buf) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_stat_ocall(
-    error: *mut c_int,
-    path: *const c_char,
-    buf: *mut stat,
-) -> c_int {
+pub extern "C" fn u_stat_ocall(error: *mut c_int, path: *const c_char, buf: *mut stat) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::stat(path, buf) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -117,24 +113,24 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_lstat_ocall(
-    error: *mut c_int,
-    path: *const c_char,
-    buf: *mut stat,
-) -> c_int {
+pub extern "C" fn u_lstat_ocall(error: *mut c_int, path: *const c_char, buf: *mut stat) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::lstat(path, buf) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -151,7 +147,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -169,7 +167,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -187,58 +187,54 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_ftruncate_ocall(
-    error: *mut c_int,
-    fd: c_int,
-    length: off_t,
-) -> c_int {
+pub extern "C" fn u_ftruncate_ocall(error: *mut c_int, fd: c_int, length: off_t) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::ftruncate(fd, length) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_ftruncate64_ocall(
-    error: *mut c_int,
-    fd: c_int,
-    length: off64_t,
-) -> c_int {
+pub extern "C" fn u_ftruncate64_ocall(error: *mut c_int, fd: c_int, length: off64_t) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::ftruncate64(fd, length) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_truncate_ocall(
-    error: *mut c_int,
-    path: *const c_char,
-    length: off_t,
-) -> c_int {
+pub extern "C" fn u_truncate_ocall(error: *mut c_int, path: *const c_char, length: off_t) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::truncate(path, length) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -255,7 +251,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -268,7 +266,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -281,7 +281,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -294,7 +296,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -307,7 +311,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -324,7 +330,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -341,24 +349,24 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_chmod_ocall(
-    error: *mut c_int,
-    path: *const c_char,
-    mode: mode_t,
-) -> c_int {
+pub extern "C" fn u_chmod_ocall(error: *mut c_int, path: *const c_char, mode: mode_t) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::chmod(path, mode) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -376,7 +384,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -393,40 +403,39 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_realpath_ocall(
-    error: *mut c_int,
-    pathname: *const c_char,
-) -> *mut c_char {
+pub extern "C" fn u_realpath_ocall(error: *mut c_int, pathname: *const c_char) -> *mut c_char {
     let mut errno = 0;
     let ret = unsafe { libc::realpath(pathname, ptr::null_mut()) };
     if ret.is_null() {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_mkdir_ocall(
-    error: *mut c_int,
-    pathname: *const c_char,
-    mode: mode_t,
-) -> c_int {
+pub extern "C" fn u_mkdir_ocall(error: *mut c_int, pathname: *const c_char, mode: mode_t) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::mkdir(pathname, mode) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -439,7 +448,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -452,7 +463,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -474,7 +487,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -487,7 +502,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -506,7 +523,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
diff --git a/sgx_urts/src/lib.rs b/sgx_urts/src/lib.rs
index 6c86dbd..08616ec 100644
--- a/sgx_urts/src/lib.rs
+++ b/sgx_urts/src/lib.rs
@@ -15,24 +15,25 @@
 // specific language governing permissions and limitations
 // under the License..
 
+#![feature(linkage)]
 #![allow(clippy::not_unsafe_ptr_arg_deref)]
+
 extern crate libc;
 extern crate sgx_types;
 
-mod enclave;
-pub mod mem;
-pub mod time;
-pub mod fd;
-pub mod file;
-pub mod socket;
 pub mod asyncio;
 pub mod env;
-pub mod sys;
-pub mod pipe;
 pub mod event;
-pub mod thread;
+pub mod fd;
+pub mod file;
+pub mod mem;
 pub mod net;
-#[cfg(feature = "signal")]
-pub mod signal;
+pub mod pipe;
 pub mod process;
+pub mod signal;
+pub mod socket;
+pub mod sys;
+pub mod thread;
+pub mod time;
+mod enclave;
 pub use enclave::*;
diff --git a/sgx_urts/src/mem.rs b/sgx_urts/src/mem.rs
index d1750f1..3b22319 100644
--- a/sgx_urts/src/mem.rs
+++ b/sgx_urts/src/mem.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use libc::{self, c_int, c_void, off_t, size_t};
 use std::io::Error;
-use libc::{self, c_int, c_void, size_t, off_t};
 
 #[no_mangle]
 pub extern "C" fn u_malloc_ocall(error: *mut c_int, size: size_t) -> *mut c_void {
@@ -26,7 +26,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -52,24 +54,24 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_munmap_ocall(
-    error: *mut c_int,
-    start: *mut c_void,
-    length: size_t,
-) -> c_int {
+pub extern "C" fn u_munmap_ocall(error: *mut c_int, start: *mut c_void, length: size_t) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::munmap(start, length) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -87,7 +89,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -105,7 +109,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
diff --git a/sgx_urts/src/net.rs b/sgx_urts/src/net.rs
index b6a229b..765da79 100644
--- a/sgx_urts/src/net.rs
+++ b/sgx_urts/src/net.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use libc::{self, addrinfo, c_char, c_int};
 use std::io::Error;
-use libc::{self, c_int, c_char, addrinfo};
 
 #[no_mangle]
 pub extern "C" fn u_getaddrinfo_ocall(
@@ -32,13 +32,15 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_freeaddrinfo_ocall(res: *mut addrinfo ) {
+pub extern "C" fn u_freeaddrinfo_ocall(res: *mut addrinfo) {
     unsafe { libc::freeaddrinfo(res) }
 }
 
diff --git a/sgx_urts/src/pipe.rs b/sgx_urts/src/pipe.rs
index 22e65b7..9f53eec 100644
--- a/sgx_urts/src/pipe.rs
+++ b/sgx_urts/src/pipe.rs
@@ -15,38 +15,35 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use std::io::Error;
 use libc::{self, c_int};
+use std::io::Error;
 
 #[no_mangle]
-pub extern "C" fn u_pipe_ocall(
-    error: *mut c_int,
-    fds: *mut c_int,
-) -> c_int {
+pub extern "C" fn u_pipe_ocall(error: *mut c_int, fds: *mut c_int) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::pipe(fds) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_pipe2_ocall(
-    error: *mut c_int,
-    fds: *mut c_int,
-    flags: c_int,
-) -> c_int {
+pub extern "C" fn u_pipe2_ocall(error: *mut c_int, fds: *mut c_int, flags: c_int) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::pipe2(fds, flags) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
diff --git a/sgx_urts/src/signal.rs b/sgx_urts/src/signal.rs
index d1b356f..96dd8fe 100644
--- a/sgx_urts/src/signal.rs
+++ b/sgx_urts/src/signal.rs
@@ -15,33 +15,36 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use std::io::Error;
-use std::collections::HashMap;
-use std::sync::{Mutex, Once};
-use std::mem;
-use libc::{self, c_int, c_void, sigset_t, siginfo_t};
-use libc::{signal, sigprocmask, sigaction, sigemptyset, sigfillset, raise};
-use libc::{SIG_SETMASK, SA_SIGINFO, SIG_ERR, SIG_DFL};
 use crate::sgx_types::{sgx_enclave_id_t, sgx_status_t};
+use libc::{self, c_int, c_void, sigaction, siginfo_t, sigset_t};
+use libc::{SA_SIGINFO, SIG_DFL, SIG_ERR, SIG_SETMASK};
+use std::collections::HashMap;
+use std::io::Error;
+use std::mem;
+use std::sync::{Mutex, Once};
 
 static DISPATCHER_INIT: Once = Once::new();
 static mut GLOBAL_DATA: Option<GlobalData> = None;
 
-pub const SIGRTMIN: c_int = 32;
-pub const SIGRTMAX: c_int = 64;
-pub const NSIG: c_int = SIGRTMAX + 1;
+#[allow(dead_code)]
+const SIGRTMIN: c_int = 32;
+const SIGRTMAX: c_int = 64;
+const NSIG: c_int = SIGRTMAX + 1;
 
-extern "C" {
-    fn t_signal_handler_ecall(eid: sgx_enclave_id_t,
-                              retval: *mut c_int,
-                              info: *const siginfo_t) -> sgx_status_t;
+#[linkage = "weak"]
+#[no_mangle]
+extern "C" fn t_signal_handler_ecall(
+    _eid: sgx_enclave_id_t,
+    _retval: *mut c_int,
+    _info: *const siginfo_t,
+) -> sgx_status_t {
+    sgx_status_t::SGX_ERROR_UNEXPECTED
 }
 
 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
 pub struct SigNum(i32);
 
 impl SigNum {
-
     pub fn from_raw(signo: i32) -> Option<SigNum> {
         if signo <= 0 || signo >= NSIG {
             None
@@ -49,32 +52,42 @@
             Some(SigNum(signo))
         }
     }
+
     pub unsafe fn from_raw_uncheck(signo: i32) -> SigNum {
         SigNum(signo)
     }
-    pub fn raw(&self) -> i32 { self.0 }
+
+    pub fn raw(&self) -> i32 {
+        self.0
+    }
 }
 
 #[derive(Copy, Clone)]
 pub struct SigSet(sigset_t);
 
 impl SigSet {
-
     pub fn new() -> SigSet {
         let set = unsafe {
             let mut set: sigset_t = mem::zeroed();
-            sigemptyset(&mut set as *mut sigset_t);
+            libc::sigemptyset(&mut set as *mut sigset_t);
             set
         };
         SigSet(set)
     }
+
     pub fn fill(&mut self) {
         unsafe {
-            sigfillset(&mut self.0 as *mut sigset_t);
+            libc::sigfillset(&mut self.0 as *mut sigset_t);
         }
     }
-    pub unsafe fn from_raw(set: sigset_t) -> SigSet { SigSet(set) }
-    pub fn raw(&self) -> sigset_t { self.0 }
+
+    pub unsafe fn from_raw(set: sigset_t) -> SigSet {
+        SigSet(set)
+    }
+
+    pub fn raw(&self) -> sigset_t {
+        self.0
+    }
 }
 
 struct GlobalData {
@@ -82,10 +95,10 @@
 }
 
 impl GlobalData {
-
     fn get() -> &'static GlobalData {
         unsafe { GLOBAL_DATA.as_ref().unwrap() }
     }
+
     fn ensure() -> &'static GlobalData {
         DISPATCHER_INIT.call_once(|| unsafe {
             GLOBAL_DATA = Some(GlobalData {
@@ -101,57 +114,63 @@
 }
 
 impl SignalDispatcher {
-
-    pub fn new () -> SignalDispatcher {
+    fn new() -> SignalDispatcher {
         SignalDispatcher {
             signal_set: Mutex::new(HashMap::new()),
         }
     }
 
-    pub fn register_signal(&self, signo: SigNum, enclave_id: sgx_enclave_id_t) -> Option<sgx_enclave_id_t> {
-         // Block all signals when registering a signal handler to avoid deadlock.
+    fn register_signal(
+        &self,
+        signo: SigNum,
+        enclave_id: sgx_enclave_id_t,
+    ) -> Option<sgx_enclave_id_t> {
+        // Block all signals when registering a signal handler to avoid deadlock.
         let mut mask = SigSet::new();
         let oldmask = SigSet::new();
         mask.fill();
 
-        unsafe { sigprocmask(SIG_SETMASK, &mask.raw(), &mut oldmask.raw() as *mut sigset_t); }
-        let old = self.signal_set
-            .lock()
-            .unwrap()
-            .insert(signo, enclave_id);
-        unsafe { sigprocmask(SIG_SETMASK, &oldmask.raw(), 0 as *mut sigset_t); }
+        unsafe {
+            libc::sigprocmask(
+                SIG_SETMASK,
+                &mask.raw(),
+                &mut oldmask.raw() as *mut sigset_t,
+            );
+        }
+        let old = self.signal_set.lock().unwrap().insert(signo, enclave_id);
+        unsafe {
+            libc::sigprocmask(SIG_SETMASK, &oldmask.raw(), 0 as *mut sigset_t);
+        }
         old
     }
 
-    pub fn get_eid_for_signal(&self, signo: SigNum) -> Option<sgx_enclave_id_t> {
-        self.signal_set
-            .lock()
-            .unwrap()
-            .get(&signo)
-            .copied()
+    fn get_eid_for_signal(&self, signo: SigNum) -> Option<sgx_enclave_id_t> {
+        self.signal_set.lock().unwrap().get(&signo).copied()
     }
 
-    pub fn deregister_all_signals_for_eid(&self, eid: sgx_enclave_id_t) {
+    fn deregister_all_signals_for_eid(&self, eid: sgx_enclave_id_t) {
         let mut mask = SigSet::new();
         let oldmask = SigSet::new();
         mask.fill();
 
-        unsafe { sigprocmask(SIG_SETMASK, &mask.raw(), &mut oldmask.raw() as *mut sigset_t); }
+        unsafe {
+            libc::sigprocmask(
+                SIG_SETMASK,
+                &mask.raw(),
+                &mut oldmask.raw() as *mut sigset_t,
+            );
+        }
         // If this enclave has registered any signals, deregister them and set the
         // signal handler to the default one.
-        self.signal_set
-            .lock()
-            .unwrap()
-            .retain(|&signum, &mut v| {
-                if v == eid {
-                    unsafe {
-                        if signal(signum.raw(), SIG_DFL) == SIG_ERR {
-                        }
-                    }
-                }
-                v != eid
-            });
-        unsafe { sigprocmask(SIG_SETMASK, &oldmask.raw(), 0 as *mut sigset_t); }
+        self.signal_set.lock().unwrap().retain(|&signum, &mut v| {
+            if v == eid {
+                unsafe { if libc::signal(signum.raw(), SIG_DFL) == SIG_ERR {} }
+            }
+            v != eid
+        });
+        unsafe {
+            libc::sigprocmask(SIG_SETMASK, &oldmask.raw(), 0 as *mut sigset_t);
+        }
     }
 
     unsafe fn handle_signal(
@@ -180,24 +199,14 @@
 
 pub fn deregister_all_signals_for_eid(enclave_id: sgx_enclave_id_t) {
     let global = GlobalData::ensure();
-    global.signal_dispatcher.deregister_all_signals_for_eid(enclave_id);
-}
-
-extern "C" fn handle_signal_entry(signum: c_int, info: *const siginfo_t, ucontext: *const c_void) {
-    let signo = SigNum::from_raw(signum);
-    if info.is_null() || signo.is_none() {
-        return;
-    }
-
-    unsafe {
-        GlobalData::get().signal_dispatcher
-            .handle_signal(signo.unwrap(), &(*info), ucontext);
-    }
+    global
+        .signal_dispatcher
+        .deregister_all_signals_for_eid(enclave_id);
 }
 
 #[no_mangle]
 pub extern "C" fn u_sigaction_ocall(
-    error: * mut c_int,
+    error: *mut c_int,
     signum: c_int,
     act: *const sigaction,
     oldact: *mut sigaction,
@@ -206,8 +215,10 @@
     let mut errno = 0;
     let signo = SigNum::from_raw(signum);
     if signo.is_none() || act.is_null() {
-        if  !error.is_null() {
-            unsafe {  *error = libc::EINVAL; }
+        if !error.is_null() {
+            unsafe {
+                *error = libc::EINVAL;
+            }
         }
         return -1;
     }
@@ -215,7 +226,9 @@
     let e_act = unsafe { &*act };
     let ret = if e_act.sa_sigaction == 0 {
         let global = GlobalData::ensure();
-        global.signal_dispatcher.register_signal(signo.unwrap(), enclave_id);
+        global
+            .signal_dispatcher
+            .register_signal(signo.unwrap(), enclave_id);
 
         type FnSaSigaction = extern "C" fn(c_int, *const siginfo_t, *const c_void);
         let new_act = sigaction {
@@ -227,16 +240,34 @@
             sa_restorer: None,
         };
         let mut old_act: sigaction = unsafe { mem::zeroed() };
-        unsafe { sigaction(signum, &new_act, &mut old_act as *mut sigaction) }
+        unsafe { libc::sigaction(signum, &new_act, &mut old_act as *mut sigaction) }
     } else {
-       unsafe { sigaction(signum, act as *const sigaction, oldact) }
+        unsafe { libc::sigaction(signum, act as *const sigaction, oldact) }
     };
 
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
+    }
+
+    extern "C" fn handle_signal_entry(
+        signum: c_int,
+        info: *const siginfo_t,
+        ucontext: *const c_void,
+    ) {
+        let signo = SigNum::from_raw(signum);
+        if info.is_null() || signo.is_none() {
+            return;
+        }
+        unsafe {
+            GlobalData::get()
+                .signal_dispatcher
+                .handle_signal(signo.unwrap(), &(*info), ucontext);
+        }
     }
     ret
 }
@@ -249,19 +280,21 @@
     oldset: *mut sigset_t,
 ) -> c_int {
     let mut errno = 0;
-    let ret = unsafe { sigprocmask(signum, set, oldset) };
+    let ret = unsafe { libc::sigprocmask(signum, set, oldset) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
 pub extern "C" fn u_raise_ocall(signum: c_int) -> c_int {
-    unsafe { raise(signum) }
+    unsafe { libc::raise(signum) }
 }
 
 #[no_mangle]
diff --git a/sgx_urts/src/socket.rs b/sgx_urts/src/socket.rs
index a97c6cb..d606a1c 100644
--- a/sgx_urts/src/socket.rs
+++ b/sgx_urts/src/socket.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use libc::{self, c_int, c_void, msghdr, size_t, sockaddr, socklen_t, ssize_t};
 use std::io::Error;
-use libc::{self, c_int, c_void, size_t, ssize_t, sockaddr, socklen_t, msghdr};
 
 #[no_mangle]
 pub extern "C" fn u_socket_ocall(
@@ -31,7 +31,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -50,7 +52,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -68,24 +72,24 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
 
 #[no_mangle]
-pub extern "C" fn u_listen_ocall(
-    error: *mut c_int,
-    sockfd: c_int,
-    backlog: c_int,
-) -> c_int {
+pub extern "C" fn u_listen_ocall(error: *mut c_int, sockfd: c_int, backlog: c_int) -> c_int {
     let mut errno = 0;
     let ret = unsafe { libc::listen(sockfd, backlog) };
     if ret < 0 {
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -105,7 +109,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -126,7 +132,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -144,7 +152,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -163,7 +173,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -186,7 +198,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -204,7 +218,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -223,7 +239,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -244,7 +262,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -262,7 +282,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -284,7 +306,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -304,7 +328,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -324,7 +350,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -344,7 +372,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -357,7 +387,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
diff --git a/sgx_urts/src/sys.rs b/sgx_urts/src/sys.rs
index b19bd2c..d9ed3bc 100644
--- a/sgx_urts/src/sys.rs
+++ b/sgx_urts/src/sys.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
+use libc::{self, c_int, c_long, c_ulong, cpu_set_t, pid_t, size_t};
 use std::io::Error;
-use libc::{self, c_int, c_long, c_ulong, size_t, pid_t, cpu_set_t};
 
 #[no_mangle]
 pub extern "C" fn u_sysconf_ocall(error: *mut c_int, name: c_int) -> c_long {
@@ -26,7 +26,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -46,7 +48,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -64,9 +68,11 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
-    ret                                         
+    ret
 }
 
 #[no_mangle]
@@ -82,7 +88,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
-    ret                                         
+    ret
 }
diff --git a/sgx_urts/src/thread.rs b/sgx_urts/src/thread.rs
index b569196..969aaae 100644
--- a/sgx_urts/src/thread.rs
+++ b/sgx_urts/src/thread.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use std::io::Error;
 use libc::{self, c_int, timespec};
+use std::io::Error;
 
 #[no_mangle]
 pub extern "C" fn u_sched_yield_ocall(error: *mut c_int) -> c_int {
@@ -26,7 +26,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
@@ -43,7 +45,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
-    ret                      
+    ret
 }
diff --git a/sgx_urts/src/time.rs b/sgx_urts/src/time.rs
index 971844e..4486309 100644
--- a/sgx_urts/src/time.rs
+++ b/sgx_urts/src/time.rs
@@ -15,8 +15,8 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use std::io::Error;
 use libc::{self, c_int, clockid_t, timespec};
+use std::io::Error;
 
 #[no_mangle]
 pub extern "C" fn u_clock_gettime_ocall(
@@ -30,7 +30,9 @@
         errno = Error::last_os_error().raw_os_error().unwrap_or(0);
     }
     if !error.is_null() {
-        unsafe { *error = errno; }
+        unsafe {
+            *error = errno;
+        }
     }
     ret
 }
diff --git a/sgx_ustdc/Makefile b/sgx_ustdc/Makefile
index 73bfa50..3d78879 100644
--- a/sgx_ustdc/Makefile
+++ b/sgx_ustdc/Makefile
@@ -18,7 +18,7 @@
 include ../buildenv.mk
 
 USTDC_CFLAGS := $(CFLAGS)
-USTDC_CFLAGS += -fPIC -Wno-attributes -I ./inc
+USTDC_CFLAGS += -fPIC -Wno-attributes -I ./inc  -Wno-strict-prototypes -Wno-deprecated-declarations
 SRCS := $(wildcard *.c)
 OBJS := $(sort $(SRCS:.c=.o))
 
diff --git a/sgx_ustdc/event.c b/sgx_ustdc/event.c
index d4d0118..ba5e5cc 100644
--- a/sgx_ustdc/event.c
+++ b/sgx_ustdc/event.c
@@ -132,7 +132,7 @@
 
 int se_event_wait_timeout(se_handle_t se_event, const struct timespec *timeout)
 {
-    int ret = -1;
+    long ret = -1;
 
     if (se_event == NULL) {
         return EINVAL;
@@ -158,12 +158,11 @@
 
 int se_event_wake(se_handle_t se_event)
 {
-    int ret = -1;
     if (se_event == NULL)
         return EINVAL;
 
     if (__sync_fetch_and_add((int*)se_event, 1) != 0) {
-       ret = syscall(__NR_futex, se_event, FUTEX_WAKE, 1, NULL, NULL, 0);  
+       syscall(__NR_futex, se_event, FUTEX_WAKE, 1, NULL, NULL, 0);  
     }
     
     return 0;
diff --git a/sgx_ustdc/fd.c b/sgx_ustdc/fd.c
index 067c7af..3842266 100644
--- a/sgx_ustdc/fd.c
+++ b/sgx_ustdc/fd.c
@@ -116,7 +116,7 @@
 
 int u_ioctl_arg0_ocall(int *error, int fd, int request)
 {
-    int ret = ioctl(fd, request);
+    int ret = ioctl(fd, (unsigned long)request);
     if (error) {
         *error = ret == -1 ? errno : 0;
     }
@@ -125,7 +125,7 @@
 
 int u_ioctl_arg1_ocall(int *error, int fd, int request, int *arg)
 {
-    int ret = ioctl(fd, request, arg);
+    int ret = ioctl(fd, (unsigned long)request, arg);
     if (error) {
         *error = ret == -1 ? errno : 0;
     }
diff --git a/sgx_ustdc/inc/inline-hashtab.h b/sgx_ustdc/inc/inline-hashtab.h
index 79d80d2..cc0d697 100644
--- a/sgx_ustdc/inc/inline-hashtab.h
+++ b/sgx_ustdc/inc/inline-hashtab.h
@@ -33,13 +33,13 @@
 }
 struct hashtab
 {
-    /* Table itself.  */
+    /* Table itself. */
     void **entries;
 
     /* Current size (in entries) of the hash table */
     size_t size;
 
-    /* Current number of elements.  */
+    /* Current number of elements. */
     size_t n_elements;
 
     /* Free function for the entries array.  This may vary depending on
@@ -77,10 +77,10 @@
 inline static void
 htab_delete (struct hashtab *htab)
 {
-    int i;
+    size_t i = 0;
 
-    for (i = htab->size - 1; i >= 0; i--)
-        free (htab->entries[i]);
+    for (i = htab->size; i > 0; i--)
+        free (htab->entries[i - 1]);
 
     if (htab->free)
         htab->free (htab->entries);
@@ -95,17 +95,17 @@
    HASH is the hash value for the element to be inserted.  */
 
 inline static void **
-find_empty_slot_for_expand (struct hashtab *htab, int hash)
+find_empty_slot_for_expand (struct hashtab *htab, unsigned int hash)
 {
     size_t size = htab->size;
-    unsigned int index = hash % size;
+    size_t index = (size_t)hash % size;
     void **slot = htab->entries + index;
-    int hash2 = 0;
+    unsigned int hash2 = 0;
 
     if (! *slot)
         return slot;
 
-    hash2 = 1 + hash % (size - 2);
+    hash2 = (unsigned int)(1 + (size_t)hash % (size - 2));
     for (;;)
     {
         index += hash2;
@@ -192,7 +192,7 @@
    expanded.  If all goes well, it will return a non-zero value.  */
 
 inline static int
-htab_expand (struct hashtab *htab, int (*hash_fn) (void *))
+htab_expand (struct hashtab *htab, unsigned int (*hash_fn) (void *))
 {
     void **oentries = NULL;
     void **olimit = NULL;
@@ -253,10 +253,10 @@
 
 inline static void **
 htab_find_slot (struct hashtab *htab, void *ptr, int insert,
-    int (*hash_fn)(void *), int (*eq_fn)(void *, void *))
+    unsigned int (*hash_fn)(void *), int (*eq_fn)(void *, void *))
 {
-    unsigned int index = 0;
-    int hash = 0, hash2 = 0;
+    size_t index = 0;
+    unsigned int hash = 0, hash2 = 0;
     size_t size = 0;
     void **entry = NULL;
 
@@ -275,7 +275,7 @@
     else if (eq_fn (*entry, ptr))
         return entry;
 
-    hash2 = 1 + hash % (size - 2);
+    hash2 = (unsigned int)(1 + (size_t)hash % (size - 2));
     for (;;)
     {
         index += hash2;
diff --git a/sgx_ustdc/signal.c b/sgx_ustdc/signal.c
index 9855fdb..2390dc1 100644
--- a/sgx_ustdc/signal.c
+++ b/sgx_ustdc/signal.c
@@ -43,10 +43,10 @@
 sgx_signal_dispatcher_t *g_signal_dispatch = NULL;
 static sgx_spinlock_t g_spin_lock;
 
-inline static int hash_func(void *p)
+inline static unsigned int hash_func(void *p)
 {
     key_value_t *kv = p;
-    return kv->signum;
+    return (unsigned int)kv->signum;
 }
 
 inline static int eq_func(void *p, void *q)
@@ -56,7 +56,7 @@
     return kv1->signum == kv2->signum;
 }
 
-int signal_dispatcher_init()
+int signal_dispatcher_init(void)
 {
     g_signal_dispatch = (sgx_signal_dispatcher_t *)malloc(sizeof(sgx_signal_dispatcher_t));
     if (g_signal_dispatch == NULL) {
@@ -73,7 +73,7 @@
     return 0;
 }
 
-int signal_dispatcher_uninit()
+int signal_dispatcher_uninit(void)
 {
     if (g_signal_dispatch == NULL) {
         return -1;
@@ -86,7 +86,7 @@
     return 0;
 }
 
-void signal_dispatcher_instance_init() {
+void signal_dispatcher_instance_init(void) {
     sgx_spin_lock(&g_spin_lock);
     if (g_signal_dispatch == NULL) {
         if (signal_dispatcher_init() < 0) {
@@ -165,7 +165,7 @@
     sigset_t mask = {0};
     sigset_t old_mask = {0};
     key_value_t *kv = NULL;
-    int i;
+    size_t i = 0;
 
     signal_dispatcher_instance_init();
 
@@ -174,9 +174,9 @@
     // If this enclave has registered any signals, deregister them and set the
     // signal handler to the default one.
     pthread_mutex_lock(&g_signal_dispatch->lock);
-     for (i = g_signal_dispatch->signal_to_eid_set->size - 1; i >= 0; i--) {
-         if (g_signal_dispatch->signal_to_eid_set->entries[i]) {
-            kv = (key_value_t*)g_signal_dispatch->signal_to_eid_set->entries[i];
+     for (i = g_signal_dispatch->signal_to_eid_set->size; i > 0; i--) {
+         if (g_signal_dispatch->signal_to_eid_set->entries[i - 1]) {
+            kv = (key_value_t*)g_signal_dispatch->signal_to_eid_set->entries[i - 1];
             if (kv->enclave_id == eid) {
                 if (signal(kv->signum, SIG_DFL) == SIG_ERR) {
                    //error
@@ -191,16 +191,17 @@
     return 0;
 }
 
-static int handle_signal(int signum, const siginfo_t *info, const void *context)
+static int handle_signal(int signum, const siginfo_t *info, __attribute__ ((unused))const void *context)
 {
     int ret = 0;
+    unsigned int result = 0;
     unsigned long long eid = 0;
 
     ret = get_eid_for_signal(signum, &eid);
     if (ret < 0) {
         return -1;
     }
-    int result = t_signal_handler_ecall(eid, &ret, info);
+    result = t_signal_handler_ecall(eid, &ret, info);
     if (result != 0) {
         return -1;
     }