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

[incubator-teaclave-sgx-sdk] branch v1.1.1-testing created (now 876c8c7)

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

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


      at 876c8c7  v1.1.1 testing

This branch includes the following new commits:

     new 876c8c7  v1.1.1 testing

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



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


[incubator-teaclave-sgx-sdk] 01/01: v1.1.1 testing

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

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

commit 876c8c75fd7464a9ac150e53309621060a50f9c7
Author: Yu Ding <di...@gmail.com>
AuthorDate: Tue Mar 17 17:27:38 2020 -0700

    v1.1.1 testing
---
 common/inc/pthread.h                               |   34 -
 common/inc/sched.h                                 |   40 +
 common/inc/sys/_types.h                            |    2 +
 common/inc/sys/stat.h                              |    2 +-
 .../inc/spinlock.h => edl/intel/sgx_pthread.edl    |   35 +-
 .../spinlock.h => edl/intel/sgx_tkey_exchange.edl  |   46 +-
 .../spinlock.h => edl/intel/sgx_tprotected_fs.edl  |   44 +-
 .../inc/spinlock.h => edl/intel/sgx_tstdc.edl      |   39 +-
 .../spinlock.h => edl/intel/sgx_tswitchless.edl    |   32 +-
 edl/sgx_asyncio.edl                                |    2 +-
 edl/sgx_env.edl                                    |   10 +-
 edl/sgx_fd.edl                                     |    8 +-
 edl/sgx_file.edl                                   |    4 +-
 edl/sgx_mem.edl                                    |   10 +-
 edl/sgx_net.edl                                    |    6 +-
 edl/sgx_net_switchless.edl                         |    4 +-
 edl/sgx_socket.edl                                 |   12 +-
 edl/sgx_sys.edl                                    |    4 +
 edl/sgx_thread.edl                                 |    8 +-
 edl/sgx_tstd.edl                                   |    9 +-
 .../Cargo.toml                                     |   12 +-
 .../LICENSE                                        |    0
 .../Readme.md                                      |    0
 sgx_align_struct_attribute/src/align.rs            |  232 ++
 sgx_align_struct_attribute/src/layout.rs           |  199 +
 .../src/lib.rs                                     |   18 +-
 sgx_alloc/Cargo.toml                               |    2 +-
 {sgx_tse => sgx_alloc}/src/alignalloc.rs           |   43 +-
 {sgx_tse => sgx_alloc}/src/alignbox.rs             |   58 +-
 sgx_alloc/src/lib.rs                               |  139 +-
 sgx_alloc/src/rsrvmem.rs                           |  166 +
 sgx_alloc/src/{lib.rs => system.rs}                |   71 +-
 sgx_backtrace/Cargo.toml                           |    2 +-
 sgx_backtrace_sys/Cargo.toml                       |    2 +-
 sgx_backtrace_sys/build.rs                         |    7 +-
 sgx_build_helper/lib.rs                            |   18 +-
 {sgx_alloc => sgx_core_futures}/Cargo.toml         |    9 +-
 {sgx_tservice => sgx_core_futures}/LICENSE         |    0
 {sgx_tservice => sgx_core_futures}/Readme.md       |    0
 {sgx_tstd => sgx_core_futures}/src/future.rs       |   23 +-
 sgx_core_futures/src/lib.rs                        |   99 +
 sgx_cov/Cargo.toml                                 |    2 +-
 sgx_crypto_helper/Cargo.toml                       |   72 +-
 sgx_crypto_helper/src/lib.rs                       |   13 +-
 sgx_crypto_helper/src/rsa2048.rs                   |   30 +
 sgx_crypto_helper/src/rsa3072.rs                   |   31 +
 sgx_demangle/Cargo.toml                            |    2 +-
 sgx_libc/Cargo.toml                                |    2 +-
 sgx_libc/src/linux/x86_64/mod.rs                   |  158 +-
 sgx_libc/src/linux/x86_64/ocall.rs                 | 1483 ++++----
 sgx_no_tstd/Cargo.toml                             |    2 +-
 sgx_no_tstd/build.rs                               |   15 +-
 sgx_panic_unwind/lib.rs                            |    2 +-
 sgx_rand/Cargo.toml                                |    2 +-
 sgx_rand_derive/Cargo.toml                         |    2 +-
 sgx_serialize/Cargo.toml                           |    2 +-
 sgx_serialize_derive/Cargo.toml                    |    2 +-
 sgx_serialize_derive_internals/Cargo.toml          |    2 +-
 sgx_tcrypto/Cargo.toml                             |    2 +-
 sgx_tcrypto/src/crypto.rs                          |  224 +-
 sgx_tcrypto_helper/Cargo.toml                      |   42 +-
 sgx_tcrypto_helper/src/lib.rs                      |   46 +-
 sgx_tcrypto_helper/src/rsa2048.rs                  |  472 ---
 sgx_tcrypto_helper/src/rsa3072.rs                  |  461 ---
 sgx_tdh/Cargo.toml                                 |    2 +-
 sgx_tdh/src/dh.rs                                  |   20 +-
 sgx_tkey_exchange/Cargo.toml                       |    2 +-
 sgx_tkey_exchange/src/lib.rs                       |   22 +-
 sgx_tprotected_fs/Cargo.toml                       |    2 +-
 sgx_tprotected_fs/src/fs.rs                        |   10 +-
 sgx_trts/Cargo.toml                                |    2 +-
 sgx_trts/src/c_str.rs                              |    2 +-
 sgx_trts/src/cpu_feature.rs                        |  117 +-
 {sgx_tstd => sgx_trts}/src/cpuid.rs                |    9 +-
 sgx_trts/src/enclave.rs                            |  145 +-
 sgx_trts/src/lib.rs                                |    5 +-
 sgx_trts/src/memchr.rs                             |    2 -
 sgx_trts/src/memeq.rs                              |   40 +-
 sgx_trts/src/oom.rs                                |    4 +-
 sgx_trts/src/trts.rs                               |   38 +-
 sgx_trts/src/veh.rs                                |   11 +-
 sgx_tse/Cargo.toml                                 |    2 +-
 sgx_tse/src/lib.rs                                 |    5 -
 sgx_tse/src/se.rs                                  |   12 +-
 sgx_tseal/Cargo.toml                               |    2 +-
 sgx_tseal/src/aad.rs                               |   24 +-
 sgx_tseal/src/internal.rs                          |   28 +-
 sgx_tseal/src/seal.rs                              |   26 +-
 sgx_tservice/Cargo.toml                            |   19 -
 sgx_tservice/src/lib.rs                            |   38 -
 sgx_tservice/src/sgxcounter.rs                     |  551 ---
 sgx_tservice/src/sgxtime.rs                        |  200 -
 sgx_tservice/src/tae.rs                            |  201 -
 sgx_tstd/Cargo.toml                                |    6 +-
 sgx_tstd/build.rs                                  |   12 +
 sgx_tstd/hashbrown/.cargo_vcs_info.json            |    5 +
 sgx_tstd/hashbrown/.gitignore                      |    3 +
 sgx_tstd/hashbrown/CHANGELOG.md                    |  208 ++
 sgx_tstd/hashbrown/Cargo.toml                      |   83 +
 sgx_tstd/hashbrown/Cargo.toml.orig                 |   58 +
 sgx_tstd/hashbrown/LICENSE-APACHE                  |  201 +
 sgx_tstd/hashbrown/LICENSE-MIT                     |   25 +
 sgx_tstd/hashbrown/README.md                       |  125 +
 sgx_tstd/hashbrown/benches/bench.rs                |  260 ++
 sgx_tstd/hashbrown/build.rs                        |    9 +
 sgx_tstd/hashbrown/clippy.toml                     |    1 +
 sgx_tstd/hashbrown/src/external_trait_impls/mod.rs |    4 +
 .../src/external_trait_impls/rayon/helpers.rs      |   26 +
 .../src/external_trait_impls/rayon/map.rs          |  676 ++++
 .../src/external_trait_impls/rayon/mod.rs          |    4 +
 .../src/external_trait_impls/rayon/raw.rs          |  193 +
 .../src/external_trait_impls/rayon/set.rs          |  646 ++++
 .../hashbrown/src/external_trait_impls/serde.rs    |  200 +
 sgx_tstd/hashbrown/src/lib.rs                      |  121 +
 sgx_tstd/hashbrown/src/macros.rs                   |   54 +
 sgx_tstd/hashbrown/src/map.rs                      | 3861 ++++++++++++++++++++
 sgx_tstd/hashbrown/src/raw/bitmask.rs              |  108 +
 sgx_tstd/hashbrown/src/raw/generic.rs              |  155 +
 sgx_tstd/hashbrown/src/raw/mod.rs                  | 1528 ++++++++
 sgx_tstd/hashbrown/src/raw/sse2.rs                 |  143 +
 sgx_tstd/hashbrown/src/rustc_entry.rs              |  621 ++++
 sgx_tstd/hashbrown/src/scopeguard.rs               |   49 +
 sgx_tstd/hashbrown/src/set.rs                      | 1906 ++++++++++
 sgx_tstd/hashbrown/tests/hasher.rs                 |   65 +
 sgx_tstd/hashbrown/tests/rayon.rs                  |  533 +++
 sgx_tstd/hashbrown/tests/serde.rs                  |   65 +
 sgx_tstd/hashbrown/tests/set.rs                    |   30 +
 sgx_tstd/src/collections/hash/map.rs               | 3438 +++++++++++------
 sgx_tstd/src/collections/hash/mod.rs               |   26 -
 sgx_tstd/src/collections/hash/set.rs               | 1429 +++++++-
 sgx_tstd/src/collections/hash/table.rs             | 1134 ------
 sgx_tstd/src/collections/mod.rs                    |    4 +-
 sgx_tstd/src/cpuid.rs                              |  126 +-
 sgx_tstd/src/enclave.rs                            |   29 +-
 sgx_tstd/src/future.rs                             |    2 +-
 sgx_tstd/src/lib.rs                                |    4 +-
 sgx_tstd/src/panicking.rs                          |   17 +-
 sgx_tstd/src/rt.rs                                 |    2 +-
 sgx_tstd/src/sync/condvar.rs                       |  187 +-
 sgx_tstd/src/sync/mod.rs                           |    4 +-
 sgx_tstd/src/sync/mutex.rs                         |  372 +-
 sgx_tstd/src/sync/remutex.rs                       |   83 +-
 sgx_tstd/src/sync/rwlock.rs                        |  319 +-
 sgx_tstd/src/sync/spinlock.rs                      |    4 +-
 sgx_tstd/src/sys/condvar.rs                        |  230 ++
 .../src/sys/fast_thread_local.rs                   |   19 +-
 sgx_tstd/src/sys/fd.rs                             |    4 +-
 sgx_tstd/src/sys/mod.rs                            |    7 +
 sgx_tstd/src/sys/mutex.rs                          |  336 ++
 sgx_tstd/src/sys/os.rs                             |    2 +-
 sgx_tstd/src/sys/rwlock.rs                         |  319 ++
 sgx_tstd/src/sys/thread.rs                         |  138 +-
 .../src/oom.rs => sgx_tstd/src/sys/thread_local.rs |   47 +-
 sgx_tstd/src/sys_common/at_exit_imp.rs             |    3 +-
 sgx_tstd/src/sys_common/mod.rs                     |   40 +-
 sgx_tstd/src/sys_common/thread.rs                  |   28 -
 sgx_tstd/src/sys_common/thread_local.rs            |  231 ++
 sgx_tstd/src/thread/local.rs                       |  411 ++-
 sgx_tstd/src/thread/mod.rs                         |   43 +-
 sgx_tunittest/Cargo.toml                           |    2 +-
 sgx_types/Cargo.toml                               |    2 +-
 sgx_types/src/cpu_feature.rs                       |    4 +-
 sgx_types/src/error.rs                             |    6 +
 sgx_types/src/function.rs                          |  673 ++--
 sgx_types/src/marker.rs                            |    4 +-
 sgx_types/src/metadata.rs                          |   54 +-
 sgx_types/src/types.rs                             |  177 +-
 sgx_ucrypto/Cargo.toml                             |    2 +-
 sgx_ucrypto/src/crypto.rs                          |  198 +-
 sgx_ucrypto/src/util.rs                            |   38 +-
 sgx_unwind/build.rs                                |   15 +-
 sgx_urts/Cargo.toml                                |    2 +-
 sgx_urts/src/asyncio.rs                            |   15 +-
 sgx_urts/src/enclave.rs                            |   44 +-
 sgx_urts/src/env.rs                                |   38 +-
 sgx_urts/src/event.rs                              |   31 +-
 sgx_urts/src/fd.rs                                 |   44 +-
 sgx_urts/src/file.rs                               |  118 +-
 sgx_urts/src/mem.rs                                |   22 +-
 sgx_urts/src/net.rs                                |   10 +-
 sgx_urts/src/pipe.rs                               |    8 +-
 sgx_urts/src/socket.rs                             |   87 +-
 sgx_urts/src/sys.rs                                |   38 +-
 sgx_urts/src/thread.rs                             |   71 +-
 sgx_urts/src/time.rs                               |    4 +-
 sgx_ustdc/Makefile                                 |    2 +-
 sgx_ustdc/asyncio.c                                |    8 +-
 sgx_ustdc/env.c                                    |   10 +-
 sgx_ustdc/event.c                                  |   42 +-
 sgx_ustdc/fd.c                                     |   26 +-
 sgx_ustdc/file.c                                   |   16 +-
 sgx_ustdc/inc/spinlock.h                           |   51 +-
 sgx_ustdc/mem.c                                    |   14 +-
 sgx_ustdc/net.c                                    |    6 +-
 sgx_ustdc/pipe.c                                   |    4 +-
 sgx_ustdc/socket.c                                 |   71 +-
 sgx_ustdc/spinlock.c                               |   54 +-
 sgx_ustdc/sys.c                                    |   24 +-
 sgx_ustdc/thread.c                                 |   79 +-
 sgx_ustdc/time.c                                   |    2 +-
 xargo/sgx_tstd/Cargo.toml                          |    4 +-
 xargo/sgx_tstd/build.rs                            |   12 +
 202 files changed, 20975 insertions(+), 8240 deletions(-)

diff --git a/common/inc/pthread.h b/common/inc/pthread.h
deleted file mode 100644
index e79668f..0000000
--- a/common/inc/pthread.h
+++ /dev/null
@@ -1,34 +0,0 @@
-#ifndef _SYS_THREAD_H_
-#define _SYS_THREAD_H_
-
-/* Thread identifiers.  The structure of the attribute type is not
-   exposed on purpose.  */
-typedef unsigned long int pthread_t;
-
-#if defined __x86_64__ && !defined __ILP32__
-# define __WORDSIZE 64
-#else
-# define __WORDSIZE 32
-#define __WORDSIZE32_SIZE_ULONG     0
-#define __WORDSIZE32_PTRDIFF_LONG   0
-#endif
-
-#ifdef __x86_64__
-# if __WORDSIZE == 64
-#  define __SIZEOF_PTHREAD_ATTR_T   56
-# else
-#  define __SIZEOF_PTHREAD_ATTR_T   32
-#endif
-
-union pthread_attr_t
-{
-    char __size[__SIZEOF_PTHREAD_ATTR_T];
-    long int __align;
-};
-#ifndef __have_pthread_attr_t
-typedef union pthread_attr_t pthread_attr_t;
-# define __have_pthread_attr_t 1
-#endif
-
-#endif
-#endif
diff --git a/common/inc/sched.h b/common/inc/sched.h
new file mode 100644
index 0000000..5c29893
--- /dev/null
+++ b/common/inc/sched.h
@@ -0,0 +1,40 @@
+/* Definition of the cpu_set_t structure used by the POSIX 1003.1b-1993
+   scheduling interface.
+   Copyright (C) 1996-2018 Free Software Foundation, Inc.
+   This file is part of the GNU C Library.
+
+   The GNU C Library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with the GNU C Library; if not, see
+   <http://www.gnu.org/licenses/>.  */
+
+#ifndef _SCHED_H
+#define _SCHED_H
+#include <sys/_types.h>
+
+/* Size definition for CPU sets.  */
+#define __CPU_SETSIZE	1024
+#define __NCPUBITS	(8 * sizeof (__cpu_mask))
+
+/* Basic access functions.  */
+#define __CPUELT(cpu)	((cpu) / __NCPUBITS)
+#define __CPUMASK(cpu)	((__cpu_mask) 1 << ((cpu) % __NCPUBITS))
+
+/* Data structure to describe CPU mask.  */
+typedef struct
+{
+  __cpu_mask __bits[__CPU_SETSIZE / __NCPUBITS];
+} cpu_set_t;
+
+typedef __pid_t   pid_t;
+
+#endif
\ No newline at end of file
diff --git a/common/inc/sys/_types.h b/common/inc/sys/_types.h
index 7768f18..5dc6d5b 100644
--- a/common/inc/sys/_types.h
+++ b/common/inc/sys/_types.h
@@ -160,6 +160,8 @@ typedef unsigned long long int  __ino64_t;
 #endif
 
 typedef unsigned int            __socklen_t;
+typedef int                     __pid_t;
+typedef long                    __cpu_mask;
 #endif /* !_SYS__TYPES_H_ */
 
 
diff --git a/common/inc/sys/stat.h b/common/inc/sys/stat.h
index 43b4776..eeae9b5 100644
--- a/common/inc/sys/stat.h
+++ b/common/inc/sys/stat.h
@@ -17,7 +17,7 @@
 
 
 #ifndef _SYS_STAT_H
-#define _SYS_STAT_H	1
+#define _SYS_STAT_H
 
 #include <sys/_types.h>
 #include <sys/types.h>
diff --git a/sgx_ustdc/inc/spinlock.h b/edl/intel/sgx_pthread.edl
similarity index 77%
copy from sgx_ustdc/inc/spinlock.h
copy to edl/intel/sgx_pthread.edl
index a8a8c55..7a097a7 100644
--- a/sgx_ustdc/inc/spinlock.h
+++ b/edl/intel/sgx_pthread.edl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
+ * Copyright (C) 2011-2019 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,29 +29,10 @@
  *
  */
 
-
-
-
-
-#ifndef _SPINLOCK_H_
-#define _SPINLOCK_H_
-
-//#include "sgx_defs.h"
-#include <stdint.h>
-
-typedef volatile uint32_t sgx_spinlock_t;
-
-#define SGX_SPINLOCK_INITIALIZER 0
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-uint32_t  sgx_spin_lock(sgx_spinlock_t *lock);
-uint32_t  sgx_spin_unlock(sgx_spinlock_t *lock);
-
-#if defined(__cplusplus)
-}
-#endif
-
-#endif /* !_SGX_SPINLOCK_H_ */
+enclave {
+    untrusted {
+        [cdecl] int pthread_wait_timeout_ocall (unsigned long long waiter, unsigned long long timeout);
+        [cdecl] int pthread_create_ocall(unsigned long long self);
+        [cdecl] int pthread_wakeup_ocall(unsigned long long waiter);
+    };
+};
diff --git a/sgx_ustdc/inc/spinlock.h b/edl/intel/sgx_tkey_exchange.edl
similarity index 67%
copy from sgx_ustdc/inc/spinlock.h
copy to edl/intel/sgx_tkey_exchange.edl
index a8a8c55..3e18c89 100644
--- a/sgx_ustdc/inc/spinlock.h
+++ b/edl/intel/sgx_tkey_exchange.edl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
+ * Copyright (C) 2011-2019 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,29 +29,21 @@
  *
  */
 
-
-
-
-
-#ifndef _SPINLOCK_H_
-#define _SPINLOCK_H_
-
-//#include "sgx_defs.h"
-#include <stdint.h>
-
-typedef volatile uint32_t sgx_spinlock_t;
-
-#define SGX_SPINLOCK_INITIALIZER 0
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-uint32_t  sgx_spin_lock(sgx_spinlock_t *lock);
-uint32_t  sgx_spin_unlock(sgx_spinlock_t *lock);
-
-#if defined(__cplusplus)
-}
-#endif
-
-#endif /* !_SGX_SPINLOCK_H_ */
+enclave {
+    trusted {
+        public sgx_status_t sgx_ra_get_ga(sgx_ra_context_t context,
+            [out] sgx_ec256_public_t *g_a);
+
+        public sgx_status_t sgx_ra_proc_msg2_trusted(sgx_ra_context_t context,
+            [in]const sgx_ra_msg2_t *p_msg2, /*copy msg2 except quote into enclave */
+            [in] const sgx_target_info_t *p_qe_target,
+            [out] sgx_report_t *p_report,
+            [out] sgx_quote_nonce_t *p_nonce);
+
+        public sgx_status_t sgx_ra_get_msg3_trusted(sgx_ra_context_t context,
+            uint32_t quote_size,
+            [in]sgx_report_t* qe_report,
+            [user_check]sgx_ra_msg3_t *p_msg3,
+            uint32_t msg3_size);
+    };
+};
diff --git a/sgx_ustdc/inc/spinlock.h b/edl/intel/sgx_tprotected_fs.edl
similarity index 56%
copy from sgx_ustdc/inc/spinlock.h
copy to edl/intel/sgx_tprotected_fs.edl
index a8a8c55..2dfad37 100644
--- a/sgx_ustdc/inc/spinlock.h
+++ b/edl/intel/sgx_tprotected_fs.edl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
+ * Copyright (C) 2011-2019 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,29 +29,19 @@
  *
  */
 
-
-
-
-
-#ifndef _SPINLOCK_H_
-#define _SPINLOCK_H_
-
-//#include "sgx_defs.h"
-#include <stdint.h>
-
-typedef volatile uint32_t sgx_spinlock_t;
-
-#define SGX_SPINLOCK_INITIALIZER 0
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-uint32_t  sgx_spin_lock(sgx_spinlock_t *lock);
-uint32_t  sgx_spin_unlock(sgx_spinlock_t *lock);
-
-#if defined(__cplusplus)
-}
-#endif
-
-#endif /* !_SGX_SPINLOCK_H_ */
+enclave {
+    from "sgx_tstdc.edl" import *;
+    untrusted {
+		void*   u_sgxprotectedfs_exclusive_file_open([in, string] const char* filename, uint8_t read_only, [out] int64_t* file_size, [out] int32_t* error_code);
+		uint8_t u_sgxprotectedfs_check_if_file_exists([in, string] const char* filename);
+		int32_t u_sgxprotectedfs_fread_node([user_check] void* f, uint64_t node_number, [out, size=node_size] uint8_t* buffer, uint32_t node_size);
+		int32_t u_sgxprotectedfs_fwrite_node([user_check] void* f, uint64_t node_number, [in, size=node_size] uint8_t* buffer, uint32_t node_size);
+		int32_t u_sgxprotectedfs_fclose([user_check] void* f);
+		uint8_t u_sgxprotectedfs_fflush([user_check] void* f);
+		int32_t u_sgxprotectedfs_remove([in, string] const char* filename);
+
+		void*   u_sgxprotectedfs_recovery_file_open([in, string] const char* filename);
+		uint8_t u_sgxprotectedfs_fwrite_recovery_node([user_check] void* f, [in, count=data_length] uint8_t* data, uint32_t data_length);
+		int32_t u_sgxprotectedfs_do_file_recovery([in, string] const char* filename, [in, string] const char* recovery_filename, uint32_t node_size);
+    };
+};
diff --git a/sgx_ustdc/inc/spinlock.h b/edl/intel/sgx_tstdc.edl
similarity index 63%
copy from sgx_ustdc/inc/spinlock.h
copy to edl/intel/sgx_tstdc.edl
index a8a8c55..4124deb 100644
--- a/sgx_ustdc/inc/spinlock.h
+++ b/edl/intel/sgx_tstdc.edl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
+ * Copyright (C) 2011-2019 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,29 +29,20 @@
  *
  */
 
+enclave {
+    untrusted {
+        [cdecl] void sgx_oc_cpuidex([out] int cpuinfo[4], int leaf, int subleaf);
+        
+        /* Go outside and wait on my untrusted event */
+        [cdecl] int sgx_thread_wait_untrusted_event_ocall([user_check] const void *self);
 
+        /* Wake a thread waiting on its untrusted event */
+        [cdecl] int sgx_thread_set_untrusted_event_ocall([user_check] const void *waiter);
 
+        /* Wake a thread waiting on its untrusted event, and wait on my untrusted event */
+        [cdecl] int sgx_thread_setwait_untrusted_events_ocall([user_check] const void *waiter, [user_check] const void *self);
 
-
-#ifndef _SPINLOCK_H_
-#define _SPINLOCK_H_
-
-//#include "sgx_defs.h"
-#include <stdint.h>
-
-typedef volatile uint32_t sgx_spinlock_t;
-
-#define SGX_SPINLOCK_INITIALIZER 0
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-uint32_t  sgx_spin_lock(sgx_spinlock_t *lock);
-uint32_t  sgx_spin_unlock(sgx_spinlock_t *lock);
-
-#if defined(__cplusplus)
-}
-#endif
-
-#endif /* !_SGX_SPINLOCK_H_ */
+        /* Wake multiple threads waiting on their untrusted events */
+        [cdecl] int sgx_thread_set_multiple_untrusted_events_ocall([in, count = total] const void **waiters, size_t total);
+    };
+};
diff --git a/sgx_ustdc/inc/spinlock.h b/edl/intel/sgx_tswitchless.edl
similarity index 77%
copy from sgx_ustdc/inc/spinlock.h
copy to edl/intel/sgx_tswitchless.edl
index a8a8c55..a20669a 100644
--- a/sgx_ustdc/inc/spinlock.h
+++ b/edl/intel/sgx_tswitchless.edl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
+ * Copyright (C) 2011-2019 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -29,29 +29,11 @@
  *
  */
 
+enclave {
 
+    trusted {
+	    public sgx_status_t sl_init_switchless([user_check]void* sl_data);
+		public sgx_status_t sl_run_switchless_tworker();
+    };
 
-
-
-#ifndef _SPINLOCK_H_
-#define _SPINLOCK_H_
-
-//#include "sgx_defs.h"
-#include <stdint.h>
-
-typedef volatile uint32_t sgx_spinlock_t;
-
-#define SGX_SPINLOCK_INITIALIZER 0
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-uint32_t  sgx_spin_lock(sgx_spinlock_t *lock);
-uint32_t  sgx_spin_unlock(sgx_spinlock_t *lock);
-
-#if defined(__cplusplus)
-}
-#endif
-
-#endif /* !_SGX_SPINLOCK_H_ */
+};
diff --git a/edl/sgx_asyncio.edl b/edl/sgx_asyncio.edl
index 72376ed..f463738 100644
--- a/edl/sgx_asyncio.edl
+++ b/edl/sgx_asyncio.edl
@@ -28,6 +28,6 @@ enclave {
         int u_poll_ocall([out] int *error, [in, out, count=nfds] struct pollfd *fds, nfds_t nfds, int timeout);
         int u_epoll_create1_ocall([out] int *error, int flags);
         int u_epoll_ctl_ocall([out] int *error, int epfd, int op, int fd, [in] struct epoll_event *event);
-        int u_epoll_wait_ocall([out] int *error, int epfd, [out, count=maxevents] struct epoll_event * events, int maxevents, int timeout);
+        int u_epoll_wait_ocall([out] int *error, int epfd, [out, count=maxevents] struct epoll_event *events, int maxevents, int timeout);
     };
 };
diff --git a/edl/sgx_env.edl b/edl/sgx_env.edl
index edefb13..d4a77cc 100644
--- a/edl/sgx_env.edl
+++ b/edl/sgx_env.edl
@@ -24,13 +24,17 @@ enclave {
     };
 
     untrusted {
-        char ** u_environ_ocall();
-        char * u_getenv_ocall([in, string] const char *name);
+        char **u_environ_ocall();
+        char *u_getenv_ocall([in, string] const char *name);
         int u_setenv_ocall([out] int *error, [in, string] const char *name, [in, string] const char *value, int overwrite);
         int u_unsetenv_ocall([out] int *error, [in, string] const char *name);
         int u_chdir_ocall([out] int *error, [in, string] const char *dir);
         char *u_getcwd_ocall([out] int *error, [out, size=buflen] char *buf, size_t buflen);
-        int u_getpwuid_r_ocall(unsigned int uid, [out] struct passwd *pwd, [out, size=buflen] char *buf, size_t buflen, [out] struct passwd **passwd_result);
+        int u_getpwuid_r_ocall(unsigned int uid,
+                               [out] struct passwd *pwd,
+                               [out, size=buflen] char *buf,
+                               size_t buflen,
+                               [out] struct passwd **passwd_result);
         unsigned int u_getuid_ocall();
     };
 };
diff --git a/edl/sgx_fd.edl b/edl/sgx_fd.edl
index 6596e03..8cfc822 100644
--- a/edl/sgx_fd.edl
+++ b/edl/sgx_fd.edl
@@ -27,13 +27,13 @@ enclave {
     };
 
     untrusted {
-        size_t u_read_ocall([out] int *error, int fd, [out, size=count] void *buf, size_t count);
-        size_t u_pread64_ocall([out] int *error, int fd, [out, size=count] void *buf, size_t count, int64_t offset);
+        size_t u_read_ocall([out] int *error, int fd, [user_check] void *buf, size_t count);
+        size_t u_pread64_ocall([out] int *error, int fd, [user_check] void *buf, size_t count, int64_t offset);
         size_t u_readv_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt);
         size_t u_preadv64_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt, int64_t offset);
 
-        size_t u_write_ocall([out] int *error, int fd, [in, size=count] const void *buf, size_t count);
-        size_t u_pwrite64_ocall([out] int *error, int fd, [in, size=count] const void *buf, size_t count, int64_t offset);
+        size_t u_write_ocall([out] int *error, int fd, [user_check] const void *buf, size_t count);
+        size_t u_pwrite64_ocall([out] int *error, int fd, [user_check] const void *buf, size_t count, int64_t offset);
         size_t u_writev_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt);
         size_t u_pwritev64_ocall([out] int *error, int fd, [in, count=iovcnt] const struct iovec *iov, int iovcnt, int64_t offset);
 
diff --git a/edl/sgx_file.edl b/edl/sgx_file.edl
index e751e79..1e28036 100644
--- a/edl/sgx_file.edl
+++ b/edl/sgx_file.edl
@@ -50,10 +50,10 @@ enclave {
         int u_chmod_ocall([out] int *error, [in, string] const char *path, uint32_t mode);
         size_t u_readlink_ocall([out] int *error, [in, string] const char *path, [out, size=bufsz] char *buf, size_t bufsz);
         int u_symlink_ocall([out] int *error, [in, string] const char *path1, [in, string] const char *path2);
-        char * u_realpath_ocall([out] int *error, [in, string] const char *pathname);
+        char *u_realpath_ocall([out] int *error, [in, string] const char *pathname);
         int u_mkdir_ocall([out] int *error, [in, string] const char *pathname, uint32_t mode);
         int u_rmdir_ocall([out] int *error, [in, string] const char *pathname);
-        void * u_opendir_ocall([out] int *error, [in, string] const char *pathname);
+        void *u_opendir_ocall([out] int *error, [in, string] const char *pathname);
         int u_readdir64_r_ocall([user_check] void *dirp, [in, out] struct dirent64_t *entry, [out] struct dirent64_t **result);
         int u_closedir_ocall([out] int *error, [user_check] void *dirp);
         int u_dirfd_ocall([out] int *error, [user_check] void *dirp);
diff --git a/edl/sgx_mem.edl b/edl/sgx_mem.edl
index 139a83f..db55802 100644
--- a/edl/sgx_mem.edl
+++ b/edl/sgx_mem.edl
@@ -22,10 +22,16 @@ enclave {
     };
 
     untrusted {
-        void * u_malloc_ocall([out] int *error, size_t size);
+        void *u_malloc_ocall([out] int *error, size_t size);
         void u_free_ocall([user_check] void *p);
 
-        void * u_mmap_ocall([out] int *error, [user_check] void *start, size_t length, int prot, int flags, int fd, int64_t offset);
+        void *u_mmap_ocall([out] int *error,
+                           [user_check] void *start,
+                           size_t length,
+                           int prot,
+                           int flags,
+                           int fd,
+                           int64_t offset);
         int u_munmap_ocall([out] int *error, [user_check] void *start, size_t length);
 
         int u_msync_ocall([out] int *error, [user_check] void *addr, size_t length, int flags);
diff --git a/edl/sgx_net.edl b/edl/sgx_net.edl
index 7cc01dc..a803b53 100644
--- a/edl/sgx_net.edl
+++ b/edl/sgx_net.edl
@@ -30,7 +30,11 @@ enclave {
     };
 
     untrusted {
-        int u_getaddrinfo_ocall([out]int * error,  [in, string] const char * node,  [in, string] const char * service, [in] const struct addrinfo * hints, [out] struct addrinfo ** res);
+        int u_getaddrinfo_ocall([out] int *error,
+                                [in, string] const char *node,
+                                [in, string] const char *service,
+                                [in] const struct addrinfo *hints,
+                                [out] struct addrinfo **res);
         void u_freeaddrinfo_ocall([user_check] struct addrinfo *res);
         char *u_gai_strerror_ocall(int errcode);
     };
diff --git a/edl/sgx_net_switchless.edl b/edl/sgx_net_switchless.edl
index 2af2b5c..ec5c500 100644
--- a/edl/sgx_net_switchless.edl
+++ b/edl/sgx_net_switchless.edl
@@ -52,7 +52,7 @@ enclave {
                                     [out, size=addrlen_in] struct sockaddr *src_addr,
                                     socklen_t addrlen_in,
                                     [out] socklen_t *addrlen_out) transition_using_threads;
-        size_t u_net_recvmsg_ocall([out] int *error, int sockfd, [in, out] struct msghdr * msg, int flags) transition_using_threads;
+        size_t u_net_recvmsg_ocall([out] int *error, int sockfd, [in, out] struct msghdr *msg, int flags) transition_using_threads;
         size_t u_net_send_ocall([out] int *error, int sockfd, [in, size=len] const void *buf, size_t len, int flags) transition_using_threads;
         size_t u_net_sendto_ocall([out] int *error,
                                   int sockfd,
@@ -61,7 +61,7 @@ enclave {
                                   int flags,
                                   [in, size=addrlen] const struct sockaddr *dest_addr,
                                   socklen_t addrlen) transition_using_threads;
-        size_t u_sendmsg_ocall([out] int *error, int sockfd, [in] const struct msghdr * msg, int flags) transition_using_threads;
+        size_t u_sendmsg_ocall([out] int *error, int sockfd, [in] const struct msghdr *msg, int flags) transition_using_threads;
         int u_net_getsockopt_ocall([out] int *error,
                                    int sockfd,
                                    int level,
diff --git a/edl/sgx_socket.edl b/edl/sgx_socket.edl
index b082c71..68ce3b6 100644
--- a/edl/sgx_socket.edl
+++ b/edl/sgx_socket.edl
@@ -45,25 +45,25 @@ enclave {
                             int sockfd,
                             [in, size=addrlen] const struct sockaddr *addr,
                             socklen_t addrlen);
-        size_t u_recv_ocall([out] int *error, int sockfd, [out, size=len] void *buf, size_t len, int flags);
+        size_t u_recv_ocall([out] int *error, int sockfd,[user_check] void *buf, size_t len, int flags);
         size_t u_recvfrom_ocall([out] int *error,
                                 int sockfd,
-                                [out, size=len] void *buf,
+                                [user_check] void *buf,
                                 size_t len,
                                 int flags,
                                 [out, size=addrlen_in] struct sockaddr *src_addr,
                                 socklen_t addrlen_in,
                                 [out] socklen_t *addrlen_out);
-        size_t u_recvmsg_ocall([out] int *error, int sockfd, [in, out] struct msghdr * msg, int flags);
-        size_t u_send_ocall([out] int *error, int sockfd, [in, size=len] const void *buf, size_t len, int flags);
+        size_t u_recvmsg_ocall([out] int *error, int sockfd, [in, out] struct msghdr *msg, int flags);
+        size_t u_send_ocall([out] int *error, int sockfd, [user_check] const void *buf, size_t len, int flags);
         size_t u_sendto_ocall([out] int *error,
                               int sockfd,
-                              [in, size=len] const void *buf,
+                              [user_check] const void *buf,
                               size_t len,
                               int flags,
                               [in, size=addrlen] const struct sockaddr *dest_addr,
                               socklen_t addrlen);
-        size_t u_sendmsg_ocall([out] int *error, int sockfd, [in] const struct msghdr * msg, int flags);
+        size_t u_sendmsg_ocall([out] int *error, int sockfd, [in] const struct msghdr *msg, int flags);
         int u_getsockopt_ocall([out] int *error,
                                int sockfd,
                                int level,
diff --git a/edl/sgx_sys.edl b/edl/sgx_sys.edl
index ce1a538..e940581 100644
--- a/edl/sgx_sys.edl
+++ b/edl/sgx_sys.edl
@@ -17,6 +17,8 @@
 
 enclave {
 
+    include "sched.h"
+
 	trusted {
         /* define ECALLs here. */
     };
@@ -24,5 +26,7 @@ enclave {
     untrusted {
         long u_sysconf_ocall([out] int *error, int name);
         int u_prctl_ocall([out] int *error, int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5);
+        int u_sched_setaffinity_ocall([out] int *error, pid_t pid, size_t cpusetsize, [in]cpu_set_t *mask);
+        int u_sched_getaffinity_ocall([out] int *error, pid_t pid, size_t cpusetsize, [out]cpu_set_t *mask);
     };
 };
diff --git a/edl/sgx_thread.edl b/edl/sgx_thread.edl
index f210f69..4dd0e5c 100644
--- a/edl/sgx_thread.edl
+++ b/edl/sgx_thread.edl
@@ -17,16 +17,14 @@
 enclave {
 
     include "time.h"
-    include "pthread.h"
+
+    from "intel/sgx_pthread.edl" import *;
 
     trusted {
-        public void *t_thread_main([in, size=len]void *arg, int len);
+        /* define ECALLs here. */
     };
 
     untrusted {
-        int u_pthread_create_ocall([out]pthread_t *thread, [in]const pthread_attr_t *attr, [user_check]void *start_routine, [in, size=len]void *arg, int len);
-        int u_pthread_join_ocall(pthread_t thread, [out]void **result);
-        int u_pthread_detach_ocall(pthread_t thread);
         int u_sched_yield_ocall([out]int *error);
         int u_nanosleep_ocall([out]int *error, [in]const struct timespec *req, [out]struct timespec *rem);
     };
diff --git a/edl/sgx_tstd.edl b/edl/sgx_tstd.edl
index 62fb049..9b74272 100644
--- a/edl/sgx_tstd.edl
+++ b/edl/sgx_tstd.edl
@@ -28,8 +28,11 @@ enclave {
     untrusted {
         /* define OCALLs here. */
         int u_thread_set_event_ocall([out] int *error, [user_check] const void *tcs);
-        int u_thread_wait_event_ocall([out] int *error, [user_check] const void *tcs, [in]const struct timespec *timeout);
-        int u_thread_set_multiple_events_ocall([out]int *error, [in, count=total]const void ** tcss, int total);
-        int u_thread_setwait_events_ocall([out]int *error, [user_check]const void * waiter_tcs, [user_check]const void * self_tcs, [in]const struct timespec *timeout);
+        int u_thread_wait_event_ocall([out] int *error, [user_check] const void *tcs, [in] const struct timespec *timeout);
+        int u_thread_set_multiple_events_ocall([out] int *error, [in, count=total] const void **tcss, int total);
+        int u_thread_setwait_events_ocall([out] int *error,
+                                          [user_check] const void *waiter_tcs,
+                                          [user_check] const void *self_tcs,
+                                          [in] const struct timespec *timeout);
     };
 };
diff --git a/sgx_rand_derive/Cargo.toml b/sgx_align_struct_attribute/Cargo.toml
similarity index 66%
copy from sgx_rand_derive/Cargo.toml
copy to sgx_align_struct_attribute/Cargo.toml
index 568a7a4..e423af5 100644
--- a/sgx_rand_derive/Cargo.toml
+++ b/sgx_align_struct_attribute/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
-name = "sgx_rand_derive"
-version = "1.1.0"
+name = "sgx_align_struct_attribute"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
@@ -9,9 +9,11 @@ description = "Rust SGX SDK provides the ability to write Intel SGX applications
 edition = "2018"
 
 [lib]
-name = "sgx_rand_derive"
+name = "sgx_align_struct_attribute"
 proc-macro = true
 
 [dependencies]
-quote = "0.3"
-syn = "0.11"
+syn = { version = "1.0", features = ["full"] }
+quote = "1.0"
+proc-macro2 = "1.0"
+
diff --git a/sgx_tservice/LICENSE b/sgx_align_struct_attribute/LICENSE
similarity index 100%
copy from sgx_tservice/LICENSE
copy to sgx_align_struct_attribute/LICENSE
diff --git a/sgx_tservice/Readme.md b/sgx_align_struct_attribute/Readme.md
similarity index 100%
copy from sgx_tservice/Readme.md
copy to sgx_align_struct_attribute/Readme.md
diff --git a/sgx_align_struct_attribute/src/align.rs b/sgx_align_struct_attribute/src/align.rs
new file mode 100644
index 0000000..0c832b2
--- /dev/null
+++ b/sgx_align_struct_attribute/src/align.rs
@@ -0,0 +1,232 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License..
+
+use 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};
+
+struct KeyValue {
+    pub ident: Ident,
+    pub punct: Punct,
+    pub value: Expr,
+}
+
+impl Parse for KeyValue {
+    fn parse(input: ParseStream) -> Result<Self> {
+        let ident = input.parse::<Ident>()?;
+        let punct = input.parse::<Punct>()?;
+        let value = input.parse::<Expr>()?;
+        Ok(KeyValue{ident, punct, value})
+    }
+}
+
+pub struct AlignArgs  {
+    vars: Vec<KeyValue>,
+}
+
+impl Parse for AlignArgs {
+    fn parse(input: ParseStream) -> Result<Self> {
+        let keyvalue = Punctuated::<KeyValue, Token![,]>::parse_terminated(input)?;
+        Ok(AlignArgs {
+            vars: keyvalue.into_iter().collect(),
+        })
+    }
+}
+
+impl AlignArgs {
+    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 {
+            return Err(Error::new(Span::call_site(), "Invalid type of align attribute parsing"));
+        };
+
+        let size_iter = self.vars.iter().filter(|v| v.ident.to_string() == "size").next();
+        let size: usize = if let Some(size_value) = size_iter {
+            self.parse_size(&size_value.value)?
+        } else {
+            return Err(Error::new(Span::call_site(), "Invalid type of size attribute parsing"));
+        };
+        Layout::from_size_align(size, align).map_err(|_e| Error::new(Span::call_site(), "Layout illegal"))
+    }
+
+    fn parse_align(&self, align_expr: &Expr) -> Result<usize> {
+        if let Expr::Lit(expr) = align_expr {
+            if let Lit::Int(ref lit) = expr.lit {
+                let align = lit.base10_parse::<u32>()?;
+                Ok(align as usize)
+            } else {
+                Err(Error::new(Span::call_site(), "Invalid align attribute parsing"))
+            }
+        } else {
+            Err(Error::new(Span::call_site(), "Invalid align attribute parsing"))
+        }
+    }
+
+    fn parse_size(&self, size_expr: &Expr) -> Result<usize> {
+        if let Expr::Lit(expr) = size_expr {
+            if let Lit::Int(ref lit) = expr.lit {
+                let size = lit.base10_parse::<u32>()?;
+                Ok(size as usize)
+            } else {
+                Err(Error::new(Span::call_site(), "Invalid size attribute parsing"))
+            }
+        } else {
+            Err(Error::new(Span::call_site(), "Invalid size attribute parsing"))
+        }
+    }
+}
+
+pub struct AlignStruct {
+    input: DeriveInput,
+    layout: Layout,
+    align_layout: Layout,
+}
+
+struct FiledExt<'a> {
+    ty: &'a Type,
+    name: Option<&'a Ident>,
+}
+
+impl<'a>FiledExt<'a> {
+    pub fn new(ty: &'a Type, name: Option<&'a Ident>) -> Self {
+        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!{
+            #name: #ty,
+        }
+    }
+}
+
+impl AlignStruct {
+    pub fn new(layout: Layout, input: DeriveInput) -> Self {
+        AlignStruct {
+            input,
+            layout,
+            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")) {
+            panic!("Structure attribute must require repr C ");
+        }
+
+        let pad_item = self.get_align_pad_field();
+        let attrs = self.get_attrs();
+        let vis = &self.input.vis;
+        let name = &self.input.ident;
+        let generics = &self.input.generics;
+        let fields = &self.get_origin_fields();
+        let align_attr = &self.generate_align_attr();
+        quote!{
+            #attrs
+            #align_attr
+            #vis struct #name#generics {
+            #pad_item,
+            #fields   
+            }
+        }
+    }
+
+    fn is_contains_specified_attr(&self, atrr: &str) -> bool {
+        let mut erxcept_attr = false;
+        for attr in &self.input.attrs {
+            let ident = attr.path.get_ident();
+            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);
+                                }
+                            }    
+                            find
+                        })
+                        .next().is_some();
+                    }
+                }
+            }
+        }
+        erxcept_attr
+    }
+
+    fn get_attrs(&self) -> proc_macro2::TokenStream {
+        let attrs = &self.input.attrs;
+        quote!{
+            #(#attrs)*
+        }
+    }
+
+    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!{
+           #[repr(align(#litint))]
+        }
+    }
+
+    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)*
+                    }
+            } else {
+                panic!("Structure fields must have names");
+            }
+        } else {
+            panic!("Only supports struct type");
+        }
+    }
+
+    fn get_align_pad_field(&mut self) -> proc_macro2::TokenStream {
+        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");
+        self.align_layout = align_layout;
+        let pad = align_layout.size() - align_layout.align() - self.layout.size();
+        let ty: syn::Type = parse_quote!([u8; #pad]);
+        let name = Ident::new("no_secret_allowed_in_here", Span::call_site());
+        quote! {
+            #name: #ty
+        }
+    }
+}
\ No newline at end of file
diff --git a/sgx_align_struct_attribute/src/layout.rs b/sgx_align_struct_attribute/src/layout.rs
new file mode 100644
index 0000000..80b7c0e
--- /dev/null
+++ b/sgx_align_struct_attribute/src/layout.rs
@@ -0,0 +1,199 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License..
+
+use std::alloc::Layout;
+use std::ptr;
+use std::fmt;
+use std::mem;
+use std::slice;
+use std::ffi::c_void;
+
+#[derive(Clone, Copy, Default)]
+pub struct AlignReq {
+    pub offset: usize,
+    pub len: usize,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct AlighAllocErr;
+
+impl fmt::Display for AlighAllocErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("memory allocation failed")
+    }
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct AlignLayoutErr;
+
+impl fmt::Display for AlignLayoutErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("invalid parameters to align Layout")
+    }
+}
+
+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)
+}
+
+fn padding_needed_for(layout: Layout, align_req: &[AlignReq]) -> Result<usize, AlignLayoutErr> {
+    if !check_layout(&layout) {
+        return Err(AlignLayoutErr);
+    }
+    if !check_align_req(layout.size(), align_req) {
+        return Err(AlignLayoutErr);
+    }
+    let bmp = make_bitmap(align_req);
+    let offset = calc_lspc(layout.align(), bmp);
+    if offset < 0 {
+        Err(AlignLayoutErr)
+    } else {
+        Ok(offset as usize)
+    }
+}
+
+fn align_needed_for(layout: Layout, offset: usize) -> Result<usize, AlignLayoutErr> {
+    Ok(calc_algn(layout.align(), layout.size() + offset))
+}
+
+#[inline]
+fn check_overflow(buf: usize, len: usize) -> bool {
+    (buf + len < len) || (buf + len < buf)
+}
+
+fn check_layout(layout: &Layout) -> bool {
+    if layout.size() == 0 || !layout.align().is_power_of_two() ||
+        layout.size() > usize::max_value() - (layout.align() - 1) {
+        false
+    } else {
+        true
+    }
+}
+
+fn check_align_req(size: usize, align_req: &[AlignReq]) -> bool {
+    if align_req.len() == 0 {
+        return false;
+    }
+    let len: usize = (size + 7) / 8;
+    let bmp: &mut [u8] = unsafe {
+        let ptr = libc::malloc(len) as *mut u8;
+        if ptr.is_null() {
+            return false;
+        }
+        ptr::write_bytes(ptr, 0, len);
+        slice::from_raw_parts_mut(ptr, len)
+    };
+
+    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); }
+            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); }
+                    return false;
+                }
+                let tmp: u8 = (1 << (offset % 8)) as u8;
+                bmp[offset / 8] |= tmp;
+            }
+        }
+    }
+    true
+}
+
+fn gen_alignmask(al: usize, a: usize, m: u64) -> i64 {
+    if a  > al {
+        gen_alignmask(al, (a >> 1) as usize, m | (m >> (a >> 1)))
+    } else {
+        m as i64
+    }
+}
+
+#[inline]
+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
+}
+
+fn ror(v: i64, c: usize) -> i64 {
+    rol(v, (0 - c as isize) as usize)
+}
+
+fn count_lzb(bmp: i64) -> i32 {
+    if bmp == 0 {
+        -1
+    } else if bmp < 0 {
+        0
+    } else {
+        count_lzb(bmp << 1) + 1
+    }
+}
+
+fn calc_lspc(al: usize, bmp: i64) -> i32 {
+    if !al.is_power_of_two() {
+        -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)))
+    }
+}
+
+fn __calc_algn(size: usize, a: usize) -> usize {
+    if a > 8 && size <= a / 2 {
+        __calc_algn(size, a / 2)
+    } else {
+        a
+    }
+}
+
+fn calc_algn(al: usize, size: usize) -> usize {
+    if al > 64  {
+        al
+    } else {
+        __calc_algn(size, mem::size_of::<u64>() * 8)
+    }
+}
+
+fn make_bitmap(align_req: &[AlignReq]) -> i64 {
+    let mut bmp: i64 = 0;
+    for req in align_req {
+        if req.len > 63 {
+            return -1;
+        } else {
+            bmp |= rol(((1 as i64) << req.len) - 1, req.offset);
+        }
+    }
+    bmp
+}
+
+mod libc {
+    use std::ffi::c_void;
+    extern {
+        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_crypto_helper/build.rs b/sgx_align_struct_attribute/src/lib.rs
similarity index 58%
rename from sgx_crypto_helper/build.rs
rename to sgx_align_struct_attribute/src/lib.rs
index f796bbf..5a48c34 100644
--- a/sgx_crypto_helper/build.rs
+++ b/sgx_align_struct_attribute/src/lib.rs
@@ -15,11 +15,19 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use std::env;
+extern crate proc_macro;
+use syn::{parse_macro_input, DeriveInput};
+use align::{AlignArgs, AlignStruct};
 
-fn main() {
-    let sdk_dir = env::var("SGX_SDK").unwrap_or_else(|_| "/opt/intel/sgxsdk".to_string());
+mod align;
+mod layout;
 
-    println!("cargo:rustc-link-search=native={}/lib64", sdk_dir);
-    println!("cargo:rustc-link-lib=static=sgx_tcrypto");
+#[proc_macro_attribute]
+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 mut alignstruct = AlignStruct::new(layout, input);
+    let expanded = alignstruct.build();
+    proc_macro::TokenStream::from(expanded)
 }
diff --git a/sgx_alloc/Cargo.toml b/sgx_alloc/Cargo.toml
index 8070eee..87c00bf 100644
--- a/sgx_alloc/Cargo.toml
+++ b/sgx_alloc/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_alloc"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tse/src/alignalloc.rs b/sgx_alloc/src/alignalloc.rs
similarity index 88%
rename from sgx_tse/src/alignalloc.rs
rename to sgx_alloc/src/alignalloc.rs
index 7774cc5..e20d85a 100644
--- a/sgx_tse/src/alignalloc.rs
+++ b/sgx_alloc/src/alignalloc.rs
@@ -18,12 +18,17 @@
 //! # align alloc crate for Rust SGX SDK
 //!
 
-use sgx_types::*;
 use core::alloc::Layout;
 use core::ptr::NonNull;
 use core::fmt;
 pub use self::platform::*;
 
+#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
+pub struct AlignReq {
+    pub offset: usize,
+    pub len: usize,
+}
+
 pub struct AlignAlloc;
 
 impl AlignAlloc {
@@ -39,12 +44,12 @@ impl AlignAlloc {
     }
 
     #[inline]
-    pub unsafe fn alloc_with_req(&mut self, layout: Layout, align_req: &[align_req_t]) -> 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: &[align_req_t])
+    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)
     }
@@ -61,12 +66,12 @@ impl AlignAlloc {
     }
 
     #[inline]
-    pub unsafe fn dealloc(&mut self, ptr: core::ptr::NonNull<u8>, layout: Layout) {
+    pub unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
         platform::dealloc(ptr.as_ptr(), layout)
     }
 
     #[inline]
-    pub fn pad_align_to(&self, layout: Layout, align_req: &[align_req_t]) -> Result<Layout, AlignLayoutErr> {
+    pub fn pad_align_to(&self, layout: Layout, align_req: &[AlignReq]) -> Result<Layout, AlignLayoutErr> {
         platform::pad_align_to(layout, align_req)
     }
 }
@@ -90,8 +95,8 @@ impl fmt::Display for AlignLayoutErr {
 }
 
 mod platform {
-    use sgx_types::*;
     use super::AlignLayoutErr;
+    use super::AlignReq;
     use core::ffi::c_void;
     use core::ptr;
     use core::mem;
@@ -100,18 +105,18 @@ mod platform {
 
     #[inline]
     pub unsafe fn alloc(layout: Layout) -> *mut u8 {
-        let req: [align_req_t; 1] = [align_req_t{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)
     }
 
-    pub unsafe fn alloc_with_req(layout: Layout, align_req: &[align_req_t]) -> *mut u8 {
+    pub unsafe fn alloc_with_req(layout: Layout, align_req: &[AlignReq]) -> *mut u8 {
         if !check_layout(&layout) {
             return ptr::null_mut();
         }
         let align_layout = match
             if align_req.len() == 0 {
-                let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+                let req: [AlignReq; 1] = [AlignReq{ offset: 0, len: layout.size() }];
                 pad_align_to(layout, &req[..])
             } else {
                 pad_align_to(layout, align_req)
@@ -130,18 +135,18 @@ mod platform {
 
     #[inline]
     pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
-        let req: [align_req_t; 1] = [align_req_t{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)
     }
 
-    pub unsafe fn alloc_with_req_zeroed(layout: Layout, align_req: &[align_req_t]) -> *mut u8 {
+    pub unsafe fn alloc_with_req_zeroed(layout: Layout, align_req: &[AlignReq]) -> *mut u8 {
         if !check_layout(&layout) {
             return ptr::null_mut();
         }
         let align_layout = match
             if align_req.len() == 0 {
-                let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+                let req: [AlignReq; 1] = [AlignReq{ offset: 0, len: layout.size() }];
                 pad_align_to(layout, &req[..])
             } else {
                 pad_align_to(layout, align_req)
@@ -192,13 +197,13 @@ mod platform {
         libc::free(raw as *mut c_void)
     }
 
-    pub fn pad_align_to(layout: Layout, align_req: &[align_req_t]) -> Result<Layout, AlignLayoutErr> {
+    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)
     }
 
-    fn padding_needed_for(layout: Layout, align_req: &[align_req_t]) -> Result<usize, AlignLayoutErr> {
+    fn padding_needed_for(layout: Layout, align_req: &[AlignReq]) -> Result<usize, AlignLayoutErr> {
         if !check_layout(&layout) {
             return Err(AlignLayoutErr);
         }
@@ -225,7 +230,7 @@ mod platform {
 
     #[inline]
     fn check_overflow(buf: usize, len: usize) -> bool {
-        ((buf + len < len) || (buf + len < buf))
+        (buf + len < len) || (buf + len < buf)
     }
 
     fn check_layout(layout: &Layout) -> bool {
@@ -237,7 +242,7 @@ mod platform {
         }
     }
 
-    fn check_align_req(size: usize, align_req: &[align_req_t]) -> bool {
+    fn check_align_req(size: usize, align_req: &[AlignReq]) -> bool {
         if align_req.len() == 0 {
             return false;
         }
@@ -329,7 +334,7 @@ mod platform {
         }
     }
 
-    fn make_bitmap(align_req: &[align_req_t]) -> i64 {
+    fn make_bitmap(align_req: &[AlignReq]) -> i64 {
         let mut bmp: i64 = 0;
         for req in align_req {
             if req.len > 63 {
@@ -345,8 +350,8 @@ mod platform {
         use core::ffi::c_void;
         type size_t = usize;
         extern {
-            pub fn malloc(size: size_t) -> * mut c_void;
+            pub fn malloc(size: size_t) -> *mut c_void;
             pub fn free(p: *mut c_void);
         }
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_tse/src/alignbox.rs b/sgx_alloc/src/alignbox.rs
similarity index 78%
rename from sgx_tse/src/alignbox.rs
rename to sgx_alloc/src/alignbox.rs
index 32cc2af..0af1472 100644
--- a/sgx_tse/src/alignbox.rs
+++ b/sgx_alloc/src/alignbox.rs
@@ -17,15 +17,17 @@
 
 //! # align box crate for Rust SGX SDK
 //!
-use sgx_types::*;
+
 use core::ptr::{Unique, NonNull};
 use core::ops::{DerefMut, Deref};
 use core::mem;
 use core::ptr;
 use core::fmt;
 use core::borrow;
-use alloc::alloc::{Layout, handle_alloc_error};
+use core::alloc::Layout;
+use alloc::alloc::handle_alloc_error;
 use super::alignalloc::AlignAlloc;
+pub use super::alignalloc::AlignReq;
 
 pub struct AlignBox<T> {
     ptr: Unique<T>,
@@ -103,23 +105,35 @@ impl<T: Clone> Clone for AlignBox<T> {
             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())};
-        AlignBox {ptr: ptr.cast().into(), align_layout: self.align_layout, origin_layout: self.origin_layout}
+        unsafe {
+            ptr::copy_nonoverlapping(&(**self).clone() as *const _ as *const u8,
+                                     ptr.as_ptr(), 
+                                     self.origin_layout.size());
+        }
+        AlignBox {
+            ptr: ptr.cast().into(),
+            align_layout: self.align_layout,
+            origin_layout: self.origin_layout,
+        }
     }
 
     #[inline]
     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)} {
+            let ptr = match unsafe {
+                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();
-        }  else   {
+        } else {
             (**self).clone_from(&(**source));
         }
         self.align_layout = source.align_layout;
@@ -146,7 +160,7 @@ unsafe impl<#[may_dangle] T> Drop for AlignBox<T> {
 
 impl<T> AlignBox<T> {
 
-    fn new_with_req_in(align: usize, align_req: &[align_req_t]) -> Option<Self> {
+    fn new_with_req_in(align: usize, align_req: &[AlignReq]) -> Option<Self> {
         if align_req.len() == 0 {
             AlignBox::new_in()
         } else {
@@ -155,42 +169,46 @@ impl<T> AlignBox<T> {
     }
 
     fn new_with_align_in(align: usize) -> Option<Self> {
-        let v: [align_req_t; 1] = [align_req_t{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<Self> {
-        let v: [align_req_t; 1] = [align_req_t{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)
     }
 
-    fn allocate_in(zeroed: bool, align: usize, align_req: &[align_req_t]) -> Option<Self> {
+    fn allocate_in(zeroed: bool, align: usize, align_req: &[AlignReq]) -> Option<Self> {
         if mem::size_of::<T>() == 0 {
             return None;
         }
 
         let layout = match Layout::from_size_align(mem::size_of::<T>(), align) {
-            Ok(n) => {n},
-            Err(_) => {return None},
+            Ok(n) => n,
+            Err(_) => return None,
         };
     
         let align_layout = match AlignAlloc.pad_align_to(layout, align_req) {
-            Ok(n) => {n},
-            Err(_) => {return None},
+            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(),
             Err(_) => handle_alloc_error(align_layout),
         };
 
-        Some(AlignBox{ptr: ptr.into(), align_layout: align_layout, origin_layout: layout})
+        Some(AlignBox{
+                ptr: ptr.into(),
+                align_layout: align_layout,
+                origin_layout: layout,
+        })
     }
 }
 
@@ -201,7 +219,7 @@ impl<T> AlignBox<T> {
      pub fn new_with_align(align: usize) -> Option<Self> {
         Self::new_with_align_in(align)
     }
-    pub fn new_with_req(align: usize, align_req: &[align_req_t]) -> Option<Self> {
+    pub fn new_with_req(align: usize, align_req: &[AlignReq]) -> Option<Self> {
         Self::new_with_req_in(align, align_req)
     }
 }
@@ -233,7 +251,7 @@ impl<T> AlignBox<T> {
             t
         }
     }
-    pub fn heap_init_with_req<F>(initialize: F, align: usize, data: &[align_req_t]) -> Option<Self>
+    pub fn heap_init_with_req<F>(initialize: F, align: usize, data: &[AlignReq]) -> Option<Self>
     where
         F: Fn(&mut T),
     {
diff --git a/sgx_alloc/src/lib.rs b/sgx_alloc/src/lib.rs
index 7fcf526..f07af9c 100644
--- a/sgx_alloc/src/lib.rs
+++ b/sgx_alloc/src/lib.rs
@@ -28,137 +28,16 @@
 
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
 
+#![feature(alloc_layout_extra)]
+#![feature(ptr_internals)]
+#![feature(dropck_eyepatch)]
 #![feature(allocator_api)]
 
-use core::alloc::{GlobalAlloc, Alloc, AllocErr, Layout};
-use core::ptr::NonNull;
+extern crate alloc;
 
-// The minimum alignment guaranteed by the architecture. This value is used to
-// add fast paths for low alignment values. In practice, the alignment is a
-// constant at the call site and the branch will be optimized out.
-#[cfg(target_arch = "x86")]
-const MIN_ALIGN: usize = 8;
+mod system;
+pub use system::System;
 
-// The alignment of sgx tlibc is 8
-// https://github.com/intel/linux-sgx/blob/master/sdk/tlibc/stdlib/malloc.c#L541
-#[cfg(target_arch = "x86_64")]
-const MIN_ALIGN: usize = 8;
-
-pub struct System;
-
-unsafe impl Alloc for System {
-    #[inline]
-    unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
-        NonNull::new(GlobalAlloc::alloc(self, layout)).ok_or(AllocErr)
-    }
-
-    #[inline]
-    unsafe fn alloc_zeroed(&mut self, layout: Layout)
-        -> Result<NonNull<u8>, AllocErr>
-    {
-        NonNull::new(GlobalAlloc::alloc_zeroed(self, layout)).ok_or(AllocErr)
-    }
-
-    #[inline]
-    unsafe fn dealloc(&mut self, ptr: core::ptr::NonNull<u8>, layout: Layout) {
-        GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
-    }
-
-    #[inline]
-    unsafe fn realloc(&mut self,
-                      ptr: core::ptr::NonNull<u8>,
-                      layout: Layout,
-                      new_size: usize) -> Result<NonNull<u8>, AllocErr> {
-        NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
-    }
-}
-
-mod realloc_fallback {
-    use core::alloc::{GlobalAlloc, Layout};
-    use core::cmp;
-    use core::ptr;
-
-    impl super::System {
-        pub(crate) unsafe fn realloc_fallback(&self, ptr: *mut u8, old_layout: Layout,
-                                              new_size: usize) -> *mut u8 {
-            // Docs for GlobalAlloc::realloc require this to be valid:
-            let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align());
-
-            let new_ptr = GlobalAlloc::alloc(self, new_layout);
-            if !new_ptr.is_null() {
-                let size = cmp::min(old_layout.size(), new_size);
-                ptr::copy_nonoverlapping(ptr, new_ptr, size);
-                GlobalAlloc::dealloc(self, ptr, old_layout);
-            }
-            new_ptr
-        }
-    }
-}
-
-mod platform {
-    use super::*;
-    use libc;
-    use core::ffi::c_void;
-    use core::ptr;
-    use core::alloc::{GlobalAlloc, Layout};
-
-    unsafe impl GlobalAlloc for System {
-        #[inline]
-        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
-            if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
-                libc::malloc(layout.size()) as *mut u8
-            } else {
-                aligned_malloc(&layout)
-            }
-        }
-
-        #[inline]
-        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 {
-                let ptr = self.alloc(layout);
-                if !ptr.is_null() {
-                    ptr::write_bytes(ptr, 0, layout.size());
-                }
-                ptr
-            }
-        }
-
-        #[inline]
-        unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
-            libc::free(ptr as *mut c_void)
-        }
-
-        #[inline]
-        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 {
-                self.realloc_fallback(ptr, layout, new_size)
-            }
-        }
-    }
-
-    #[inline]
-    unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
-        libc::memalign(layout.align(), layout.size()) as *mut u8
-    }
-}
-
-mod libc {
-    use core::ffi::c_void;
-    type size_t = usize;
-    extern {
-        pub fn calloc(nobj: size_t, size: size_t) -> * mut c_void;
-        pub fn malloc(size: size_t) -> * mut c_void;
-        pub fn realloc(p: * mut c_void, size: size_t) -> * mut c_void;
-        pub fn free(p: * mut c_void);
-        pub fn memalign(align: size_t, size: size_t) -> *mut c_void;
-    }
-}
\ No newline at end of file
+pub mod alignalloc;
+pub mod alignbox;
+pub mod rsrvmem;
diff --git a/sgx_alloc/src/rsrvmem.rs b/sgx_alloc/src/rsrvmem.rs
new file mode 100644
index 0000000..3d54e42
--- /dev/null
+++ b/sgx_alloc/src/rsrvmem.rs
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License..
+
+use core::ptr::NonNull;
+use core::fmt;
+pub use self::platform::*;
+
+pub struct RsrvMemAlloc;
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub enum ProtectAttr {
+    Read,
+    ReadWrite,
+    ReadExec,
+    ReadWriteExec,
+}
+
+impl RsrvMemAlloc {
+    #[inline]
+    /// Allocate a range of EPC memory from the reserved memory area with RW permission
+    ///
+    /// # Parameters
+    ///
+    /// **count**
+    ///
+    /// Count of pages to allocate region
+    ///
+    /// # Return value
+    ///
+    /// Starting address of the new allocated memory area on success;
+    ///
+    pub unsafe fn alloc(&mut self, count: u32) -> Result<NonNull<u8>, RsrvMemAllocErr> {
+        NonNull::new(platform::alloc(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)
+    }
+
+    /// Free a range of EPC memory from the reserved memory area
+    ///
+    /// # Parameters
+    ///
+    /// ** ptr**
+    ///
+    /// Starting address of region to be freed. Page aligned.
+    ///
+    /// **count**
+    ///
+    /// Count of pages to allocate region
+    ///
+    #[inline]
+    pub unsafe fn dealloc(&mut self, addr: NonNull<u8>, count: u32) -> Result<(), RsrvMemAllocErr> {
+        platform::dealloc(addr.as_ptr(), count)
+    }
+
+    /// Modify the access permissions of the pages in the reserved memory area.
+    ///
+    /// # Parameters
+    ///
+    /// # Parameters
+    ///
+    /// ** ptr**
+    ///
+    /// Starting address of region to be freed. Page aligned.
+    ///
+    /// **count**
+    ///
+    /// Count of pages to allocate region
+    ///
+    /// **port**
+    ///
+    /// The target memory protection.
+    ///
+    #[inline]
+    pub unsafe fn protect(&self, addr: NonNull<u8>, count: u32, prot: ProtectAttr) -> Result<(), RsrvMemAllocErr> {
+        platform::protect(addr.as_ptr(), count, prot)
+    }
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct RsrvMemAllocErr;
+
+impl fmt::Display for RsrvMemAllocErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("reserves memory allocation failed")
+    }
+}
+
+mod platform {
+    use super::RsrvMemAllocErr;
+    use super::ProtectAttr;
+    use core::ffi::c_void;
+    use core::ptr;
+
+    const SGX_PROT_READ:  u32 = 0x1;
+    const SGX_PROT_WRITE: u32 = 0x2;
+    const SGX_PROT_EXEC:  u32 = 0x4;
+    const SE_PAGE_SIZE:   usize =  0x1000;
+
+    type size_t = usize;
+    type int32_t = i32;
+    type sgx_status_t = u32;
+
+    extern {
+        pub fn sgx_alloc_rsrv_mem(length: size_t) -> *mut c_void;
+        pub fn sgx_free_rsrv_mem(addr: *const c_void, length: size_t) -> int32_t;
+        pub fn sgx_tprotect_rsrv_mem(addr: *const c_void, length: size_t, prot: i32) -> sgx_status_t;  
+    }
+
+    #[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_zeroed(count: u32) -> *mut u8 {
+        let raw = alloc(count);
+        if !raw.is_null() {
+            ptr::write_bytes(raw, 0, count as usize * SE_PAGE_SIZE);
+        }
+        raw
+    }
+
+    #[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 {
+            Ok(())
+        } else {
+            Err(RsrvMemAllocErr)
+        }
+    }
+
+    #[inline]
+    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 },
+        };
+        if sgx_tprotect_rsrv_mem(addr as *const c_void,
+                                 count as usize * SE_PAGE_SIZE,
+                                 attr as i32) == 0 {
+            Ok(())
+        } else {
+            Err(RsrvMemAllocErr) 
+        }
+    }
+}
diff --git a/sgx_alloc/src/lib.rs b/sgx_alloc/src/system.rs
similarity index 69%
copy from sgx_alloc/src/lib.rs
copy to sgx_alloc/src/system.rs
index 7fcf526..3b29cdb 100644
--- a/sgx_alloc/src/lib.rs
+++ b/sgx_alloc/src/system.rs
@@ -22,15 +22,7 @@
 //! It is essential, because we depends on Intel SGX's SDK.
 //! 2018-06-22 Add liballoc components here
 
-#![no_std]
-
-#![allow(non_camel_case_types)]
-
-#![cfg_attr(target_env = "sgx", feature(rustc_private))]
-
-#![feature(allocator_api)]
-
-use core::alloc::{GlobalAlloc, Alloc, AllocErr, Layout};
+use core::alloc::{GlobalAlloc, AllocRef, AllocErr, Layout};
 use core::ptr::NonNull;
 
 // The minimum alignment guaranteed by the architecture. This value is used to
@@ -39,37 +31,66 @@ use core::ptr::NonNull;
 #[cfg(target_arch = "x86")]
 const MIN_ALIGN: usize = 8;
 
-// The alignment of sgx tlibc is 8
+// The alignment of sgx tlibc is 16
 // https://github.com/intel/linux-sgx/blob/master/sdk/tlibc/stdlib/malloc.c#L541
 #[cfg(target_arch = "x86_64")]
-const MIN_ALIGN: usize = 8;
+const MIN_ALIGN: usize = 16;
 
 pub struct System;
 
-unsafe impl Alloc for System {
+unsafe impl AllocRef for System {
     #[inline]
-    unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
-        NonNull::new(GlobalAlloc::alloc(self, layout)).ok_or(AllocErr)
+    fn alloc(&mut self, layout: Layout) -> Result<(NonNull<u8>, usize), AllocErr> {
+        if layout.size() == 0 {
+            Ok((layout.dangling(), 0))
+        } else {
+            unsafe {
+                NonNull::new(GlobalAlloc::alloc(self, layout))
+                    .ok_or(AllocErr)
+                    .map(|p| (p, layout.size()))
+            }
+        }
     }
 
     #[inline]
-    unsafe fn alloc_zeroed(&mut self, layout: Layout)
-        -> Result<NonNull<u8>, AllocErr>
+    fn alloc_zeroed(&mut self, layout: Layout)
+        -> Result<(NonNull<u8>, usize), AllocErr>
     {
-        NonNull::new(GlobalAlloc::alloc_zeroed(self, layout)).ok_or(AllocErr)
+        if layout.size() == 0 {
+            Ok((layout.dangling(), 0))
+        } else {
+            unsafe {
+                NonNull::new(GlobalAlloc::alloc_zeroed(self, layout))
+                    .ok_or(AllocErr)
+                    .map(|p| (p, layout.size()))
+            }
+        }
     }
 
     #[inline]
     unsafe fn dealloc(&mut self, ptr: core::ptr::NonNull<u8>, layout: Layout) {
-        GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
+        if layout.size() != 0 {
+            GlobalAlloc::dealloc(self, ptr.as_ptr(), layout)
+        }
     }
 
     #[inline]
     unsafe fn realloc(&mut self,
                       ptr: core::ptr::NonNull<u8>,
                       layout: Layout,
-                      new_size: usize) -> Result<NonNull<u8>, AllocErr> {
-        NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
+                      new_size: usize) -> Result<(NonNull<u8>, usize), AllocErr> {
+        //NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
+        match (layout.size(), new_size) {
+            (0, 0) => Ok((layout.dangling(), 0)),
+            (0, _) => self.alloc(Layout::from_size_align_unchecked(new_size, layout.align())),
+            (_, 0) => {
+                self.dealloc(ptr, layout);
+                Ok((layout.dangling(), 0))
+            }
+            (_, _) => NonNull::new(GlobalAlloc::realloc(self, ptr.as_ptr(), layout, new_size))
+                .ok_or(AllocErr)
+                .map(|p| (p, new_size)),
+        }
     }
 }
 
@@ -155,10 +176,10 @@ mod libc {
     use core::ffi::c_void;
     type size_t = usize;
     extern {
-        pub fn calloc(nobj: size_t, size: size_t) -> * mut c_void;
-        pub fn malloc(size: size_t) -> * mut c_void;
-        pub fn realloc(p: * mut c_void, size: size_t) -> * mut c_void;
-        pub fn free(p: * mut c_void);
+        pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void;
+        pub fn malloc(size: size_t) -> *mut c_void;
+        pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void;
+        pub fn free(p: *mut c_void);
         pub fn memalign(align: size_t, size: size_t) -> *mut c_void;
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_backtrace/Cargo.toml b/sgx_backtrace/Cargo.toml
index 8b823b1..fa6f50c 100644
--- a/sgx_backtrace/Cargo.toml
+++ b/sgx_backtrace/Cargo.toml
@@ -1,7 +1,7 @@
 
 [package]
 name = "sgx_backtrace"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_backtrace_sys/Cargo.toml b/sgx_backtrace_sys/Cargo.toml
index 392d15c..4f44fbc 100644
--- a/sgx_backtrace_sys/Cargo.toml
+++ b/sgx_backtrace_sys/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_backtrace_sys"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 build = "build.rs"
 repository = "https://github.com/apache/teaclave-sgx-sdk"
diff --git a/sgx_backtrace_sys/build.rs b/sgx_backtrace_sys/build.rs
index 99100df..7ac756f 100644
--- a/sgx_backtrace_sys/build.rs
+++ b/sgx_backtrace_sys/build.rs
@@ -26,7 +26,12 @@ fn main() {
 }
 
 fn build_libbacktrace(_target: &str) -> Result<(), ()> {
-    let native = native_lib_boilerplate("sgx_backtrace_sys/libbacktrace", "libbacktrace", "backtrace", "")?;
+    let native = native_lib_boilerplate(
+                    "sgx_backtrace_sys/libbacktrace",
+                    "libbacktrace",
+                    "backtrace",
+                    "",
+                    &vec![])?;
 
     let mut build = cc::Build::new();
     build
diff --git a/sgx_build_helper/lib.rs b/sgx_build_helper/lib.rs
index bb1cbff..106c45a 100644
--- a/sgx_build_helper/lib.rs
+++ b/sgx_build_helper/lib.rs
@@ -14,6 +14,7 @@ use std::process::{Command, Stdio};
 use std::time::{SystemTime, UNIX_EPOCH};
 use std::{env, fs};
 use std::thread;
+use std::ffi::OsStr;
 
 /// A helper macro to `unwrap` a result except also print out details like:
 ///
@@ -129,22 +130,29 @@ pub fn output(cmd: &mut Command) -> String {
     String::from_utf8(output.stdout).unwrap()
 }
 
-pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
+pub fn rerun_if_changed_anything_in_dir(dir: &Path, filter: &Vec<&str>) {
     let mut stack = dir.read_dir()
         .unwrap()
         .map(|e| e.unwrap())
-        .filter(|e| &*e.file_name() != ".git")
+        .filter(|e| !is_in_filter_list(&*e.file_name(), filter))
         .collect::<Vec<_>>();
     while let Some(entry) = stack.pop() {
         let path = entry.path();
         if entry.file_type().unwrap().is_dir() {
-            stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
+            stack.extend(path.read_dir()
+                .unwrap()
+                .map(|e| e.unwrap())
+                .filter(|e| !is_in_filter_list(&*e.file_name(), filter)));
         } else {
             println!("cargo:rerun-if-changed={}", path.display());
         }
     }
 }
 
+fn is_in_filter_list(elem: &OsStr, filter: &Vec<&str>) -> bool {
+    filter.iter().any(|e| *e == elem) || elem == ".git"
+}
+
 /// Returns the last-modified time for `path`, or zero if it doesn't exist.
 pub fn mtime(path: &Path) -> SystemTime {
     fs::metadata(path)
@@ -228,10 +236,11 @@ pub fn native_lib_boilerplate(
     out_name: &str,
     link_name: &str,
     search_subdir: &str,
+    filter: &Vec<&str>,
 ) -> Result<NativeLibBoilerplate, ()> {
     let current_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
     let src_dir = current_dir.join("..").join(src_name);
-    rerun_if_changed_anything_in_dir(&src_dir);
+    rerun_if_changed_anything_in_dir(&src_dir, filter);
 
     let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or_else(||
         env::var_os("OUT_DIR").unwrap());
@@ -284,6 +293,7 @@ pub fn sanitizer_lib_boilerplate(sanitizer_name: &str)
         sanitizer_name,
         &to_link,
         search_path,
+        &vec![],
     )?;
     Ok((lib, link_name))
 }
diff --git a/sgx_alloc/Cargo.toml b/sgx_core_futures/Cargo.toml
similarity index 80%
copy from sgx_alloc/Cargo.toml
copy to sgx_core_futures/Cargo.toml
index 8070eee..d40cf57 100644
--- a/sgx_alloc/Cargo.toml
+++ b/sgx_core_futures/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
-name = "sgx_alloc"
-version = "1.1.0"
+name = "sgx_core_futures"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
@@ -9,8 +9,7 @@ description = "Rust SGX SDK provides the ability to write Intel SGX applications
 edition = "2018"
 
 [lib]
-name = "sgx_alloc"
+name = "sgx_core_futures"
 crate-type = ["rlib"]
 
-[features]
-default = []
+
diff --git a/sgx_tservice/LICENSE b/sgx_core_futures/LICENSE
similarity index 100%
rename from sgx_tservice/LICENSE
rename to sgx_core_futures/LICENSE
diff --git a/sgx_tservice/Readme.md b/sgx_core_futures/Readme.md
similarity index 100%
rename from sgx_tservice/Readme.md
rename to sgx_core_futures/Readme.md
diff --git a/sgx_tstd/src/future.rs b/sgx_core_futures/src/future.rs
similarity index 88%
copy from sgx_tstd/src/future.rs
copy to sgx_core_futures/src/future.rs
index 3c9d129..7c3b4bb 100644
--- a/sgx_tstd/src/future.rs
+++ b/sgx_core_futures/src/future.rs
@@ -49,24 +49,21 @@ impl<T: Generator<Yield = ()>> Future for GenFuture<T> {
     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
         // Safe because we're !Unpin + !Drop mapping to a ?Unpin value
         let gen = unsafe { Pin::map_unchecked_mut(self, |s| &mut s.0) };
-        set_task_context(cx, || match gen.resume() {
+        set_task_context(cx, || match gen.resume(()) {
             GeneratorState::Yielded(()) => Poll::Pending,
             GeneratorState::Complete(x) => Poll::Ready(x),
         })
     }
 }
 
-thread_local! {
-    static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
-}
+#[thread_local]
+static TLS_CX: Cell<Option<NonNull<Context<'static>>>> = Cell::new(None);
 
 struct SetOnDrop(Option<NonNull<Context<'static>>>);
 
 impl Drop for SetOnDrop {
     fn drop(&mut self) {
-        TLS_CX.with(|tls_cx| {
-            tls_cx.set(self.0.take());
-        });
+        TLS_CX.set(self.0.take());
     }
 }
 
@@ -79,9 +76,7 @@ where
     let cx = unsafe {
         core::mem::transmute::<&mut Context<'_>, &mut Context<'static>>(cx)
     };
-    let old_cx = TLS_CX.with(|tls_cx| {
-        tls_cx.replace(Some(NonNull::from(cx)))
-    });
+    let old_cx = TLS_CX.replace(Some(NonNull::from(cx)));
     let _reset = SetOnDrop(old_cx);
     f()
 }
@@ -96,11 +91,9 @@ pub fn get_task_context<F, R>(f: F) -> R
 where
     F: FnOnce(&mut Context<'_>) -> R
 {
-    let cx_ptr = TLS_CX.with(|tls_cx| {
-        // Clear the entry so that nested `get_task_waker` calls
-        // will fail or set their own value.
-        tls_cx.replace(None)
-    });
+    // Clear the entry so that nested `get_task_waker` calls
+    // will fail or set their own value.
+    let cx_ptr = TLS_CX.replace(None);
     let _reset = SetOnDrop(cx_ptr);
 
     let mut cx_ptr = cx_ptr.expect(
diff --git a/sgx_core_futures/src/lib.rs b/sgx_core_futures/src/lib.rs
new file mode 100644
index 0000000..f994884
--- /dev/null
+++ b/sgx_core_futures/src/lib.rs
@@ -0,0 +1,99 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License..
+
+//! Libcore wrapper allowing async/await
+//!
+//! # Usage
+//!
+//! Put the following in your Cargo.toml:
+//!
+//! ```toml
+//! [dependencies]
+//! core = { package = "sgx_core_futures", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
+//! ```
+//!
+//! # Why
+//!
+//! Currently, async/await is not usable from libcore. Attempting to call .await
+//! from a `no_std` crate will yield the following error:
+//!
+//! ```norun
+//! error[E0433]: failed to resolve: could not find `poll_with_tls_context` in `future`
+//! error[E0433]: failed to resolve: could not find `from_generator` in `future`
+//! ```
+//!
+//! This is due to await lowering to some code calling the functions
+//! `::core::futures::poll_with_tls_context` and `::core::futures::from_generator`
+//! in order to setup a per-thread context containing the current task. Those
+//! functions, however, do not exist. The equivalent functions are defined in
+//! libstd. They set up a thread-local variable which contains the current task
+//! being executed. When polling a future, this task will get retrieved in order
+//! to call the future's `poll` function.
+//!
+//! 
+//! As mentioned, the libstd version of those functions use a thread-local
+//! variable, which is only supported in rust's libstd through the
+//! `thread_local!` macro - which doesn't exist in libcore. There is, however,
+//! an alternative: The (unstable) `#[thread_local]` attribute, which uses ELF
+//! TLS. Note that ELF TLS is not portable to all targets - it needs to be
+//! supported by the OS, the loader, etc...
+//!
+//! Here's a small example of the thread_local attribute in action:
+//!
+//! ```rust
+//! #![feature(thread_local)]
+//! use core::cell::Cell;
+//! #[thread_local]
+//! static TLS_CX: Cell<i32> = Cell::new(1);
+//! ```
+//!
+//! Using this trick, we can copy paste libstd's implementation of the
+//! `poll_with_tls_context`/`from_generator` functions, but replacing the
+//! `thread_local!` macro with a `#[thread_local]` macro. Ez pz.
+//!
+//! # Wrapping libcore
+//!
+//! This trick is nice, but compiling a custom libcore is fastidious. Instead,
+//! we're going to wrap libcore, exposing our own libcore that just reexports
+//! the real libcore's functions, and adding our own extra stuff. This,
+//! surprisingly, can be done simply by declaring a `core` dependency with the
+//! `package` attribute set to our "real" crates.io package name. This will
+//! trick cargo into giving rustc our wrapper core as if it was the real
+//! libcore.
+//!
+//! So that's it. All this crate does is reexport libcore, adding a couple
+//! functions in the future module. You just have to use the following in your
+//! Cargo.toml in order to use it, and rust will happily use `core-futures-tls`
+//! as if it was the libcore.
+//!
+//! ```toml
+//! [dependencies]
+//! core = { package = "sgx_core_futures", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
+//! ```
+//!
+//! # Closing thoughts
+//!
+//! While this crate still uses TLS, it should be possible to create a version
+//! that stores the thread local context in a global for single-threaded systems
+//! such as microcontrollers. This is left as an exercise to the reader.
+
+#![no_std]
+#![cfg_attr(target_env = "sgx", feature(rustc_private))]
+#![feature(thread_local, generator_trait, optin_builtin_traits)]
+
+pub mod future;
+pub use core::*;
\ No newline at end of file
diff --git a/sgx_cov/Cargo.toml b/sgx_cov/Cargo.toml
index ec42888..45d2e07 100644
--- a/sgx_cov/Cargo.toml
+++ b/sgx_cov/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_cov"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_crypto_helper/Cargo.toml b/sgx_crypto_helper/Cargo.toml
index bd5c976..44dc589 100644
--- a/sgx_crypto_helper/Cargo.toml
+++ b/sgx_crypto_helper/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_crypto_helper"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
@@ -13,21 +13,69 @@ name = "sgx_crypto_helper"
 crate-type = ["staticlib","rlib"]
 
 [features]
-default = []
-enclave_cargo = ["sgx_tcrypto"]
+default = ["ucrypto_help"]
+ucrypto_help = [
+    "sgx_ucrypto",
+    "libc",
+    "serde",
+    "serde_derive",
+    "serde-big-array"]
+mesalock_sgx = [
+    "sgx_tcrypto",
+    "sgx_tstd",
+    "serde-sgx",
+    "serde_derive-sgx",
+    "serde-big-array-sgx"]
 
 [dependencies]
-sgx_ucrypto = { path = "../sgx_ucrypto" }
-sgx_tcrypto = { path = "../sgx_tcrypto", optional = true }
-libc = "0.2"
-serde = "1.0.98"
-serde_derive = "1.0.98"
-sgx_types = { path = "../sgx_types" }
-itertools = "*"
-serde-big-array = "0.1"
+sgx_ucrypto = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
+libc = { version = "0.2", optional = true }
+itertools = { version = "*", default-features = false }
+serde = { version = "1.0.104", optional = true }
+serde_derive = { version = "1.0.104", optional = true }
+serde-big-array = { version = "0.1", optional = true }
+serde-sgx = { git = "https://github.com/mesalock-linux/serde-sgx", package = 'serde', optional = true }
+serde_derive-sgx = { git = "https://github.com/mesalock-linux/serde-sgx", package = 'serde_derive', optional = true }
+serde-big-array-sgx = { git = "https://github.com/mesalock-linux/serde-big-array-sgx", package = 'serde-big-array', optional = true }
+
+[target.'cfg(not(target_env = "sgx"))'.dependencies]
+sgx_tcrypto = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
+sgx_tstd    = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
+sgx_types   = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 
 [dev-dependencies]
-sgx_ucrypto = { path = "../sgx_ucrypto" }
+sgx_ucrypto = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
 rdrand = "0.6"
 rand_core = "0.4"
 serde_json = "*"
+
+[patch.'https://github.com/apache/teaclave-sgx-sdk.git']
+sgx_align_struct_attribute = { path = "../sgx_align_struct_attribute" }
+sgx_alloc = { path = "../sgx_alloc" }
+sgx_backtrace = { path = "../sgx_backtrace" }
+sgx_backtrace_sys = { path = "../sgx_backtrace_sys" }
+sgx_build_helper = { path = "../sgx_build_helper" }
+sgx_cov = { path = "../sgx_cov" }
+sgx_crypto_helper = { path = "../sgx_crypto_helper" }
+sgx_demangle = { path = "../sgx_demangle" }
+sgx_libc = { path = "../sgx_libc" }
+sgx_no_tstd = { path = "../sgx_no_tstd" }
+sgx_rand = { path = "../sgx_rand" }
+sgx_rand_derive = { path = "../sgx_rand_derive" }
+sgx_serialize = { path = "../sgx_serialize" }
+sgx_serialize_derive = { path = "../sgx_serialize_derive" }
+sgx_serialize_derive_internals = { path = "../sgx_serialize_derive_internals" }
+sgx_tcrypto = { path = "../sgx_tcrypto" }
+sgx_tcrypto_helper = { path = "../sgx_tcrypto_helper" }
+sgx_tdh = { path = "../sgx_tdh" }
+sgx_tkey_exchange = { path = "../sgx_tkey_exchange" }
+sgx_tprotected_fs = { path = "../sgx_tprotected_fs" }
+sgx_trts = { path = "../sgx_trts" }
+sgx_tse = { path = "../sgx_tse" }
+sgx_tseal = { path = "../sgx_tseal" }
+sgx_tstd = { path = "../sgx_tstd" }
+sgx_tunittest = { path = "../sgx_tunittest" }
+sgx_types = { path = "../sgx_types" }
+sgx_ucrypto = { path = "../sgx_ucrypto" }
+sgx_unwind = { path = "../sgx_unwind" }
+#sgx_urts = { path = "../sgx_urts" }
\ No newline at end of file
diff --git a/sgx_crypto_helper/src/lib.rs b/sgx_crypto_helper/src/lib.rs
index ab03ac9..16deecc 100644
--- a/sgx_crypto_helper/src/lib.rs
+++ b/sgx_crypto_helper/src/lib.rs
@@ -67,9 +67,20 @@ pub trait RsaKeyPair {
     fn decrypt_buffer(self, ciphertext: &[u8], plaintext: &mut Vec<u8>) -> SgxResult<usize>;
 }
 
+#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
+extern crate serde_sgx;
+#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
 extern crate serde;
+
+#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
+extern crate serde_derive_sgx as serde_derive;
+#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
 extern crate serde_derive;
-extern crate itertools;
+
+#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
+#[macro_use]
+extern crate serde_big_array_sgx as serde_big_array;
+#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
 #[macro_use]
 extern crate serde_big_array;
 
diff --git a/sgx_crypto_helper/src/rsa2048.rs b/sgx_crypto_helper/src/rsa2048.rs
index be74e77..e054554 100644
--- a/sgx_crypto_helper/src/rsa2048.rs
+++ b/sgx_crypto_helper/src/rsa2048.rs
@@ -19,6 +19,27 @@ big_array! { BigArray; }
 /// implementations. The block size of plain text is 190 bytes
 /// and the block size of cipher text is 256 bytes.
 /// 190 byte = 2048bit - 2*SHA256_BYTE - 2
+#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
+#[derive(Serialize, Deserialize, Clone, Copy)]
+#[serde(crate = "serde_sgx")]
+pub struct Rsa2048KeyPair {
+    #[serde(with = "BigArray")]
+    n: [u8; SGX_RSA2048_KEY_SIZE],
+    #[serde(with = "BigArray")]
+    d: [u8; SGX_RSA2048_PRI_EXP_SIZE],
+    e: [u8; SGX_RSA2048_PUB_EXP_SIZE],
+    #[serde(with = "BigArray")]
+    p: [u8; SGX_RSA2048_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    q: [u8; SGX_RSA2048_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    dmp1: [u8; SGX_RSA2048_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    dmq1: [u8; SGX_RSA2048_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    iqmp: [u8; SGX_RSA2048_KEY_SIZE / 2],
+}
+#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
 #[derive(Serialize, Deserialize, Clone, Copy)]
 pub struct Rsa2048KeyPair {
     #[serde(with = "BigArray")]
@@ -202,6 +223,15 @@ impl Rsa2048KeyPair {
     }
 }
 
+#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
+#[derive(Serialize, Deserialize, Clone, Copy)]
+#[serde(crate = "serde_sgx")]
+pub struct Rsa2048PubKey {
+    #[serde(with = "BigArray")]
+    n: [u8; SGX_RSA2048_KEY_SIZE],
+    e: [u8; SGX_RSA2048_PUB_EXP_SIZE],
+}
+#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
 #[derive(Serialize, Deserialize, Clone, Copy)]
 pub struct Rsa2048PubKey {
     #[serde(with = "BigArray")]
diff --git a/sgx_crypto_helper/src/rsa3072.rs b/sgx_crypto_helper/src/rsa3072.rs
index fb43dc7..d9cff53 100644
--- a/sgx_crypto_helper/src/rsa3072.rs
+++ b/sgx_crypto_helper/src/rsa3072.rs
@@ -18,7 +18,9 @@ big_array! { BigArray; }
 /// implementations. The block size of plain text is 318 bytes
 /// and the block size of cipher text is 256 bytes.
 /// 318 byte = 3072bit - 2*SHA256_BYTE -2
+#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
 #[derive(Serialize, Deserialize, Clone, Copy)]
+#[serde(crate = "serde_sgx")]
 pub struct Rsa3072KeyPair {
     #[serde(with = "BigArray")]
     n: [u8; SGX_RSA3072_KEY_SIZE],
@@ -36,6 +38,26 @@ pub struct Rsa3072KeyPair {
     #[serde(with = "BigArray")]
     iqmp: [u8; SGX_RSA3072_KEY_SIZE / 2],
 }
+#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
+#[derive(Serialize, Deserialize, Clone, Copy)]
+pub struct Rsa3072KeyPair {
+    #[serde(with = "BigArray")]
+    n: [u8; SGX_RSA3072_KEY_SIZE],
+    #[serde(with = "BigArray")]
+    d: [u8; SGX_RSA3072_PRI_EXP_SIZE],
+    e: [u8; SGX_RSA3072_PUB_EXP_SIZE],
+    #[serde(with = "BigArray")]
+    p: [u8; SGX_RSA3072_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    q: [u8; SGX_RSA3072_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    dmp1: [u8; SGX_RSA3072_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    dmq1: [u8; SGX_RSA3072_KEY_SIZE / 2],
+    #[serde(with = "BigArray")]
+    iqmp: [u8; SGX_RSA3072_KEY_SIZE / 2],
+}
+
 
 impl Default for Rsa3072KeyPair {
     fn default() -> Self {
@@ -196,6 +218,15 @@ impl Rsa3072KeyPair {
     }
 }
 
+#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
+#[derive(Serialize, Deserialize, Clone, Copy)]
+#[serde(crate = "serde_sgx")]
+pub struct Rsa3072PubKey {
+    #[serde(with = "BigArray")]
+    n: [u8; SGX_RSA3072_KEY_SIZE],
+    e: [u8; SGX_RSA3072_PUB_EXP_SIZE],
+}
+#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
 #[derive(Serialize, Deserialize, Clone, Copy)]
 pub struct Rsa3072PubKey {
     #[serde(with = "BigArray")]
diff --git a/sgx_demangle/Cargo.toml b/sgx_demangle/Cargo.toml
index 81714e6..b0e19a8 100644
--- a/sgx_demangle/Cargo.toml
+++ b/sgx_demangle/Cargo.toml
@@ -1,7 +1,7 @@
 
 [package]
 name = "sgx_demangle"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_libc/Cargo.toml b/sgx_libc/Cargo.toml
index 4352e1d..bcd4509 100644
--- a/sgx_libc/Cargo.toml
+++ b/sgx_libc/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_libc"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_libc/src/linux/x86_64/mod.rs b/sgx_libc/src/linux/x86_64/mod.rs
index 2fe633f..b63a66a 100644
--- a/sgx_libc/src/linux/x86_64/mod.rs
+++ b/sgx_libc/src/linux/x86_64/mod.rs
@@ -27,30 +27,75 @@ pub use sgx_types::{c_void, c_schar, c_char, c_uchar, c_short, c_ushort, c_int,
 pub use sgx_types::{size_t, ptrdiff_t, intptr_t, uintptr_t, ssize_t};
 pub use sgx_types::time_t;
 
+use sgx_types::{sgx_thread_mutex_t, sgx_thread_mutex_attr_t, sgx_thread_cond_t, sgx_thread_cond_attr_t};
 use core::ptr;
 use core::mem;
 
 extern {
-    pub fn calloc(nobj: size_t, size: size_t) -> * mut c_void;
-    pub fn malloc(size: size_t) -> * mut c_void;
-    pub fn realloc(p: * mut c_void, size: size_t) -> * mut c_void;
-    pub fn free(p: * mut c_void);
+    pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void;
+    pub fn malloc(size: size_t) -> *mut c_void;
+    pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void;
+    pub fn free(p: *mut c_void);
     pub fn memalign(align: size_t, size: size_t) -> *mut c_void;
 }
 
+#[link(name = "sgx_pthread")]
+extern {
+    pub fn pthread_create(native: *mut pthread_t,
+                          attr: *const pthread_attr_t,
+                          f: extern fn(*mut c_void) -> *mut c_void,
+                          value: *mut c_void) -> c_int;
+    pub fn pthread_join(native: pthread_t,
+                        value: *mut *mut c_void) -> c_int;
+    pub fn pthread_exit(value: *mut c_void);
+    pub fn pthread_self() -> pthread_t;
+    pub fn pthread_equal(t1: pthread_t, t2: pthread_t) -> c_int;
+
+    pub fn pthread_once(once_control: *mut pthread_once_t, init_routine: extern fn()) -> c_int;
+
+    pub fn pthread_key_create(key: *mut pthread_key_t,
+                              dtor: Option<unsafe extern fn(*mut c_void)>) -> c_int;
+    pub fn pthread_key_delete(key: pthread_key_t) -> c_int;
+    pub fn pthread_getspecific(key: pthread_key_t) -> *mut c_void;
+    pub fn pthread_setspecific(key: pthread_key_t, value: *const c_void) -> c_int;
+    
+    pub fn pthread_mutex_init(lock: *mut pthread_mutex_t,
+                              attr: *const pthread_mutexattr_t) -> c_int;
+    pub fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> c_int;
+    pub fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> c_int;
+    pub fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> c_int;
+    pub fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> c_int;
+
+    pub fn pthread_cond_init(cond: *mut pthread_cond_t,
+                             attr: *const pthread_condattr_t) -> c_int;
+    pub fn pthread_cond_wait(cond: *mut pthread_cond_t,
+                             lock: *mut pthread_mutex_t) -> c_int;
+    pub fn pthread_cond_signal(cond: *mut pthread_cond_t) -> c_int;
+    pub fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> c_int;
+    pub fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> c_int;
+}
+
+pub type exit_function_t = extern "C" fn();
+
+#[link(name = "sgx_trts")]
+extern {
+    pub fn abort() -> !;
+    pub fn atexit(fun: exit_function_t) -> c_int;
+}
+
 #[link(name = "sgx_tstdc")]
 extern {
-    //pub fn memchr(s: * const c_void, c: c_int, n: size_t) -> *mut c_void;
+    //pub fn memchr(s: *const c_void, c: c_int, n: size_t) -> *mut c_void;
     //pub fn memrchr(cx: *const c_void, c: c_int, n: size_t) -> *mut c_void;
-    pub fn strlen(s: * const c_char) -> size_t;
-    pub fn malloc_usable_size(ptr: * const c_void) -> size_t;
+    pub fn strlen(s: *const c_char) -> size_t;
+    pub fn malloc_usable_size(ptr: *const c_void) -> size_t;
 }
 
 #[link(name = "sgx_tstdc")]
 extern {
     #[cfg_attr(target_os = "linux", link_name = "__errno_location")]
-    fn errno_location() -> * mut c_int;
-    fn strerror_r(errnum: c_int, buf: * mut c_char, buflen: size_t) -> c_int;
+    fn errno_location() -> *mut c_int;
+    fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: size_t) -> c_int;
 }
 
 /// Get the last error number.
@@ -69,16 +114,13 @@ pub fn set_errno(e: i32) {
 
 /// Gets a detailed string description for the given error number.
 pub unsafe fn error_string(errno: i32, buf: &mut [i8]) -> i32 {
-
     let p = buf.as_mut_ptr();
-    strerror_r(errno as c_int, p as * mut c_char, buf.len()) as i32
+    strerror_r(errno as c_int, p as *mut c_char, buf.len()) as i32
 }
 
-pub unsafe fn memchr(s: * const u8, c: u8, n: usize) -> * const u8 {
-
+pub unsafe fn memchr(s: *const u8, c: u8, n: usize) -> *const u8 {
     let mut ret = ptr::null();
     let mut p = s;
-
     for _ in 0..n {
         if *p == c {
             ret = p;
@@ -89,12 +131,10 @@ pub unsafe fn memchr(s: * const u8, c: u8, n: usize) -> * const u8 {
     ret
 }
 
-pub unsafe fn memrchr(s: * const u8, c: u8, n: usize) -> * const u8 {
-
-    if n == 0 {return ptr::null();}
-
+pub unsafe fn memrchr(s: *const u8, c: u8, n: usize) -> *const u8 {
+    if n == 0 { return ptr::null(); }
     let mut ret = ptr::null();
-    let mut p: * const u8 = (s as usize + (n - 1)) as * const u8;
+    let mut p: *const u8 = (s as usize + (n - 1)) as *const u8;
     for _ in 0..n {
         if *p == c {
             ret = p;
@@ -135,17 +175,29 @@ pub type uid_t = u32;
 pub type gid_t = u32;
 pub type ino64_t = u64;
 pub type nfds_t = c_ulong;
-pub type pthread_t = c_ulong;
 pub type pid_t = i32;
 
+pub type pthread_t = *mut c_void;
+pub type pthread_attr_t = *mut c_void;
+pub type pthread_mutex_t = *mut sgx_thread_mutex_t;
+pub type pthread_mutexattr_t = *mut sgx_thread_mutex_attr_t;
+pub type pthread_cond_t = *mut sgx_thread_cond_t;
+pub type pthread_condattr_t = *mut sgx_thread_cond_attr_t;
+pub type pthread_key_t = c_int;
+
+pub const PTHREAD_NEEDS_INIT: c_int = 0;
+pub const PTHREAD_DONE_INIT: c_int = 0;
+pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = ptr::null_mut();
+pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = ptr::null_mut();
+pub const PTHREAD_ONCE_INIT: pthread_once_t = pthread_once_t {
+    state: PTHREAD_NEEDS_INIT,
+    mutex: PTHREAD_MUTEX_INITIALIZER
+    };
+
 #[derive(Copy, Clone, Debug)]
 pub enum DIR {}
 
 s! {
-    #[cfg(target_arch = "x86_64")]
-    pub struct pthread_attr_t {
-       __size: [u64; 7],
-    }
     pub struct stat {
         pub st_dev: dev_t,
         pub st_ino: ino_t,
@@ -402,11 +454,25 @@ s! {
         pub pw_shell: *mut c_char,
     }
 
+    pub struct cpu_set_t {
+        #[cfg(all(target_pointer_width = "32",
+                  not(target_arch = "x86_64")))]
+        bits: [u32; 32],
+        #[cfg(not(all(target_pointer_width = "32",
+                      not(target_arch = "x86_64"))))]
+        bits: [u64; 16],
+    }
+
     pub struct ucred {
         pub pid: pid_t,
         pub uid: uid_t,
         pub gid: gid_t,
     }
+
+    pub struct pthread_once_t {
+        pub state: c_int,
+        pub mutex: pthread_mutex_t,
+    }
 }
 
 pub const AT_FDCWD: c_int = -100;
@@ -1161,6 +1227,8 @@ pub const _SC_XOPEN_STREAMS: c_int = 246;
 pub const _SC_THREAD_ROBUST_PRIO_INHERIT: c_int = 247;
 pub const _SC_THREAD_ROBUST_PRIO_PROTECT: c_int = 248;
 
+pub const CPU_SETSIZE: c_int = 0x400;
+
 pub const EPERM: int32_t              = 1;
 pub const ENOENT: int32_t             = 2;
 pub const ESRCH: int32_t              = 3;
@@ -1297,7 +1365,7 @@ pub const EHWPOISON: int32_t          = 133;
 pub const ENOTSUP: int32_t            = EOPNOTSUPP;
 pub const ESGX: int32_t               = 0x0000_FFFF;
 
-
+#[inline]
 pub unsafe fn FD_CLR(fd: c_int, set: *mut fd_set) -> () {
     let fd = fd as usize;
     let size = mem::size_of_val(&(*set).fds_bits[0]) * 8;
@@ -1305,12 +1373,14 @@ pub unsafe fn FD_CLR(fd: c_int, set: *mut fd_set) -> () {
     return
 }
 
+#[inline]
 pub unsafe fn FD_ISSET(fd: c_int, set: *mut fd_set) -> bool {
     let fd = fd as usize;
     let size = mem::size_of_val(&(*set).fds_bits[0]) * 8;
     return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0
 }
 
+#[inline]
 pub unsafe fn FD_SET(fd: c_int, set: *mut fd_set) -> () {
     let fd = fd as usize;
     let size = mem::size_of_val(&(*set).fds_bits[0]) * 8;
@@ -1318,10 +1388,48 @@ pub unsafe fn FD_SET(fd: c_int, set: *mut fd_set) -> () {
     return
 }
 
+#[inline]
 pub unsafe fn FD_ZERO(set: *mut fd_set) -> () {
     for slot in (*set).fds_bits.iter_mut() {
         *slot = 0;
     }
 }
 
+#[inline]
+pub unsafe fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () {
+    for slot in cpuset.bits.iter_mut() {
+        *slot = 0;
+    }
+}
+
+#[inline]
+pub unsafe fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () {
+    let size_in_bits
+        = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc
+    let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits);
+    cpuset.bits[idx] |= 1 << offset;
+    ()
+}
+
+#[inline]
+pub unsafe fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () {
+    let size_in_bits
+        = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc
+    let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits);
+    cpuset.bits[idx] &= !(1 << offset);
+    ()
+}
+
+#[inline]
+pub unsafe fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool {
+    let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]);
+    let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits);
+    0 != (cpuset.bits[idx] & (1 << offset))
+}
+
+#[inline]
+pub unsafe fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool {
+    set1.bits == set2.bits
+}
+
 pub mod ocall;
diff --git a/sgx_libc/src/linux/x86_64/ocall.rs b/sgx_libc/src/linux/x86_64/ocall.rs
index 59363e2..29e3daa 100644
--- a/sgx_libc/src/linux/x86_64/ocall.rs
+++ b/sgx_libc/src/linux/x86_64/ocall.rs
@@ -15,7 +15,7 @@
 // specific language governing permissions and limitations
 // under the License..
 
-use sgx_types::{self, sgx_status_t};
+use sgx_types::*;
 use super::*;
 use alloc::slice;
 use alloc::vec::Vec;
@@ -23,250 +23,252 @@ use alloc::boxed::Box;
 use core::ptr;
 use core::mem;
 
+const MAX_OCALL_ALLOC_SIZE: size_t = 0x4000; //16K
 extern "C" {
     // memory
-    pub fn u_malloc_ocall(result: * mut * mut c_void, error: * mut c_int, size: size_t) -> sgx_status_t;
-    pub fn u_free_ocall(p: * mut c_void) -> sgx_status_t;
-    pub fn u_mmap_ocall(result: * mut * mut c_void,
-                        error: * mut c_int,
-                        start: * mut c_void,
+    pub fn u_malloc_ocall(result: *mut *mut c_void, error: *mut c_int, size: size_t) -> sgx_status_t;
+    pub fn u_free_ocall(p: *mut c_void) -> sgx_status_t;
+    pub fn u_mmap_ocall(result: *mut *mut c_void,
+                        error: *mut c_int,
+                        start: *mut c_void,
                         length: size_t,
                         prot: c_int,
                         flags: c_int,
                         fd: c_int,
                         offset: off_t) -> sgx_status_t;
-    pub fn u_munmap_ocall(result: * mut c_int,
-                          error: * mut c_int,
-                          start: * mut c_void,
+    pub fn u_munmap_ocall(result: *mut c_int,
+                          error: *mut c_int,
+                          start: *mut c_void,
                           length: size_t) -> sgx_status_t;
-
-    pub fn u_msync_ocall(result: * mut c_int,
-                         error: * mut c_int,
-                         addr: * mut c_void,
+    pub fn u_msync_ocall(result: *mut c_int,
+                         error: *mut c_int,
+                         addr: *mut c_void,
                          length: size_t,
                          flags: c_int) -> sgx_status_t;
 
-    pub fn u_mprotect_ocall(result: * mut c_int,
-                            error: * mut c_int,
-                            addr: * mut c_void,
+    pub fn u_mprotect_ocall(result: *mut c_int,
+                            error: *mut c_int,
+                            addr: *mut c_void,
                             length: size_t,
                             prot: c_int) -> sgx_status_t;
     // env
-    pub fn u_getuid_ocall(result: * mut uid_t) -> sgx_status_t;
-    pub fn u_environ_ocall(result: * mut * const * const c_char) -> sgx_status_t;
-    pub fn u_getenv_ocall(result: * mut * const c_char,
-                          name: * const c_char) -> sgx_status_t;
-    pub fn u_setenv_ocall(result: * mut c_int,
-                          error: * mut c_int,
-                          name: * const c_char,
-                          value: * const c_char,
+    pub fn u_getuid_ocall(result: *mut uid_t) -> sgx_status_t;
+    pub fn u_environ_ocall(result: *mut *const *const c_char) -> sgx_status_t;
+    pub fn u_getenv_ocall(result: *mut *const c_char,
+                          name: *const c_char) -> sgx_status_t;
+    pub fn u_setenv_ocall(result: *mut c_int,
+                          error: *mut c_int,
+                          name: *const c_char,
+                          value: *const c_char,
                           overwrite: c_int) -> sgx_status_t;
-    pub fn u_unsetenv_ocall(result: * mut c_int,
-                            error: * mut c_int,
-                            name: * const c_char) -> sgx_status_t;
-    pub fn u_getcwd_ocall(result: *mut *mut c_char,  error: * mut c_int, buf: *mut c_char, size: size_t) -> sgx_status_t;
-    pub fn u_chdir_ocall(result: * mut c_int,  error: * mut c_int, dir: *const c_char) -> sgx_status_t;
-    pub fn u_getpwuid_r_ocall(result: * mut c_int,
+    pub fn u_unsetenv_ocall(result: *mut c_int,
+                            error: *mut c_int,
+                            name: *const c_char) -> sgx_status_t;
+    pub fn u_getcwd_ocall(result: *mut *mut c_char,
+                          error: *mut c_int,
+                          buf: *mut c_char,
+                          size: size_t) -> sgx_status_t;
+    pub fn u_chdir_ocall(result: *mut c_int,  error: *mut c_int, dir: *const c_char) -> sgx_status_t;
+    pub fn u_getpwuid_r_ocall(result: *mut c_int,
                               uid: uid_t,
                               pwd: *mut passwd,
                               buf: *mut c_char,
                               buflen: size_t,
                               passwd_result: *mut *mut passwd) -> sgx_status_t;
     // file
-    pub fn u_open_ocall(result: * mut c_int,
-                        error: * mut c_int,
-                        path: * const c_char,
+    pub fn u_open_ocall(result: *mut c_int,
+                        error: *mut c_int,
+                        path: *const c_char,
                         flags: c_int) -> sgx_status_t;
-    pub fn u_open64_ocall(result: * mut c_int,
-                          error: * mut c_int,
-                          path: * const c_char,
+    pub fn u_open64_ocall(result: *mut c_int,
+                          error: *mut c_int,
+                          path: *const c_char,
                           oflag: c_int,
                           mode: c_int) -> sgx_status_t;
-    pub fn u_fstat_ocall(result: * mut c_int,
-                         error: * mut c_int,
+    pub fn u_fstat_ocall(result: *mut c_int,
+                         error: *mut c_int,
                          fd: c_int,
-                         buf: * mut stat) -> sgx_status_t;
-    pub fn u_fstat64_ocall(result: * mut c_int,
-                           error: * mut c_int,
+                         buf: *mut stat) -> sgx_status_t;
+    pub fn u_fstat64_ocall(result: *mut c_int,
+                           error: *mut c_int,
                            fd: c_int,
-                           buf: * mut stat64) -> sgx_status_t;
-    pub fn u_stat_ocall(result: * mut c_int,
-                        error: * mut c_int,
-                        path: * const c_char,
-                        buf: * mut stat) -> sgx_status_t;
-    pub fn u_stat64_ocall(result: * mut c_int,
-                          error: * mut c_int,
-                          path: * const c_char,
-                          buf: * mut stat64) -> sgx_status_t;
-    pub fn u_lstat_ocall(result: * mut c_int,
-                         error: * mut c_int,
-                         path: * const c_char,
-                         buf: * mut stat) -> sgx_status_t;
-    pub fn u_lstat64_ocall(result: * mut c_int,
-                           error: * mut c_int,
-                           path: * const c_char,
-                           buf: * mut stat64) -> sgx_status_t;
-    pub fn u_lseek_ocall(result: * mut off_t,
-                         error: * mut c_int,
+                           buf: *mut stat64) -> sgx_status_t;
+    pub fn u_stat_ocall(result: *mut c_int,
+                        error: *mut c_int,
+                        path: *const c_char,
+                        buf: *mut stat) -> sgx_status_t;
+    pub fn u_stat64_ocall(result: *mut c_int,
+                          error: *mut c_int,
+                          path: *const c_char,
+                          buf: *mut stat64) -> sgx_status_t;
+    pub fn u_lstat_ocall(result: *mut c_int,
+                         error: *mut c_int,
+                         path: *const c_char,
+                         buf: *mut stat) -> sgx_status_t;
+    pub fn u_lstat64_ocall(result: *mut c_int,
+                           error: *mut c_int,
+                           path: *const c_char,
+                           buf: *mut stat64) -> sgx_status_t;
+    pub fn u_lseek_ocall(result: *mut off_t,
+                         error: *mut c_int,
                          fd: c_int,
                          offset: off_t,
                          whence: c_int) -> sgx_status_t;
-    pub fn u_lseek64_ocall(result: * mut off64_t,
-                           error: * mut c_int,
+    pub fn u_lseek64_ocall(result: *mut off64_t,
+                           error: *mut c_int,
                            fd: c_int,
                            offset: off64_t,
                            whence: c_int) -> sgx_status_t;
-    pub fn u_ftruncate_ocall(result: * mut c_int,
-                             error: * mut c_int,
+    pub fn u_ftruncate_ocall(result: *mut c_int,
+                             error: *mut c_int,
                              fd: c_int,
                              length: off_t) -> sgx_status_t;
-    pub fn u_ftruncate64_ocall(result: * mut c_int,
-                               error: * mut c_int,
+    pub fn u_ftruncate64_ocall(result: *mut c_int,
+                               error: *mut c_int,
                                fd: c_int,
                                length: off64_t) -> sgx_status_t;
-    pub fn u_truncate_ocall(result: * mut c_int,
-                            error: * mut c_int,
-                            path: * const c_char,
+    pub fn u_truncate_ocall(result: *mut c_int,
+                            error: *mut c_int,
+                            path: *const c_char,
                             length: off_t) -> sgx_status_t;
-    pub fn u_truncate64_ocall(result: * mut c_int,
-                              error: * mut c_int,
-                              path: * const c_char,
+    pub fn u_truncate64_ocall(result: *mut c_int,
+                              error: *mut c_int,
+                              path: *const c_char,
                               length: off64_t) -> sgx_status_t;
-    pub fn u_fsync_ocall(result: * mut c_int,
-                         error: * mut c_int,
+    pub fn u_fsync_ocall(result: *mut c_int,
+                         error: *mut c_int,
                          fd: c_int) -> sgx_status_t;
-    pub fn u_fdatasync_ocall(result: * mut c_int,
-                             error: * mut c_int,
+    pub fn u_fdatasync_ocall(result: *mut c_int,
+                             error: *mut c_int,
                              fd: c_int) -> sgx_status_t;
-    pub fn u_fchmod_ocall(result: * mut c_int,
-                          error: * mut c_int,
+    pub fn u_fchmod_ocall(result: *mut c_int,
+                          error: *mut c_int,
                           fd: c_int,
                           mode: mode_t) -> sgx_status_t;
-    pub fn u_unlink_ocall(result: * mut c_int,
-                          error: * mut c_int,
-                          pathname: * const c_char) -> sgx_status_t;
-    pub fn u_link_ocall(result: * mut c_int,
-                        error: * mut c_int,
-                        oldpath: * const c_char,
-                        newpath: * const c_char) -> sgx_status_t;
-    pub fn u_rename_ocall(result: * mut c_int,
-                          error: * mut c_int,
-                          oldpath: * const c_char,
-                          newpath: * const c_char) -> sgx_status_t;
-    pub fn u_chmod_ocall(result: * mut c_int,
-                         error: * mut c_int,
-                         path: * const c_char,
+    pub fn u_unlink_ocall(result: *mut c_int,
+                          error: *mut c_int,
+                          pathname: *const c_char) -> sgx_status_t;
+    pub fn u_link_ocall(result: *mut c_int,
+                        error: *mut c_int,
+                        oldpath: *const c_char,
+                        newpath: *const c_char) -> sgx_status_t;
+    pub fn u_rename_ocall(result: *mut c_int,
+                          error: *mut c_int,
+                          oldpath: *const c_char,
+                          newpath: *const c_char) -> sgx_status_t;
+    pub fn u_chmod_ocall(result: *mut c_int,
+                         error: *mut c_int,
+                         path: *const c_char,
                          mode: mode_t) -> sgx_status_t;
-    pub fn u_readlink_ocall(result: * mut ssize_t,
-                            error: * mut c_int,
-                            path: * const c_char,
-                            buf: * mut c_char,
+    pub fn u_readlink_ocall(result: *mut ssize_t,
+                            error: *mut c_int,
+                            path: *const c_char,
+                            buf: *mut c_char,
                             bufsz: size_t) -> sgx_status_t;
-    pub fn u_symlink_ocall(result: * mut c_int,
-                           error: * mut c_int,
-                           path1: * const c_char,
-                           path2: * const c_char) -> sgx_status_t;
-    pub fn u_realpath_ocall(result: * mut * mut c_char,
-                            error: * mut c_int,
-                            pathname: * const c_char) -> sgx_status_t;
-    pub fn u_mkdir_ocall(result: * mut c_int,
-                         error: * mut c_int,
-                         pathname: * const c_char,
+    pub fn u_symlink_ocall(result: *mut c_int,
+                           error: *mut c_int,
+                           path1: *const c_char,
+                           path2: *const c_char) -> sgx_status_t;
+    pub fn u_realpath_ocall(result: *mut *mut c_char,
+                            error: *mut c_int,
+                            pathname: *const c_char) -> sgx_status_t;
+    pub fn u_mkdir_ocall(result: *mut c_int,
+                         error: *mut c_int,
+                         pathname: *const c_char,
                          mode: mode_t) -> sgx_status_t;
-    pub fn u_rmdir_ocall(result: * mut c_int,
-                         error: * mut c_int,
-                         pathname: * const c_char) -> sgx_status_t;
-    pub fn u_opendir_ocall(result: * mut * mut DIR,
-                           error: * mut c_int,
-                           pathname: * const c_char) -> sgx_status_t;
-    pub fn u_readdir64_r_ocall(result: * mut c_int,
-                               dirp: * mut DIR,
-                               entry: * mut dirent64,
-                               dirresult: * mut * mut  dirent64) -> sgx_status_t;
-    pub fn u_closedir_ocall(result: * mut c_int,
-                            error: * mut c_int,
-                            dirp: * mut DIR) -> sgx_status_t;
-    pub fn u_dirfd_ocall(result: * mut c_int,
-                         error: * mut c_int,
-                         dirp: * mut DIR) -> sgx_status_t;
-    pub fn u_fstatat64_ocall(result: * mut c_int,
-                             error: * mut c_int,
+    pub fn u_rmdir_ocall(result: *mut c_int,
+                         error: *mut c_int,
+                         pathname: *const c_char) -> sgx_status_t;
+    pub fn u_opendir_ocall(result: *mut *mut DIR,
+                           error: *mut c_int,
+                           pathname: *const c_char) -> sgx_status_t;
+    pub fn u_readdir64_r_ocall(result: *mut c_int,
+                               dirp: *mut DIR,
+                               entry: *mut dirent64,
+                               dirresult: *mut *mut  dirent64) -> sgx_status_t;
+    pub fn u_closedir_ocall(result: *mut c_int,
+                            error: *mut c_int,
+                            dirp: *mut DIR) -> sgx_status_t;
+    pub fn u_dirfd_ocall(result: *mut c_int,
+                         error: *mut c_int,
+                         dirp: *mut DIR) -> sgx_status_t;
+    pub fn u_fstatat64_ocall(result: *mut c_int,
+                             error: *mut c_int,
                              dirfd: c_int,
-                             pathname: * const c_char,
-                             buf: * mut stat64,
+                             pathname: *const c_char,
+                             buf: *mut stat64,
                              flags: c_int) -> sgx_status_t;
     // fd
-    pub fn u_read_ocall(result: * mut ssize_t,
-                        errno: * mut c_int,
+    pub fn u_read_ocall(result: *mut ssize_t,
+                        errno: *mut c_int,
                         fd: c_int,
-                        buf: * mut c_void,
+                        buf: *mut c_void,
                         count: size_t) -> sgx_status_t;
-    pub fn u_pread64_ocall(result: * mut ssize_t,
-                           errno: * mut c_int,
+    pub fn u_pread64_ocall(result: *mut ssize_t,
+                           errno: *mut c_int,
                            fd: c_int,
-                           buf: * mut c_void,
+                           buf: *mut c_void,
                            count: size_t,
                            offset: off64_t) -> sgx_status_t;
-    pub fn u_readv_ocall(result: * mut ssize_t,
-                         errno: * mut c_int,
+    pub fn u_readv_ocall(result: *mut ssize_t,
+                         errno: *mut c_int,
                          fd: c_int,
-                         iov: * const iovec,
+                         iov: *const iovec,
                          iovcnt: c_int) -> sgx_status_t;
-    pub fn u_preadv64_ocall(result: * mut ssize_t,
-                            errno: * mut c_int,
+    pub fn u_preadv64_ocall(result: *mut ssize_t,
+                            errno: *mut c_int,
                             fd: c_int,
-                            iov: * const iovec,
+                            iov: *const iovec,
                             iovcnt: c_int,
                             offset: off64_t) -> sgx_status_t;
-    pub fn u_write_ocall(result: * mut ssize_t,
-                         errno: * mut c_int,
+    pub fn u_write_ocall(result: *mut ssize_t,
+                         errno: *mut c_int,
                          fd: c_int,
-                         buf: * const c_void,
+                         buf: *const c_void,
                          count: size_t) -> sgx_status_t;
-    pub fn u_pwrite64_ocall(result: * mut ssize_t,
-                            errno: * mut c_int,
+    pub fn u_pwrite64_ocall(result: *mut ssize_t,
+                            errno: *mut c_int,
                             fd: c_int,
-                            buf: * const c_void,
+                            buf: *const c_void,
                             count: size_t,
                             offset: off64_t) -> sgx_status_t;
-    pub fn u_writev_ocall(result: * mut ssize_t,
-                          errno: * mut c_int,
+    pub fn u_writev_ocall(result: *mut ssize_t,
+                          errno: *mut c_int,
                           fd: c_int,
-                          iov: * const iovec,
+                          iov: *const iovec,
                           iovcnt: c_int) -> sgx_status_t;
-    pub fn u_pwritev64_ocall(result: * mut ssize_t,
-                             errno: * mut c_int,
+    pub fn u_pwritev64_ocall(result: *mut ssize_t,
+                             errno: *mut c_int,
                              fd: c_int,
-                             iov: * const iovec,
+                             iov: *const iovec,
                              iovcnt: c_int,
                              offset: off64_t) -> sgx_status_t;
-    pub fn u_fcntl_arg0_ocall(result: * mut c_int,
-                              errno: * mut c_int,
+    pub fn u_fcntl_arg0_ocall(result: *mut c_int,
+                              errno: *mut c_int,
                               fd: c_int,
                               cmd: c_int) -> sgx_status_t;
-
-    pub fn u_fcntl_arg1_ocall(result: * mut c_int,
-                              errno: * mut c_int,
+    pub fn u_fcntl_arg1_ocall(result: *mut c_int,
+                              errno: *mut c_int,
                               fd: c_int,
                               cmd: c_int,
                               arg: c_int) -> sgx_status_t;
-    pub fn u_ioctl_arg0_ocall(result: * mut c_int,
-                              errno: * mut c_int,
+    pub fn u_ioctl_arg0_ocall(result: *mut c_int,
+                              errno: *mut c_int,
                               fd: c_int,
                               request: c_int) -> sgx_status_t;
-    pub fn u_ioctl_arg1_ocall(result: * mut c_int,
-                              errno: * mut c_int,
+    pub fn u_ioctl_arg1_ocall(result: *mut c_int,
+                              errno: *mut c_int,
                               fd: c_int,
                               request: c_int,
-                              arg: * const c_int) -> sgx_status_t;
-    pub fn u_close_ocall(result: * mut c_int,
-                         errno: * mut c_int,
+                              arg: *mut c_int) -> sgx_status_t;
+    pub fn u_close_ocall(result: *mut c_int,
+                         errno: *mut c_int,
                          fd: c_int) -> sgx_status_t;
     // time
-    pub fn u_clock_gettime_ocall(result: * mut c_int,
-                                 errno: * mut c_int,
+    pub fn u_clock_gettime_ocall(result: *mut c_int,
+                                 errno: *mut c_int,
                                  clk_id: clockid_t,
-                                 tp: * mut timespec) -> sgx_status_t;
+                                 tp: *mut timespec) -> sgx_status_t;
     // socket
     pub fn u_socket_ocall(result: *mut c_int,
                           errno: *mut c_int,
@@ -279,10 +281,10 @@ extern "C" {
                               ty: c_int,
                               protocol: c_int,
                               sv: *mut c_int) -> sgx_status_t;
-    pub fn u_bind_ocall(result: * mut c_int,
-                        errno: * mut c_int,
+    pub fn u_bind_ocall(result: *mut c_int,
+                        errno: *mut c_int,
                         sockfd: c_int,
-                        address: * const sockaddr,
+                        address: *const sockaddr,
                         addrlen: socklen_t) -> sgx_status_t;
     pub fn u_listen_ocall(result: *mut c_int,
                           error: *mut c_int,
@@ -301,155 +303,154 @@ extern "C" {
                            addrlen_in: socklen_t,
                            addrlen_out: *mut socklen_t,
                            flags: c_int) -> sgx_status_t;
-    pub fn u_connect_ocall(result: * mut c_int,
-                           errno: * mut c_int,
+    pub fn u_connect_ocall(result: *mut c_int,
+                           errno: *mut c_int,
                            sockfd: c_int,
-                           address: * const sockaddr,
+                           address: *const sockaddr,
                            addrlen: socklen_t) -> sgx_status_t;
-    pub fn u_send_ocall(result: * mut ssize_t,
-                        errno: * mut c_int,
+    pub fn u_send_ocall(result: *mut ssize_t,
+                        errno: *mut c_int,
                         sockfd: c_int,
-                        buf: * const c_void,
+                        buf: *const c_void,
                         len: size_t,
                         flags: c_int) -> sgx_status_t;
-    pub fn u_sendto_ocall(result: * mut ssize_t,
-                          errno: * mut c_int,
+    pub fn u_sendto_ocall(result: *mut ssize_t,
+                          errno: *mut c_int,
                           sockfd: c_int,
-                          buf: * const c_void,
+                          buf: *const c_void,
                           len: size_t,
                           flags: c_int,
-                          addr: * const sockaddr,
+                          addr: *const sockaddr,
                           addrlen: socklen_t) -> sgx_status_t;
-    pub fn u_sendmsg_ocall(result: * mut ssize_t,
-                           error: * mut c_int,
+    pub fn u_sendmsg_ocall(result: *mut ssize_t,
+                           error: *mut c_int,
                            sockfd: c_int,
-                           msg: * const msghdr,
+                           msg: *const msghdr,
                            flags: c_int) -> sgx_status_t;
-    pub fn u_recv_ocall(result: * mut ssize_t,
-                        errno: * mut c_int,
+    pub fn u_recv_ocall(result: *mut ssize_t,
+                        errno: *mut c_int,
                         sockfd: c_int,
-                        buf: * mut c_void,
+                        buf: *mut c_void,
                         len: size_t,
                         flags: c_int) -> sgx_status_t;
-    pub fn u_recvfrom_ocall(result: * mut ssize_t,
-                            errno: * mut c_int,
+    pub fn u_recvfrom_ocall(result: *mut ssize_t,
+                            errno: *mut c_int,
                             sockfd: c_int,
-                            buf: * mut c_void,
+                            buf: *mut c_void,
                             len: size_t,
                             flags: c_int,
-                            addr: * mut sockaddr,
+                            addr: *mut sockaddr,
                             addrlen_in: socklen_t,
-                            addrlen_out: * mut socklen_t) -> sgx_status_t;
-    pub fn u_recvmsg_ocall(result: * mut ssize_t,
-                           error: * mut c_int,
+                            addrlen_out: *mut socklen_t) -> sgx_status_t;
+    pub fn u_recvmsg_ocall(result: *mut ssize_t,
+                           error: *mut c_int,
                            sockfd: c_int,
-                           msg: * mut msghdr,
+                           msg: *mut msghdr,
                            flags: c_int) -> sgx_status_t;
-    pub fn u_setsockopt_ocall(result: * mut c_int,
-                              errno: * mut c_int,
+    pub fn u_setsockopt_ocall(result: *mut c_int,
+                              errno: *mut c_int,
                               sockfd: c_int,
                               level: c_int,
                               optname: c_int,
-                              optval: * const c_void,
+                              optval: *const c_void,
                               optlen: socklen_t) -> sgx_status_t;
-    pub fn u_getsockopt_ocall(result: * mut c_int,
-                              errno: * mut c_int,
+    pub fn u_getsockopt_ocall(result: *mut c_int,
+                              errno: *mut c_int,
                               sockfd: c_int,
                               level: c_int,
                               optname: c_int,
-                              optval: * mut c_void,
+                              optval: *mut c_void,
                               optlen_in: socklen_t,
-                              optlen_out: * mut socklen_t) -> sgx_status_t;
-    pub fn u_getpeername_ocall(result: * mut c_int,
-                               errno: * mut c_int,
+                              optlen_out: *mut socklen_t) -> sgx_status_t;
+    pub fn u_getpeername_ocall(result: *mut c_int,
+                               errno: *mut c_int,
                                sockfd: c_int,
-                               address: * mut sockaddr,
+                               address: *mut sockaddr,
                                addrlen_in: socklen_t,
-                               addrlen_out: * mut socklen_t) -> sgx_status_t;
-    pub fn u_getsockname_ocall(result: * mut c_int,
-                               errno: * mut c_int,
+                               addrlen_out: *mut socklen_t) -> sgx_status_t;
+    pub fn u_getsockname_ocall(result: *mut c_int,
+                               errno: *mut c_int,
                                sockfd: c_int,
-                               address: * mut sockaddr,
+                               address: *mut sockaddr,
                                addrlen_in: socklen_t,
-                               addrlen_out: * mut socklen_t) -> sgx_status_t;
-    pub fn u_shutdown_ocall(result: * mut c_int,
-                            errno: * mut c_int,
+                               addrlen_out: *mut socklen_t) -> sgx_status_t;
+    pub fn u_shutdown_ocall(result: *mut c_int,
+                            errno: *mut c_int,
                             sockfd: c_int,
                             how: c_int) -> sgx_status_t;
     // net
-    pub fn u_getaddrinfo_ocall(result: * mut c_int,
-                               errno: * mut c_int,
-                               node: * const c_char,
-                               service: * const c_char,
-                               hints: * const addrinfo,
-                               res: * mut * mut addrinfo) -> sgx_status_t;
-    pub fn u_freeaddrinfo_ocall(res: * mut addrinfo) -> sgx_status_t;
-    pub fn u_gai_strerror_ocall(result: * mut * const c_char, errcode: c_int) -> sgx_status_t;
+    pub fn u_getaddrinfo_ocall(result: *mut c_int,
+                               errno: *mut c_int,
+                               node: *const c_char,
+                               service: *const c_char,
+                               hints: *const addrinfo,
+                               res: *mut *mut addrinfo) -> sgx_status_t;
+    pub fn u_freeaddrinfo_ocall(res: *mut addrinfo) -> sgx_status_t;
+    pub fn u_gai_strerror_ocall(result: *mut *const c_char, errcode: c_int) -> sgx_status_t;
     // async io
-    pub fn u_poll_ocall(result: * mut c_int,
-                        errno: * mut c_int,
-                        fds: * mut pollfd,
+    pub fn u_poll_ocall(result: *mut c_int,
+                        errno: *mut c_int,
+                        fds: *mut pollfd,
                         nfds: nfds_t,
                         timeout: c_int) -> sgx_status_t;
-    pub fn u_epoll_create1_ocall(result: * mut c_int,
-                                 error: * mut c_int,
+    pub fn u_epoll_create1_ocall(result: *mut c_int,
+                                 error: *mut c_int,
                                  flags: c_int) -> sgx_status_t;
-    pub fn u_epoll_ctl_ocall(result: * mut c_int,
-                             error: * mut c_int,
+    pub fn u_epoll_ctl_ocall(result: *mut c_int,
+                             error: *mut c_int,
                              epfd: c_int,
                              op: c_int,
                              fd: c_int,
-                             event: * mut epoll_event) -> sgx_status_t;
-    pub fn u_epoll_wait_ocall(result: * mut c_int,
-                              error: * mut c_int,
+                             event: *mut epoll_event) -> sgx_status_t;
+    pub fn u_epoll_wait_ocall(result: *mut c_int,
+                              error: *mut c_int,
                               epfd: c_int,
-                              events: * mut epoll_event,
+                              events: *mut epoll_event,
                               maxevents: c_int,
                               timeout: c_int) -> sgx_status_t;
     // sys
-    pub fn u_sysconf_ocall(result: * mut c_long,
-                           error: * mut c_int,
+    pub fn u_sysconf_ocall(result: *mut c_long,
+                           error: *mut c_int,
                            name: c_int) -> sgx_status_t;
-    pub fn u_prctl_ocall(result: * mut c_int,
-                         error: * mut c_int,
+    pub fn u_prctl_ocall(result: *mut c_int,
+                         error: *mut c_int,
                          option: c_int,
                          arg2: c_ulong,
                          arg3: c_ulong,
                          arg4: c_ulong,
                          arg5: c_ulong) -> sgx_status_t;
+    pub fn u_sched_setaffinity_ocall(result: *mut c_int,
+                                     error: *mut c_int,
+                                     pid: pid_t,
+                                     cpusetsize: size_t,
+                                     mask: *const cpu_set_t) -> sgx_status_t;
+    pub fn u_sched_getaffinity_ocall(result: *mut c_int,
+                                     error: *mut c_int,
+                                     pid: pid_t,
+                                     cpusetsize: size_t,
+                                     mask: *mut cpu_set_t) -> sgx_status_t;
     // pipe
-    pub fn u_pipe_ocall(result: * mut c_int,
-                        error: * mut c_int,
-                        fds: * mut c_int) -> sgx_status_t;
-    pub fn u_pipe2_ocall(result: * mut c_int,
-                         error: * mut c_int,
-                         fds: * mut c_int,
+    pub fn u_pipe_ocall(result: *mut c_int,
+                        error: *mut c_int,
+                        fds: *mut c_int) -> sgx_status_t;
+    pub fn u_pipe2_ocall(result: *mut c_int,
+                         error: *mut c_int,
+                         fds: *mut c_int,
                          flags: c_int) -> sgx_status_t;
     //thread
-    pub  fn u_pthread_create_ocall(result: * mut c_int,
-                                   native: * mut pthread_t,
-                                   attr: * const pthread_attr_t,
-                                   f: * mut c_void,
-                                   value: * mut c_void,
-                                   len: c_int) -> sgx_status_t;
-    pub  fn u_pthread_join_ocall(result: * mut c_int,
-                                 native: pthread_t,
-                                 value: *mut *mut c_void) -> sgx_status_t;
-    pub  fn u_pthread_detach_ocall(result: * mut c_int,
-                                   native: pthread_t) -> sgx_status_t;
-    pub  fn u_sched_yield_ocall(result: * mut c_int,
-                                error: * mut c_int) -> sgx_status_t;
-    pub  fn u_nanosleep_ocall(result: * mut c_int,
-                              error: * mut c_int,
+    pub  fn u_sched_yield_ocall(result: *mut c_int,
+                                error: *mut c_int) -> sgx_status_t;
+    pub  fn u_nanosleep_ocall(result: *mut c_int,
+                              error: *mut c_int,
                               rqtp: *const timespec,
                               rmtp: *mut timespec) -> sgx_status_t;
 }
 
-pub unsafe fn malloc(size: size_t) -> * mut c_void {
-    let mut result: * mut c_void = ptr::null_mut();
+pub unsafe fn malloc(size: size_t) -> *mut c_void {
+    let mut result: *mut c_void = ptr::null_mut();
     let mut error: c_int = 0;
-    let status = u_malloc_ocall(&mut result as * mut * mut c_void,
-                                &mut error as * mut c_int,
+    let status = u_malloc_ocall(&mut result as *mut *mut c_void,
+                                &mut error as *mut c_int,
                                 size);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -463,15 +464,20 @@ pub unsafe fn malloc(size: size_t) -> * mut c_void {
     result
 }
 
-pub unsafe fn free(p: * mut c_void) {
+pub unsafe fn free(p: *mut c_void) {
     let _ = u_free_ocall(p);
 }
 
-pub unsafe fn mmap(start: * mut c_void, length: size_t, prot: c_int, flags: c_int, fd: c_int, offset: off_t) -> * mut c_void {
-    let mut result: * mut c_void = ptr::null_mut();
+pub unsafe fn mmap(start: *mut c_void,
+                   length: size_t,
+                   prot: c_int,
+                   flags: c_int,
+                   fd: c_int,
+                   offset: off_t) -> *mut c_void {
+    let mut result: *mut c_void = ptr::null_mut();
     let mut error: c_int = 0;
-    let status = u_mmap_ocall(&mut result as * mut * mut c_void,
-                              &mut error as * mut c_int,
+    let status = u_mmap_ocall(&mut result as *mut *mut c_void,
+                              &mut error as *mut c_int,
                               start,
                               length,
                               prot,
@@ -485,16 +491,16 @@ pub unsafe fn mmap(start: * mut c_void, length: size_t, prot: c_int, flags: c_in
         }
     } else {
         set_errno(ESGX);
-        result = -1 as isize as * mut c_void;
+        result = -1 as isize as *mut c_void;
     }
     result
 }
 
-pub unsafe fn munmap(start: * mut c_void, length: size_t) -> c_int {
+pub unsafe fn munmap(start: *mut c_void, length: size_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_munmap_ocall(&mut result as * mut c_int,
-                                &mut error as * mut c_int,
+    let status = u_munmap_ocall(&mut result as *mut c_int,
+                                &mut error as *mut c_int,
                                 start,
                                 length);
 
@@ -509,11 +515,11 @@ pub unsafe fn munmap(start: * mut c_void, length: size_t) -> c_int {
     result
 }
 
-pub unsafe fn msync(addr: * mut c_void, length: size_t, flags: c_int) -> c_int {
+pub unsafe fn msync(addr: *mut c_void, length: size_t, flags: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_msync_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_msync_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                addr,
                                length,
                                flags);
@@ -529,11 +535,11 @@ pub unsafe fn msync(addr: * mut c_void, length: size_t, flags: c_int) -> c_int {
     result
 }
 
-pub unsafe fn mprotect(addr: * mut c_void, length: size_t, prot: c_int) -> c_int {
+pub unsafe fn mprotect(addr: *mut c_void, length: size_t, prot: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_mprotect_ocall(&mut result as * mut c_int,
-                                  &mut error as * mut c_int,
+    let status = u_mprotect_ocall(&mut result as *mut c_int,
+                                  &mut error as *mut c_int,
                                   addr,
                                   length,
                                   prot);
@@ -551,16 +557,17 @@ pub unsafe fn mprotect(addr: * mut c_void, length: size_t, prot: c_int) -> c_int
 
 pub unsafe fn getuid() -> uid_t {
     let mut result: uid_t = 0;
-    let status = u_getuid_ocall(&mut result as * mut uid_t);
+    let status = u_getuid_ocall(&mut result as *mut uid_t);
     if status != sgx_status_t::SGX_SUCCESS {
          set_errno(ESGX);
          result = 0;
     }
     result
 }
-pub unsafe fn environ() -> * const * const c_char {
-    let mut result: * const * const c_char = ptr::null();
-    let status = u_environ_ocall(&mut result as * mut * const * const c_char);
+
+pub unsafe fn environ() -> *const *const c_char {
+    let mut result: *const *const c_char = ptr::null();
+    let status = u_environ_ocall(&mut result as *mut *const *const c_char);
 
     if status != sgx_status_t::SGX_SUCCESS {
         result = ptr::null();
@@ -568,9 +575,9 @@ pub unsafe fn environ() -> * const * const c_char {
     result
 }
 
-pub unsafe fn getenv(name: * const c_char) -> * const c_char {
-    let mut result: * const c_char = ptr::null();
-    let status = u_getenv_ocall(&mut result as * mut * const c_char, name);
+pub unsafe fn getenv(name: *const c_char) -> *const c_char {
+    let mut result: *const c_char = ptr::null();
+    let status = u_getenv_ocall(&mut result as *mut *const c_char, name);
 
     if status != sgx_status_t::SGX_SUCCESS {
         result = ptr::null();
@@ -578,11 +585,11 @@ pub unsafe fn getenv(name: * const c_char) -> * const c_char {
     result
 }
 
-pub unsafe fn setenv(name: * const c_char, value: * const c_char, overwrite: c_int) -> c_int {
+pub unsafe fn setenv(name: *const c_char, value: *const c_char, overwrite: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_setenv_ocall(&mut result as * mut c_int,
-                                &mut error as * mut c_int,
+    let status = u_setenv_ocall(&mut result as *mut c_int,
+                                &mut error as *mut c_int,
                                 name,
                                 value,
                                 overwrite);
@@ -598,11 +605,11 @@ pub unsafe fn setenv(name: * const c_char, value: * const c_char, overwrite: c_i
     result
 }
 
-pub unsafe fn unsetenv(name: * const c_char) -> c_int {
+pub unsafe fn unsetenv(name: *const c_char) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_unsetenv_ocall(&mut result as * mut c_int,
-                                  &mut error as * mut c_int,
+    let status = u_unsetenv_ocall(&mut result as *mut c_int,
+                                  &mut error as *mut c_int,
                                   name);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -616,10 +623,10 @@ pub unsafe fn unsetenv(name: * const c_char) -> c_int {
     result
 }
 
-pub unsafe fn getcwd(buf: * mut c_char, size: size_t) -> * mut c_char {
-    let mut result: * mut c_char = ptr::null_mut();
+pub unsafe fn getcwd(buf: *mut c_char, size: size_t) -> *mut c_char {
+    let mut result: *mut c_char = ptr::null_mut();
     let mut error: c_int = 0;
-    let status = u_getcwd_ocall(&mut result as * mut * mut c_char, &mut error as * mut c_int, buf, size);
+    let status = u_getcwd_ocall(&mut result as *mut *mut c_char, &mut error as *mut c_int, buf, size);
     if status == sgx_status_t::SGX_SUCCESS {
         if result.is_null() {
             set_errno(error);
@@ -633,10 +640,10 @@ pub unsafe fn getcwd(buf: * mut c_char, size: size_t) -> * mut c_char {
     result
 }
 
-pub unsafe fn chdir(dir: * const c_char) -> c_int {
+pub unsafe fn chdir(dir: *const c_char) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_chdir_ocall(&mut result as * mut c_int, &mut error as * mut c_int, dir);
+    let status = u_chdir_ocall(&mut result as *mut c_int, &mut error as *mut c_int, dir);
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
             set_errno(error);
@@ -649,12 +656,12 @@ pub unsafe fn chdir(dir: * const c_char) -> c_int {
 }
 
 pub unsafe fn getpwuid_r(uid: uid_t,
-                         pwd: * mut passwd,
-                         buf: * mut c_char,
+                         pwd: *mut passwd,
+                         buf: *mut c_char,
                          buflen: size_t,
-                         passwd_result:  *mut * mut passwd) -> c_int {
+                         passwd_result:  *mut *mut passwd) -> c_int {
     let mut result: c_int = 0;
-    let status = u_getpwuid_r_ocall(&mut result as * mut c_int,
+    let status = u_getpwuid_r_ocall(&mut result as *mut c_int,
                                     uid,
                                     pwd,
                                     buf,
@@ -705,11 +712,11 @@ pub unsafe fn getpwuid_r(uid: uid_t,
     result
 }
 
-pub unsafe fn open(path: * const c_char, flags: c_int) -> c_int {
+pub unsafe fn open(path: *const c_char, flags: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_open_ocall(&mut result as * mut c_int,
-                              &mut error as * mut c_int,
+    let status = u_open_ocall(&mut result as *mut c_int,
+                              &mut error as *mut c_int,
                               path,
                               flags);
 
@@ -724,11 +731,11 @@ pub unsafe fn open(path: * const c_char, flags: c_int) -> c_int {
     result
 }
 
-pub unsafe fn open64(path: * const c_char, oflag: c_int, mode: c_int) -> c_int {
+pub unsafe fn open64(path: *const c_char, oflag: c_int, mode: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_open64_ocall(&mut result as * mut c_int,
-                                &mut error as * mut c_int,
+    let status = u_open64_ocall(&mut result as *mut c_int,
+                                &mut error as *mut c_int,
                                 path,
                                 oflag,
                                 mode);
@@ -744,11 +751,11 @@ pub unsafe fn open64(path: * const c_char, oflag: c_int, mode: c_int) -> c_int {
     result
 }
 
-pub unsafe fn fstat(fd: c_int, buf: * mut stat) -> c_int {
+pub unsafe fn fstat(fd: c_int, buf: *mut stat) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fstat_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_fstat_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                fd,
                                buf);
 
@@ -763,11 +770,11 @@ pub unsafe fn fstat(fd: c_int, buf: * mut stat) -> c_int {
     result
 }
 
-pub unsafe fn fstat64(fd: c_int, buf: * mut stat64) -> c_int {
+pub unsafe fn fstat64(fd: c_int, buf: *mut stat64) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fstat64_ocall(&mut result as * mut c_int,
-                                 &mut error as * mut c_int,
+    let status = u_fstat64_ocall(&mut result as *mut c_int,
+                                 &mut error as *mut c_int,
                                  fd,
                                  buf);
 
@@ -782,11 +789,11 @@ pub unsafe fn fstat64(fd: c_int, buf: * mut stat64) -> c_int {
     result
 }
 
-pub unsafe fn stat(path: * const c_char, buf: * mut stat) -> c_int {
+pub unsafe fn stat(path: *const c_char, buf: *mut stat) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_stat_ocall(&mut result as * mut c_int,
-                              &mut error as * mut c_int,
+    let status = u_stat_ocall(&mut result as *mut c_int,
+                              &mut error as *mut c_int,
                               path,
                               buf);
 
@@ -801,11 +808,11 @@ pub unsafe fn stat(path: * const c_char, buf: * mut stat) -> c_int {
     result
 }
 
-pub unsafe fn stat64(path: * const c_char, buf: * mut stat64) -> c_int {
+pub unsafe fn stat64(path: *const c_char, buf: *mut stat64) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_stat64_ocall(&mut result as * mut c_int,
-                                &mut error as * mut c_int,
+    let status = u_stat64_ocall(&mut result as *mut c_int,
+                                &mut error as *mut c_int,
                                 path,
                                 buf);
 
@@ -820,11 +827,11 @@ pub unsafe fn stat64(path: * const c_char, buf: * mut stat64) -> c_int {
     result
 }
 
-pub unsafe fn lstat(path: * const c_char, buf: * mut stat) -> c_int {
+pub unsafe fn lstat(path: *const c_char, buf: *mut stat) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_lstat_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_lstat_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                path,
                                buf);
 
@@ -839,11 +846,11 @@ pub unsafe fn lstat(path: * const c_char, buf: * mut stat) -> c_int {
     result
 }
 
-pub unsafe fn lstat64(path: * const c_char, buf: * mut stat64) -> c_int {
+pub unsafe fn lstat64(path: *const c_char, buf: *mut stat64) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_lstat64_ocall(&mut result as * mut c_int,
-                                 &mut error as * mut c_int,
+    let status = u_lstat64_ocall(&mut result as *mut c_int,
+                                 &mut error as *mut c_int,
                                  path,
                                  buf);
 
@@ -861,8 +868,8 @@ pub unsafe fn lstat64(path: * const c_char, buf: * mut stat64) -> c_int {
 pub unsafe fn lseek(fd: c_int, offset: off_t, whence: c_int) -> off_t {
     let mut result: off_t = 0;
     let mut error: c_int = 0;
-    let status = u_lseek_ocall(&mut result as * mut off_t,
-                               &mut error as * mut c_int,
+    let status = u_lseek_ocall(&mut result as *mut off_t,
+                               &mut error as *mut c_int,
                                fd,
                                offset,
                                whence);
@@ -881,8 +888,8 @@ pub unsafe fn lseek(fd: c_int, offset: off_t, whence: c_int) -> off_t {
 pub unsafe fn lseek64(fd: c_int, offset: off64_t, whence: c_int) -> off64_t {
     let mut result: off64_t = 0;
     let mut error: c_int = 0;
-    let status = u_lseek64_ocall(&mut result as * mut off64_t,
-                                 &mut error as * mut c_int,
+    let status = u_lseek64_ocall(&mut result as *mut off64_t,
+                                 &mut error as *mut c_int,
                                  fd,
                                  offset,
                                  whence);
@@ -901,8 +908,8 @@ pub unsafe fn lseek64(fd: c_int, offset: off64_t, whence: c_int) -> off64_t {
 pub unsafe fn ftruncate(fd: c_int, length: off_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_ftruncate_ocall(&mut result as * mut c_int,
-                                   &mut error as * mut c_int,
+    let status = u_ftruncate_ocall(&mut result as *mut c_int,
+                                   &mut error as *mut c_int,
                                    fd,
                                    length);
 
@@ -920,8 +927,8 @@ pub unsafe fn ftruncate(fd: c_int, length: off_t) -> c_int {
 pub unsafe fn ftruncate64(fd: c_int, length: off64_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_ftruncate64_ocall(&mut result as * mut c_int,
-                                     &mut error as * mut c_int,
+    let status = u_ftruncate64_ocall(&mut result as *mut c_int,
+                                     &mut error as *mut c_int,
                                      fd,
                                      length);
 
@@ -936,11 +943,11 @@ pub unsafe fn ftruncate64(fd: c_int, length: off64_t) -> c_int {
     result
 }
 
-pub unsafe fn truncate(path: * const c_char, length: off_t) -> c_int {
+pub unsafe fn truncate(path: *const c_char, length: off_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_truncate_ocall(&mut result as * mut c_int,
-                                  &mut error as * mut c_int,
+    let status = u_truncate_ocall(&mut result as *mut c_int,
+                                  &mut error as *mut c_int,
                                   path,
                                   length);
 
@@ -955,11 +962,11 @@ pub unsafe fn truncate(path: * const c_char, length: off_t) -> c_int {
     result
 }
 
-pub unsafe fn truncate64(path: * const c_char, length: off64_t) -> c_int {
+pub unsafe fn truncate64(path: *const c_char, length: off64_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_truncate64_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_truncate64_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     path,
                                     length);
 
@@ -977,8 +984,8 @@ pub unsafe fn truncate64(path: * const c_char, length: off64_t) -> c_int {
 pub unsafe fn fsync(fd: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fsync_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_fsync_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                fd);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -995,8 +1002,8 @@ pub unsafe fn fsync(fd: c_int) -> c_int {
 pub unsafe fn fdatasync(fd: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fdatasync_ocall(&mut result as * mut c_int,
-                                   &mut error as * mut c_int,
+    let status = u_fdatasync_ocall(&mut result as *mut c_int,
+                                   &mut error as *mut c_int,
                                    fd);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1013,8 +1020,8 @@ pub unsafe fn fdatasync(fd: c_int) -> c_int {
 pub unsafe fn fchmod(fd: c_int, mode: mode_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fchmod_ocall(&mut result as * mut c_int,
-                                &mut error as * mut c_int,
+    let status = u_fchmod_ocall(&mut result as *mut c_int,
+                                &mut error as *mut c_int,
                                 fd,
                                 mode);
 
@@ -1029,11 +1036,11 @@ pub unsafe fn fchmod(fd: c_int, mode: mode_t) -> c_int {
     result
 }
 
-pub unsafe fn unlink(pathname: * const c_char) -> c_int {
+pub unsafe fn unlink(pathname: *const c_char) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_unlink_ocall(&mut result as * mut c_int,
-                                &mut error as * mut c_int,
+    let status = u_unlink_ocall(&mut result as *mut c_int,
+                                &mut error as *mut c_int,
                                 pathname);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1047,11 +1054,11 @@ pub unsafe fn unlink(pathname: * const c_char) -> c_int {
     result
 }
 
-pub unsafe fn link(oldpath: * const c_char, newpath: * const c_char) -> c_int {
+pub unsafe fn link(oldpath: *const c_char, newpath: *const c_char) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_link_ocall(&mut result as * mut c_int,
-                              &mut error as * mut c_int,
+    let status = u_link_ocall(&mut result as *mut c_int,
+                              &mut error as *mut c_int,
                               oldpath,
                               newpath);
 
@@ -1066,11 +1073,11 @@ pub unsafe fn link(oldpath: * const c_char, newpath: * const c_char) -> c_int {
     result
 }
 
-pub unsafe fn rename(oldpath: * const c_char, newpath: * const c_char) -> c_int {
+pub unsafe fn rename(oldpath: *const c_char, newpath: *const c_char) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_rename_ocall(&mut result as * mut c_int,
-                                &mut error as * mut c_int,
+    let status = u_rename_ocall(&mut result as *mut c_int,
+                                &mut error as *mut c_int,
                                 oldpath,
                                 newpath);
 
@@ -1085,11 +1092,11 @@ pub unsafe fn rename(oldpath: * const c_char, newpath: * const c_char) -> c_int
     result
 }
 
-pub unsafe fn chmod(path: * const c_char, mode: mode_t) -> c_int {
+pub unsafe fn chmod(path: *const c_char, mode: mode_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_chmod_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_chmod_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                path,
                                mode);
 
@@ -1104,11 +1111,11 @@ pub unsafe fn chmod(path: * const c_char, mode: mode_t) -> c_int {
     result
 }
 
-pub unsafe fn readlink(path: * const c_char, buf: * mut c_char, bufsz: size_t) -> ssize_t {
+pub unsafe fn readlink(path: *const c_char, buf: *mut c_char, bufsz: size_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_readlink_ocall(&mut result as * mut ssize_t,
-                                  &mut error as * mut c_int,
+    let status = u_readlink_ocall(&mut result as *mut ssize_t,
+                                  &mut error as *mut c_int,
                                   path,
                                   buf,
                                   bufsz);
@@ -1124,11 +1131,11 @@ pub unsafe fn readlink(path: * const c_char, buf: * mut c_char, bufsz: size_t) -
     result
 }
 
-pub unsafe fn symlink(path1: * const c_char, path2: * const c_char) -> c_int {
+pub unsafe fn symlink(path1: *const c_char, path2: *const c_char) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_symlink_ocall(&mut result as * mut c_int,
-                                 &mut error as * mut c_int,
+    let status = u_symlink_ocall(&mut result as *mut c_int,
+                                 &mut error as *mut c_int,
                                  path1,
                                  path2);
 
@@ -1143,11 +1150,11 @@ pub unsafe fn symlink(path1: * const c_char, path2: * const c_char) -> c_int {
     result
 }
 
-pub unsafe fn realpath(pathname: * const c_char) -> * mut c_char {
-    let mut result: * mut c_char = ptr::null_mut();
+pub unsafe fn realpath(pathname: *const c_char) -> *mut c_char {
+    let mut result: *mut c_char = ptr::null_mut();
     let mut error: c_int = 0;
-    let status = u_realpath_ocall(&mut result as * mut * mut c_char,
-                                  &mut error as * mut c_int,
+    let status = u_realpath_ocall(&mut result as *mut *mut c_char,
+                                  &mut error as *mut c_int,
                                   pathname);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1161,11 +1168,11 @@ pub unsafe fn realpath(pathname: * const c_char) -> * mut c_char {
     result
 }
 
-pub unsafe fn mkdir(pathname: * const c_char, mode: mode_t) -> c_int {
+pub unsafe fn mkdir(pathname: *const c_char, mode: mode_t) -> c_int {
     let mut error: c_int = 0;
     let mut result: c_int = 0;
-    let status = u_mkdir_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_mkdir_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                pathname,
                                mode);
 
@@ -1180,11 +1187,11 @@ pub unsafe fn mkdir(pathname: * const c_char, mode: mode_t) -> c_int {
     result
 }
 
-pub unsafe fn rmdir(pathname: * const c_char) -> c_int {
+pub unsafe fn rmdir(pathname: *const c_char) -> c_int {
     let mut error: c_int = 0;
     let mut result: c_int = 0;
-    let status = u_rmdir_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_rmdir_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                pathname);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1198,11 +1205,11 @@ pub unsafe fn rmdir(pathname: * const c_char) -> c_int {
     result
 }
 
-pub unsafe fn opendir(pathname: * const c_char) -> * mut DIR {
-    let mut result: * mut DIR = ptr::null_mut();
+pub unsafe fn opendir(pathname: *const c_char) -> *mut DIR {
+    let mut result: *mut DIR = ptr::null_mut();
     let mut error: c_int = 0;
-    let status = u_opendir_ocall(&mut result as * mut * mut DIR,
-                                 &mut error as * mut c_int,
+    let status = u_opendir_ocall(&mut result as *mut *mut DIR,
+                                 &mut error as *mut c_int,
                                  pathname);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1216,11 +1223,11 @@ pub unsafe fn opendir(pathname: * const c_char) -> * mut DIR {
     result
 }
 
-pub unsafe fn readdir64_r(dirp: * mut DIR,
-                          entry: * mut dirent64,
-                          dirresult: * mut * mut dirent64) -> c_int {
+pub unsafe fn readdir64_r(dirp: *mut DIR,
+                          entry: *mut dirent64,
+                          dirresult: *mut *mut dirent64) -> c_int {
     let mut result: c_int = 0;
-    let status = u_readdir64_r_ocall(&mut result as * mut c_int,
+    let status = u_readdir64_r_ocall(&mut result as *mut c_int,
                                      dirp,
                                      entry,
                                      dirresult);
@@ -1238,11 +1245,11 @@ pub unsafe fn readdir64_r(dirp: * mut DIR,
     result
 }
                            
-pub unsafe fn closedir(dirp: * mut DIR) -> c_int {
+pub unsafe fn closedir(dirp: *mut DIR) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_closedir_ocall(&mut result as * mut c_int,
-                                  &mut error as * mut c_int,
+    let status = u_closedir_ocall(&mut result as *mut c_int,
+                                  &mut error as *mut c_int,
                                   dirp);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1256,11 +1263,11 @@ pub unsafe fn closedir(dirp: * mut DIR) -> c_int {
     result
 }   
 
-pub unsafe fn dirfd(dirp: * mut DIR) -> c_int {
+pub unsafe fn dirfd(dirp: *mut DIR) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_dirfd_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_dirfd_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                dirp);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1275,13 +1282,13 @@ pub unsafe fn dirfd(dirp: * mut DIR) -> c_int {
 }
 
 pub unsafe fn fstatat64(dirfd: c_int,
-                        pathname: * const c_char,
-                        buf: * mut stat64,
+                        pathname: *const c_char,
+                        buf: *mut stat64,
                         flags: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fstatat64_ocall(&mut result as * mut c_int,
-                                   &mut error as * mut c_int,
+    let status = u_fstatat64_ocall(&mut result as *mut c_int,
+                                   &mut error as *mut c_int,
                                    dirfd,
                                    pathname,
                                    buf,
@@ -1298,13 +1305,34 @@ pub unsafe fn fstatat64(dirfd: c_int,
     result
 }
 
-pub unsafe fn read(fd: c_int, buf: * mut c_void, count: size_t) -> ssize_t {
+pub unsafe fn read(fd: c_int, buf: *mut c_void, count: size_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_read_ocall(&mut result as * mut ssize_t,
-                              &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, count) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if count >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(count)
+    } else {
+        malloc(count)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    tmp_buf.write_bytes(0_u8, count);
+
+    let status = u_read_ocall(&mut result as *mut ssize_t,
+                              &mut error as *mut c_int,
                               fd,
-                              buf,
+                              tmp_buf,
                               count);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1315,16 +1343,46 @@ pub unsafe fn read(fd: c_int, buf: * mut c_void, count: size_t) -> ssize_t {
         set_errno(ESGX);
         result = -1;
     }
+
+    if result != -1 {
+        ptr::copy_nonoverlapping(tmp_buf as *mut u8, buf as *mut u8, count);
+    }
+    if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
     result
 }
 
-pub unsafe fn pread64(fd: c_int, buf: * mut c_void, count: size_t, offset: off64_t) -> ssize_t {
+pub unsafe fn pread64(fd: c_int, buf: *mut c_void, count: size_t, offset: off64_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_pread64_ocall(&mut result as * mut ssize_t,
-                                 &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, count) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if count >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(count)
+    } else {
+        malloc(count)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    tmp_buf.write_bytes(0_u8, count);
+
+    let status = u_pread64_ocall(&mut result as *mut ssize_t,
+                                 &mut error as *mut c_int,
                                  fd,
-                                 buf,
+                                 tmp_buf,
                                  count,
                                  offset);
 
@@ -1336,17 +1394,26 @@ pub unsafe fn pread64(fd: c_int, buf: * mut c_void, count: size_t, offset: off64
         set_errno(ESGX);
         result = -1;
     }
+
+    if result != -1 {
+        ptr::copy_nonoverlapping(tmp_buf as *mut u8, buf as *mut u8, count);
+    }
+    if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
     result
 }
 
-pub unsafe fn readv(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
+pub unsafe fn readv(fd: c_int, iov: *const iovec, iovcnt: c_int) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let mut ptr: * mut u8 = ptr::null_mut();
+    let mut ptr: *mut u8 = ptr::null_mut();
     let mut iosize: usize = 0;
 
     if iov.is_null() || iovcnt <= 0 ||
-       sgx_types::sgx_is_within_enclave(iov as * const c_void, iovcnt as usize * mem::size_of::<iovec>()) == 0 {
+       sgx_is_within_enclave(iov as *const c_void, iovcnt as usize * mem::size_of::<iovec>()) == 0 {
         set_errno(EINVAL);
         return -1;
     }
@@ -1354,7 +1421,7 @@ pub unsafe fn readv(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
     let v = slice::from_raw_parts(iov, iovcnt as usize);
     for io in v {
         if !io.iov_base.is_null() && io.iov_len > 0 &&
-            sgx_types::sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
+            sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
             iosize += io.iov_len as usize;
         } else {
             set_errno(EINVAL);
@@ -1362,7 +1429,7 @@ pub unsafe fn readv(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
         }
     }
 
-    let iobase = malloc(iosize) as * mut u8;
+    let iobase = malloc(iosize) as *mut u8;
     if iobase.is_null() {
         set_errno(ENOMEM );
         return -1;
@@ -1372,14 +1439,14 @@ pub unsafe fn readv(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
     let mut tmpiovec: Vec<iovec> = Vec::with_capacity(iovcnt as usize);
     ptr = iobase;
     for io in v {
-        let tmpiov = iovec{iov_base: ptr as * mut c_void,
+        let tmpiov = iovec{iov_base: ptr as *mut c_void,
                            iov_len: io.iov_len};
         tmpiovec.push(tmpiov);
         ptr = ptr.add(io.iov_len as usize);
     }
 
-    let status = u_readv_ocall(&mut result as * mut ssize_t,
-                               &mut error as * mut c_int,
+    let status = u_readv_ocall(&mut result as *mut ssize_t,
+                               &mut error as *mut c_int,
                                fd,
                                tmpiovec.as_slice().as_ptr(),
                                iovcnt);
@@ -1395,22 +1462,22 @@ pub unsafe fn readv(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
 
     if result != -1 {
         for i in 0..v.len() {
-            ptr::copy_nonoverlapping(tmpiovec[i].iov_base as * mut u8, v[i].iov_base as * mut u8, v[i].iov_len as usize);
+            ptr::copy_nonoverlapping(tmpiovec[i].iov_base as *mut u8, v[i].iov_base as *mut u8, v[i].iov_len as usize);
         }
     }
 
-    free(iobase as * mut c_void);
+    free(iobase as *mut c_void);
     result
 }
 
-pub unsafe fn preadv64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: off64_t) -> ssize_t {
+pub unsafe fn preadv64(fd: c_int, iov: *const iovec, iovcnt: c_int, offset: off64_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let mut ptr: * mut u8 = ptr::null_mut();
+    let mut ptr: *mut u8 = ptr::null_mut();
     let mut iosize: usize = 0;
 
     if iov.is_null() || iovcnt <= 0 ||
-       sgx_types::sgx_is_within_enclave(iov as * const c_void, iovcnt as usize * mem::size_of::<iovec>()) == 0 {
+       sgx_is_within_enclave(iov as *const c_void, iovcnt as usize * mem::size_of::<iovec>()) == 0 {
         set_errno(EINVAL);
         return -1;
     }
@@ -1418,7 +1485,7 @@ pub unsafe fn preadv64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: off
     let v = slice::from_raw_parts(iov, iovcnt as usize);
     for io in v {
         if !io.iov_base.is_null() && io.iov_len > 0 &&
-            sgx_types::sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
+            sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
             iosize += io.iov_len as usize;
         } else {
             set_errno(EINVAL);
@@ -1426,7 +1493,7 @@ pub unsafe fn preadv64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: off
         }
     }
 
-    let iobase = malloc(iosize) as * mut u8;
+    let iobase = malloc(iosize) as *mut u8;
     if iobase.is_null() {
         set_errno(ENOMEM );
         return -1;
@@ -1436,14 +1503,14 @@ pub unsafe fn preadv64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: off
     let mut tmpiovec: Vec<iovec> = Vec::with_capacity(iovcnt as usize);
     ptr = iobase;
     for io in v {
-        let tmpiov = iovec{iov_base: ptr as * mut c_void,
+        let tmpiov = iovec{iov_base: ptr as *mut c_void,
                            iov_len: io.iov_len};
         tmpiovec.push(tmpiov);
         ptr = ptr.add(io.iov_len as usize);
     }
 
-    let status = u_preadv64_ocall(&mut result as * mut ssize_t,
-                               &mut error as * mut c_int,
+    let status = u_preadv64_ocall(&mut result as *mut ssize_t,
+                               &mut error as *mut c_int,
                                fd,
                                tmpiovec.as_slice().as_ptr(),
                                iovcnt,
@@ -1460,21 +1527,42 @@ pub unsafe fn preadv64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: off
 
     if result != -1 {
         for i in 0..v.len() {
-            ptr::copy_nonoverlapping(tmpiovec[i].iov_base as * mut u8, v[i].iov_base as * mut u8, v[i].iov_len as usize);
+            ptr::copy_nonoverlapping(tmpiovec[i].iov_base as *mut u8, v[i].iov_base as *mut u8, v[i].iov_len as usize);
         }
     }
 
-    free(iobase as * mut c_void);
+    free(iobase as *mut c_void);
     result
 }
 
-pub unsafe fn write(fd: c_int, buf: * const c_void, count: size_t) -> ssize_t {
+pub unsafe fn write(fd: c_int, buf: *const c_void, count: size_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_write_ocall(&mut result as * mut ssize_t,
-                               &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, count) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if count >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(count)
+    } else {
+        malloc(count)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    ptr::copy_nonoverlapping(buf as *const u8, tmp_buf as *mut u8, count);
+
+    let status = u_write_ocall(&mut result as *mut ssize_t,
+                               &mut error as *mut c_int,
                                fd,
-                               buf,
+                               tmp_buf,
                                count);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1485,16 +1573,43 @@ pub unsafe fn write(fd: c_int, buf: * const c_void, count: size_t) -> ssize_t {
         set_errno(ESGX);
         result = -1;
     }
+
+    if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
     result
 }
 
-pub unsafe fn pwrite64(fd: c_int, buf: * const c_void, count: size_t, offset: off64_t) -> ssize_t {
+pub unsafe fn pwrite64(fd: c_int, buf: *const c_void, count: size_t, offset: off64_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_pwrite64_ocall(&mut result as * mut ssize_t,
-                                  &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, count) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if count >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(count)
+    } else {
+        malloc(count)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    ptr::copy_nonoverlapping(buf as *const u8, tmp_buf as *mut u8, count);
+
+    let status = u_pwrite64_ocall(&mut result as *mut ssize_t,
+                                  &mut error as *mut c_int,
                                   fd,
-                                  buf,
+                                  tmp_buf,
                                   count,
                                   offset);
 
@@ -1506,17 +1621,23 @@ pub unsafe fn pwrite64(fd: c_int, buf: * const c_void, count: size_t, offset: of
         set_errno(ESGX);
         result = -1;
     }
+
+    if count <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
     result
 }
 
-pub unsafe fn writev(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
+pub unsafe fn writev(fd: c_int, iov: *const iovec, iovcnt: c_int) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let mut ptr: * mut u8 = ptr::null_mut();
+    let mut ptr: *mut u8 = ptr::null_mut();
     let mut iosize: usize = 0;
 
     if iov.is_null() || iovcnt <= 0 ||
-       sgx_types::sgx_is_within_enclave(iov as * const c_void, iovcnt as usize * mem::size_of::<iovec>()) == 0 {
+       sgx_is_within_enclave(iov as *const c_void, iovcnt as usize * mem::size_of::<iovec>()) == 0 {
         set_errno(EINVAL);
         return -1;
     }
@@ -1524,7 +1645,7 @@ pub unsafe fn writev(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
     let v = slice::from_raw_parts(iov, iovcnt as usize);
     for io in v {
         if !io.iov_base.is_null() && io.iov_len > 0 &&
-            sgx_types::sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
+            sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
             iosize += io.iov_len as usize;
         } else {
             set_errno(EINVAL);
@@ -1532,7 +1653,7 @@ pub unsafe fn writev(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
         }
     }
 
-    let iobase = malloc(iosize) as * mut u8;
+    let iobase = malloc(iosize) as *mut u8;
     if iobase.is_null() {
         set_errno(ENOMEM );
         return -1;
@@ -1542,15 +1663,15 @@ pub unsafe fn writev(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
     let mut tmpiovec: Vec<iovec> = Vec::with_capacity(iovcnt as usize);
     ptr = iobase;
     for io in v {
-        let tmpiov = iovec{iov_base: ptr as * mut c_void,
+        let tmpiov = iovec{iov_base: ptr as *mut c_void,
                            iov_len: io.iov_len};
-        ptr::copy_nonoverlapping(tmpiov.iov_base as * mut u8, io.iov_base as * mut u8, io.iov_len as usize);
+        ptr::copy_nonoverlapping(tmpiov.iov_base as *mut u8, io.iov_base as *mut u8, io.iov_len as usize);
         tmpiovec.push(tmpiov);
         ptr = ptr.add(io.iov_len as usize);
     }
 
-    let status = u_writev_ocall(&mut result as * mut ssize_t,
-                                &mut error as * mut c_int,
+    let status = u_writev_ocall(&mut result as *mut ssize_t,
+                                &mut error as *mut c_int,
                                 fd,
                                 tmpiovec.as_slice().as_ptr(),
                                 iovcnt);
@@ -1564,18 +1685,18 @@ pub unsafe fn writev(fd: c_int, iov: * const iovec, iovcnt: c_int) -> ssize_t {
         result = -1;
     }
 
-    free(iobase as * mut c_void);
+    free(iobase as *mut c_void);
     result
 }
 
-pub unsafe fn pwritev64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: off64_t) -> ssize_t {
+pub unsafe fn pwritev64(fd: c_int, iov: *const iovec, iovcnt: c_int, offset: off64_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let mut ptr: * mut u8 = ptr::null_mut();
+    let mut ptr: *mut u8 = ptr::null_mut();
     let mut iosize: usize = 0;
 
     if iov.is_null() || iovcnt <= 0 ||
-       sgx_types::sgx_is_within_enclave(iov as * const c_void, iovcnt as usize * mem::size_of::<iovec>()) ==0 {
+       sgx_is_within_enclave(iov as *const c_void, iovcnt as usize * mem::size_of::<iovec>()) ==0 {
         set_errno(EINVAL);
         return -1;
     }
@@ -1583,7 +1704,7 @@ pub unsafe fn pwritev64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: of
     let v = slice::from_raw_parts(iov, iovcnt as usize);
     for io in v {
         if !io.iov_base.is_null() && io.iov_len > 0 &&
-            sgx_types::sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
+            sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
             iosize += io.iov_len as usize;
         } else {
             set_errno(EINVAL);
@@ -1591,7 +1712,7 @@ pub unsafe fn pwritev64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: of
         }
     }
 
-    let iobase = malloc(iosize) as * mut u8;
+    let iobase = malloc(iosize) as *mut u8;
     if iobase.is_null() {
         set_errno(ENOMEM );
         return -1;
@@ -1601,15 +1722,15 @@ pub unsafe fn pwritev64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: of
     let mut tmpiovec: Vec<iovec> = Vec::with_capacity(iovcnt as usize);
     ptr = iobase;
     for io in v {
-        let tmpiov = iovec{iov_base: ptr as * mut c_void,
+        let tmpiov = iovec{iov_base: ptr as *mut c_void,
                            iov_len: io.iov_len};
-        ptr::copy_nonoverlapping(tmpiov.iov_base as * mut u8, io.iov_base as * mut u8, io.iov_len as usize);
+        ptr::copy_nonoverlapping(tmpiov.iov_base as *mut u8, io.iov_base as *mut u8, io.iov_len as usize);
         tmpiovec.push(tmpiov);
         ptr = ptr.add(io.iov_len as usize);
     }
 
-    let status = u_pwritev64_ocall(&mut result as * mut ssize_t,
-                                   &mut error as * mut c_int,
+    let status = u_pwritev64_ocall(&mut result as *mut ssize_t,
+                                   &mut error as *mut c_int,
                                    fd,
                                    tmpiovec.as_slice().as_ptr(),
                                    iovcnt,
@@ -1624,15 +1745,15 @@ pub unsafe fn pwritev64(fd: c_int, iov: * const iovec, iovcnt: c_int, offset: of
         result = -1;
     }
 
-    free(iobase as * mut c_void);
+    free(iobase as *mut c_void);
     result
 }
 
 pub unsafe fn fcntl_arg0(fd: c_int, cmd: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fcntl_arg0_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_fcntl_arg0_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     fd,
                                     cmd);
 
@@ -1650,8 +1771,8 @@ pub unsafe fn fcntl_arg0(fd: c_int, cmd: c_int) -> c_int {
 pub unsafe fn fcntl_arg1(fd: c_int, cmd: c_int, arg: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_fcntl_arg1_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_fcntl_arg1_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     fd,
                                     cmd,
                                     arg);
@@ -1670,8 +1791,8 @@ pub unsafe fn fcntl_arg1(fd: c_int, cmd: c_int, arg: c_int) -> c_int {
 pub unsafe fn ioctl_arg0(fd: c_int, request: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_ioctl_arg0_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_ioctl_arg0_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     fd,
                                     request);
 
@@ -1686,13 +1807,14 @@ pub unsafe fn ioctl_arg0(fd: c_int, request: c_int) -> c_int {
     result
 }
 
-pub unsafe fn ioctl_arg1(fd: c_int, request: c_int, arg: * const c_int) -> c_int {
+pub unsafe fn ioctl_arg1(fd: c_int, request: c_int, arg: *mut c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_ioctl_arg1_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_ioctl_arg1_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     fd,
-                                    request,arg);
+                                    request,
+                                    arg);
 
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -1708,8 +1830,8 @@ pub unsafe fn ioctl_arg1(fd: c_int, request: c_int, arg: * const c_int) -> c_int
 pub unsafe fn close(fd: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_close_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_close_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                fd);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1723,11 +1845,11 @@ pub unsafe fn close(fd: c_int) -> c_int {
     result
 }
 
-pub unsafe fn clock_gettime(clk_id: clockid_t, tp: * mut timespec) -> c_int {
+pub unsafe fn clock_gettime(clk_id: clockid_t, tp: *mut timespec) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_clock_gettime_ocall(&mut result as * mut c_int,
-                                       &mut error as * mut c_int,
+    let status = u_clock_gettime_ocall(&mut result as *mut c_int,
+                                       &mut error as *mut c_int,
                                        clk_id,
                                        tp);
 
@@ -1742,7 +1864,6 @@ pub unsafe fn clock_gettime(clk_id: clockid_t, tp: * mut timespec) -> c_int {
     result
 }
 
-
 pub unsafe fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
@@ -1784,11 +1905,11 @@ pub unsafe fn socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_i
     result
 }
 
-pub unsafe fn bind(sockfd: c_int, address: * const sockaddr, addrlen: socklen_t) -> c_int {
+pub unsafe fn bind(sockfd: c_int, address: *const sockaddr, addrlen: socklen_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_bind_ocall(&mut result as * mut c_int,
-                              &mut error as * mut c_int,
+    let status = u_bind_ocall(&mut result as *mut c_int,
+                              &mut error as *mut c_int,
                               sockfd,
                               address,
                               addrlen);
@@ -1833,7 +1954,7 @@ pub unsafe fn accept(sockfd: c_int, addr: *mut sockaddr, addrlen: *mut socklen_t
                                 sockfd,
                                 addr,
                                 len_in, // This additional arg is just for EDL
-                                &mut len_out as * mut socklen_t);
+                                &mut len_out as *mut socklen_t);
 
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -1860,7 +1981,7 @@ pub unsafe fn accept4(sockfd: c_int, addr: *mut sockaddr, addrlen: *mut socklen_
                                  sockfd,
                                  addr,
                                  len_in, // This additional arg is just for EDL
-                                 &mut len_out as * mut socklen_t,
+                                 &mut len_out as *mut socklen_t,
                                  flags);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -1878,11 +1999,11 @@ pub unsafe fn accept4(sockfd: c_int, addr: *mut sockaddr, addrlen: *mut socklen_
     result
 }
 
-pub unsafe fn connect(sockfd: c_int, address: * const sockaddr, addrlen: socklen_t) -> c_int {
+pub unsafe fn connect(sockfd: c_int, address: *const sockaddr, addrlen: socklen_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_connect_ocall(&mut result as * mut c_int,
-                                 &mut error as * mut c_int,
+    let status = u_connect_ocall(&mut result as *mut c_int,
+                                 &mut error as *mut c_int,
                                  sockfd,
                                  address,
                                  addrlen);
@@ -1898,13 +2019,34 @@ pub unsafe fn connect(sockfd: c_int, address: * const sockaddr, addrlen: socklen
     result
 }
 
-pub unsafe fn send(sockfd: c_int, buf: * const c_void, len: size_t, flags: c_int) -> ssize_t {
+pub unsafe fn send(sockfd: c_int, buf: *const c_void, len: size_t, flags: c_int) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_send_ocall(&mut result as * mut ssize_t,
-                              &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, len) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if len >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(len)
+    } else {
+        malloc(len)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    ptr::copy_nonoverlapping(buf as *const u8, tmp_buf as *mut u8, len);
+
+    let status = u_send_ocall(&mut result as *mut ssize_t,
+                              &mut error as *mut c_int,
                               sockfd,
-                              buf,
+                              tmp_buf,
                               len,
                               flags);
 
@@ -1916,21 +2058,48 @@ pub unsafe fn send(sockfd: c_int, buf: * const c_void, len: size_t, flags: c_int
         set_errno(ESGX);
         result = -1;
     }
+
+    if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
     result
 }
 
 pub unsafe fn sendto(sockfd: c_int,
-                     buf: * const c_void,
+                     buf: *const c_void,
                      len: size_t,
                      flags: c_int,
-                     addr: * const sockaddr,
+                     addr: *const sockaddr,
                      addrlen: socklen_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_sendto_ocall(&mut result as * mut ssize_t,
-                                &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, len) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if len >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(len)
+    } else {
+        malloc(len)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    ptr::copy_nonoverlapping(buf as *const u8, tmp_buf as *mut u8, len);
+
+    let status = u_sendto_ocall(&mut result as *mut ssize_t,
+                                &mut error as *mut c_int,
                                 sockfd,
-                                buf,
+                                tmp_buf,
                                 len,
                                 flags,
                                 addr,
@@ -1944,34 +2113,40 @@ pub unsafe fn sendto(sockfd: c_int,
         set_errno(ESGX);
         result = -1;
     }
+
+    if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
     result
 }
 
-pub unsafe fn sendmsg(sockfd: c_int, msg: * const msghdr, flags: c_int) -> ssize_t {
+pub unsafe fn sendmsg(sockfd: c_int, msg: *const msghdr, flags: c_int) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
     let mut hdrsize: usize = 0;
-    let mut ptr: * mut u8 = ptr::null_mut();
+    let mut ptr: *mut u8 = ptr::null_mut();
 
-    if msg.is_null() || sgx_types::sgx_is_within_enclave(msg as * const c_void, mem::size_of::<msghdr>()) == 0 {
+    if msg.is_null() || sgx_is_within_enclave(msg as *const c_void, mem::size_of::<msghdr>()) == 0 {
         set_errno(EINVAL);
         return -1;
     }
 
     let mhdr: &msghdr = &*msg;
     if !mhdr.msg_name.is_null() && mhdr.msg_namelen > 0 &&
-        sgx_types::sgx_is_within_enclave(mhdr.msg_name, mhdr.msg_namelen as usize) != 0 {
+        sgx_is_within_enclave(mhdr.msg_name, mhdr.msg_namelen as usize) != 0 {
         hdrsize += mhdr.msg_namelen as usize;
     }
 
     if !mhdr.msg_iov.is_null() && mhdr.msg_iovlen > 0 &&
-       sgx_types::sgx_is_within_enclave(mhdr.msg_iov as * const c_void, mhdr.msg_iovlen as usize * mem::size_of::<iovec>()) != 0 {
+       sgx_is_within_enclave(mhdr.msg_iov as *const c_void, mhdr.msg_iovlen as usize * mem::size_of::<iovec>()) != 0 {
 
         hdrsize += mhdr.msg_iovlen as usize * mem::size_of::<iovec>();
         let v = slice::from_raw_parts(mhdr.msg_iov, mhdr.msg_iovlen as usize);
         for io in v {
             if !io.iov_base.is_null() && io.iov_len > 0 &&
-                sgx_types::sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
+                sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
                 hdrsize += io.iov_len as usize;
             } else {
                 set_errno(EINVAL);
@@ -1981,11 +2156,11 @@ pub unsafe fn sendmsg(sockfd: c_int, msg: * const msghdr, flags: c_int) -> ssize
     }
 
     if !mhdr.msg_control.is_null() &&  mhdr.msg_controllen > 0 &&
-        sgx_types::sgx_is_within_enclave(mhdr.msg_control, mhdr.msg_controllen as usize) != 0 {
+        sgx_is_within_enclave(mhdr.msg_control, mhdr.msg_controllen as usize) != 0 {
         hdrsize += mhdr.msg_controllen as usize;
     }
 
-    let hdrbase = malloc(hdrsize) as * mut u8;
+    let hdrbase = malloc(hdrsize) as *mut u8;
     if hdrbase.is_null() {
         set_errno(ENOMEM );
         return -1;
@@ -1995,35 +2170,35 @@ pub unsafe fn sendmsg(sockfd: c_int, msg: * const msghdr, flags: c_int) -> ssize
     let mut tmpmsg: msghdr = mem::zeroed();
     ptr = hdrbase;
     if !mhdr.msg_name.is_null() && mhdr.msg_namelen > 0 {
-        tmpmsg.msg_name = ptr as * mut c_void;
+        tmpmsg.msg_name = ptr as *mut c_void;
         tmpmsg.msg_namelen = mhdr.msg_namelen;
-        ptr::copy_nonoverlapping(mhdr.msg_name as * mut u8, tmpmsg.msg_name as * mut u8, mhdr.msg_namelen as usize);
+        ptr::copy_nonoverlapping(mhdr.msg_name as *mut u8, tmpmsg.msg_name as *mut u8, mhdr.msg_namelen as usize);
         ptr = ptr.add(mhdr.msg_namelen as usize);
     }
 
     if !mhdr.msg_iov.is_null() && mhdr.msg_iovlen > 0 {
-        let tmpiov = slice::from_raw_parts_mut(ptr as * mut iovec, mhdr.msg_iovlen as usize);
+        let tmpiov = slice::from_raw_parts_mut(ptr as *mut iovec, mhdr.msg_iovlen as usize);
         ptr = ptr.add(mhdr.msg_iovlen as usize * mem::size_of::<iovec>());
 
         let v = slice::from_raw_parts(mhdr.msg_iov, mhdr.msg_iovlen as usize);
         for i in 0..v.len() {
-            tmpiov[i].iov_base = ptr as * mut c_void;
+            tmpiov[i].iov_base = ptr as *mut c_void;
             tmpiov[i].iov_len = v[i].iov_len;
-            ptr::copy_nonoverlapping(v[i].iov_base as * mut u8, tmpiov[i].iov_base as * mut u8, v[i].iov_len as usize);
+            ptr::copy_nonoverlapping(v[i].iov_base as *mut u8, tmpiov[i].iov_base as *mut u8, v[i].iov_len as usize);
             ptr = ptr.add(v[i].iov_len as usize);
         }
     }
 
     if !mhdr.msg_control.is_null() &&  mhdr.msg_controllen > 0 {
-        tmpmsg.msg_control = ptr as * mut c_void;
+        tmpmsg.msg_control = ptr as *mut c_void;
         tmpmsg.msg_controllen = mhdr.msg_controllen;
-        ptr::copy_nonoverlapping(mhdr.msg_control as * mut u8, tmpmsg.msg_control as * mut u8, mhdr.msg_controllen as usize);
+        ptr::copy_nonoverlapping(mhdr.msg_control as *mut u8, tmpmsg.msg_control as *mut u8, mhdr.msg_controllen as usize);
     }
 
-    let status = u_sendmsg_ocall(&mut result as * mut ssize_t,
-                                 &mut error as * mut c_int,
+    let status = u_sendmsg_ocall(&mut result as *mut ssize_t,
+                                 &mut error as *mut c_int,
                                  sockfd,
-                                 &tmpmsg as * const msghdr,
+                                 &tmpmsg as *const msghdr,
                                  flags);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -2035,17 +2210,38 @@ pub unsafe fn sendmsg(sockfd: c_int, msg: * const msghdr, flags: c_int) -> ssize
         result = -1;
     }
 
-    free(hdrbase as * mut c_void);
+    free(hdrbase as *mut c_void);
     result
 }
 
-pub unsafe fn recv(sockfd: c_int, buf: * mut c_void, len: size_t, flags: c_int) -> ssize_t {
+pub unsafe fn recv(sockfd: c_int, buf: *mut c_void, len: size_t, flags: c_int) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
-    let status = u_recv_ocall(&mut result as * mut ssize_t,
-                              &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, len) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if len >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(len)
+    } else {
+        malloc(len)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    tmp_buf.write_bytes(0_u8, len);
+
+    let status = u_recv_ocall(&mut result as *mut ssize_t,
+                              &mut error as *mut c_int,
                               sockfd,
-                              buf,
+                              tmp_buf,
                               len,
                               flags);
 
@@ -2057,28 +2253,58 @@ pub unsafe fn recv(sockfd: c_int, buf: * mut c_void, len: size_t, flags: c_int)
         set_errno(ESGX);
         result = -1;
     }
+
+    if result != -1 {
+        ptr::copy_nonoverlapping(tmp_buf as *mut u8, buf as *mut u8, len);
+    }
+    if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
     result
 }
 
 pub unsafe fn recvfrom(sockfd: c_int,
-                       buf: * mut c_void,
+                       buf: *mut c_void,
                        len: size_t,
                        flags: c_int,
-                       addr: * mut sockaddr,
-                       addrlen: * mut socklen_t) -> ssize_t {
+                       addr: *mut sockaddr,
+                       addrlen: *mut socklen_t) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
     let len_in: socklen_t = if !addrlen.is_null() { *addrlen } else { 0 };
     let mut len_out: socklen_t = 0 as socklen_t;
-    let status = u_recvfrom_ocall(&mut result as * mut ssize_t,
-                                  &mut error as * mut c_int,
+
+    if buf.is_null() || sgx_is_within_enclave(buf, len) == 0 {
+        set_errno(EINVAL);
+        return -1;
+    }
+    if len >= usize::max_value() {
+        set_errno(EINVAL);
+        return -1;
+    }
+
+    let tmp_buf = if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocalloc(len)
+    } else {
+        malloc(len)
+    };
+    if tmp_buf.is_null() {
+        set_errno(ENOMEM );
+        return -1;
+    }
+    tmp_buf.write_bytes(0_u8, len);
+
+    let status = u_recvfrom_ocall(&mut result as *mut ssize_t,
+                                  &mut error as *mut c_int,
                                   sockfd,
-                                  buf,
+                                  tmp_buf,
                                   len,
                                   flags,
                                   addr,
                                   len_in, // This additional arg is just for EDL
-                                  &mut len_out as * mut socklen_t);
+                                  &mut len_out as *mut socklen_t);
 
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -2089,37 +2315,46 @@ pub unsafe fn recvfrom(sockfd: c_int,
         result = -1;
     }
 
+    if result != -1 {
+        ptr::copy_nonoverlapping(tmp_buf as *mut u8, buf as *mut u8, len);
+    }
+    if len <= MAX_OCALL_ALLOC_SIZE {
+        sgx_ocfree();
+    } else {
+        free(tmp_buf);
+    }
+
     if !addrlen.is_null() {
         *addrlen = len_out;
     }
     result
 }
 
-pub unsafe fn recvmsg(sockfd: c_int, msg: * mut msghdr, flags: c_int) -> ssize_t {
+pub unsafe fn recvmsg(sockfd: c_int, msg: *mut msghdr, flags: c_int) -> ssize_t {
     let mut result: ssize_t = 0;
     let mut error: c_int = 0;
     let mut hdrsize: usize = 0;
-    let mut ptr: * mut u8 = ptr::null_mut();
+    let mut ptr: *mut u8 = ptr::null_mut();
 
-    if msg.is_null() || sgx_types::sgx_is_within_enclave(msg as * const c_void, mem::size_of::<msghdr>()) == 0 {
+    if msg.is_null() || sgx_is_within_enclave(msg as *const c_void, mem::size_of::<msghdr>()) == 0 {
         set_errno(EINVAL);
         return -1;
     }
 
     let mhdr: &mut msghdr = &mut *msg;
     if !mhdr.msg_name.is_null() && mhdr.msg_namelen > 0 &&
-        sgx_types::sgx_is_within_enclave(mhdr.msg_name, mhdr.msg_namelen as usize) != 0 {
+        sgx_is_within_enclave(mhdr.msg_name, mhdr.msg_namelen as usize) != 0 {
         hdrsize += mhdr.msg_namelen as usize;
     }
 
     if !mhdr.msg_iov.is_null() && mhdr.msg_iovlen > 0 &&
-       sgx_types::sgx_is_within_enclave(mhdr.msg_iov as * const c_void, mhdr.msg_iovlen as usize * mem::size_of::<iovec>()) != 0 {
+       sgx_is_within_enclave(mhdr.msg_iov as *const c_void, mhdr.msg_iovlen as usize * mem::size_of::<iovec>()) != 0 {
 
         hdrsize += mhdr.msg_iovlen as usize * mem::size_of::<iovec>();
         let v = slice::from_raw_parts(mhdr.msg_iov, mhdr.msg_iovlen as usize);
         for io in v {
             if !io.iov_base.is_null() && io.iov_len > 0 &&
-                sgx_types::sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
+                sgx_is_within_enclave(io.iov_base, io.iov_len as usize) != 0 {
                 hdrsize += io.iov_len as usize;
             } else {
                 set_errno(EINVAL);
@@ -2129,11 +2364,11 @@ pub unsafe fn recvmsg(sockfd: c_int, msg: * mut msghdr, flags: c_int) -> ssize_t
     }
 
     if !mhdr.msg_control.is_null() &&  mhdr.msg_controllen > 0 &&
-        sgx_types::sgx_is_within_enclave(mhdr.msg_control, mhdr.msg_controllen as usize) != 0 {
+        sgx_is_within_enclave(mhdr.msg_control, mhdr.msg_controllen as usize) != 0 {
         hdrsize += mhdr.msg_controllen as usize;
     }
 
-    let hdrbase = malloc(hdrsize) as * mut u8;
+    let hdrbase = malloc(hdrsize) as *mut u8;
     if hdrbase.is_null() {
         set_errno(ENOMEM );
         return -1;
@@ -2143,34 +2378,34 @@ pub unsafe fn recvmsg(sockfd: c_int, msg: * mut msghdr, flags: c_int) -> ssize_t
     let mut tmpmsg: msghdr = mem::zeroed();
     ptr = hdrbase;
     if !mhdr.msg_name.is_null() && mhdr.msg_namelen > 0 {
-        tmpmsg.msg_name = ptr as * mut c_void;
+        tmpmsg.msg_name = ptr as *mut c_void;
         tmpmsg.msg_namelen = mhdr.msg_namelen;
-        ptr::copy_nonoverlapping(mhdr.msg_name as * mut u8, tmpmsg.msg_name as * mut u8, mhdr.msg_namelen as usize);
+        ptr::copy_nonoverlapping(mhdr.msg_name as *mut u8, tmpmsg.msg_name as *mut u8, mhdr.msg_namelen as usize);
         ptr = ptr.add(mhdr.msg_namelen as usize);
     }
 
     if !mhdr.msg_iov.is_null() && mhdr.msg_iovlen > 0 {
-        let tmpiov = slice::from_raw_parts_mut(ptr as * mut iovec, mhdr.msg_iovlen as usize);
+        let tmpiov = slice::from_raw_parts_mut(ptr as *mut iovec, mhdr.msg_iovlen as usize);
         ptr = ptr.add(mhdr.msg_iovlen as usize * mem::size_of::<iovec>());
 
         let v = slice::from_raw_parts(mhdr.msg_iov, mhdr.msg_iovlen as usize);
         for i in 0..v.len() {
-            tmpiov[i].iov_base = ptr as * mut c_void;
+            tmpiov[i].iov_base = ptr as *mut c_void;
             tmpiov[i].iov_len = v[i].iov_len;
             ptr = ptr.add(v[i].iov_len as usize);
         }
     }
 
     if !mhdr.msg_control.is_null() &&  mhdr.msg_controllen > 0 {
-        tmpmsg.msg_control = ptr as * mut c_void;
+        tmpmsg.msg_control = ptr as *mut c_void;
         tmpmsg.msg_controllen = mhdr.msg_controllen;
-        ptr::copy_nonoverlapping(mhdr.msg_control as * mut u8, tmpmsg.msg_control as * mut u8, mhdr.msg_controllen as usize);
+        ptr::copy_nonoverlapping(mhdr.msg_control as *mut u8, tmpmsg.msg_control as *mut u8, mhdr.msg_controllen as usize);
     }
 
-    let status = u_recvmsg_ocall(&mut result as * mut ssize_t,
-                                 &mut error as * mut c_int,
+    let status = u_recvmsg_ocall(&mut result as *mut ssize_t,
+                                 &mut error as *mut c_int,
                                  sockfd,
-                                 &mut tmpmsg as * mut msghdr,
+                                 &mut tmpmsg as *mut msghdr,
                                  flags);
 
     if status == sgx_status_t::SGX_SUCCESS {
@@ -2188,33 +2423,33 @@ pub unsafe fn recvmsg(sockfd: c_int, msg: * mut msghdr, flags: c_int) -> ssize_t
     }
 
     if !mhdr.msg_iov.is_null() && mhdr.msg_iovlen > 0 {
-        let tmpiov = slice::from_raw_parts_mut(ptr as * mut iovec, mhdr.msg_iovlen as usize);
+        let tmpiov = slice::from_raw_parts_mut(ptr as *mut iovec, mhdr.msg_iovlen as usize);
         ptr = ptr.add(mhdr.msg_iovlen as usize * mem::size_of::<iovec>());
 
         let v = slice::from_raw_parts(mhdr.msg_iov, mhdr.msg_iovlen as usize);
         for i in 0..v.len() {
-            ptr::copy_nonoverlapping(tmpiov[i].iov_base as * mut u8, v[i].iov_base as * mut u8, v[i].iov_len as usize);
+            ptr::copy_nonoverlapping(tmpiov[i].iov_base as *mut u8, v[i].iov_base as *mut u8, v[i].iov_len as usize);
             ptr = ptr.add(v[i].iov_len as usize);
         }
     }
 
     if !mhdr.msg_control.is_null() &&  mhdr.msg_controllen > 0 {
-        ptr::copy_nonoverlapping(tmpmsg.msg_control as * mut u8, mhdr.msg_control as * mut u8, mhdr.msg_controllen as usize);
+        ptr::copy_nonoverlapping(tmpmsg.msg_control as *mut u8, mhdr.msg_control as *mut u8, mhdr.msg_controllen as usize);
     }
 
-    free(hdrbase as * mut c_void);
+    free(hdrbase as *mut c_void);
     result
 }
 
 pub unsafe fn setsockopt(sockfd: c_int,
                          level: c_int,
                          optname: c_int,
-                         optval: * const c_void,
+                         optval: *const c_void,
                          optlen: socklen_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_setsockopt_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_setsockopt_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     sockfd,
                                     level,
                                     optname,
@@ -2235,21 +2470,21 @@ pub unsafe fn setsockopt(sockfd: c_int,
 pub unsafe fn getsockopt(sockfd: c_int,
                          level: c_int,
                          optname: c_int,
-                         optval: * mut c_void,
-                         optlen: * mut socklen_t) -> c_int {
+                         optval: *mut c_void,
+                         optlen: *mut socklen_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
     let len_in: socklen_t = if !optlen.is_null() { *optlen } else { 0 };
     let mut len_out: socklen_t = 0 as socklen_t;
 
-    let status = u_getsockopt_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_getsockopt_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     sockfd,
                                     level,
                                     optname,
                                     optval,
                                     len_in,
-                                    &mut len_out as * mut socklen_t);
+                                    &mut len_out as *mut socklen_t);
 
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -2266,17 +2501,17 @@ pub unsafe fn getsockopt(sockfd: c_int,
     result
 }
 
-pub unsafe fn getpeername(sockfd: c_int, address: * mut sockaddr, addrlen: * mut socklen_t) -> c_int {
+pub unsafe fn getpeername(sockfd: c_int, address: *mut sockaddr, addrlen: *mut socklen_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
     let len_in: socklen_t = if !addrlen.is_null() { *addrlen } else { 0 };
     let mut len_out: socklen_t = 0 as socklen_t;
-    let status = u_getpeername_ocall(&mut result as * mut c_int,
-                                     &mut error as * mut c_int,
+    let status = u_getpeername_ocall(&mut result as *mut c_int,
+                                     &mut error as *mut c_int,
                                      sockfd,
                                      address,
                                      len_in,
-                                     &mut len_out as * mut socklen_t);
+                                     &mut len_out as *mut socklen_t);
 
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -2293,17 +2528,17 @@ pub unsafe fn getpeername(sockfd: c_int, address: * mut sockaddr, addrlen: * mut
     result
 }
 
-pub unsafe fn getsockname(sockfd: c_int, address: * mut sockaddr, addrlen: * mut socklen_t) -> c_int {
+pub unsafe fn getsockname(sockfd: c_int, address: *mut sockaddr, addrlen: *mut socklen_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
     let len_in: socklen_t = if !addrlen.is_null() { *addrlen } else { 0 };
     let mut len_out: socklen_t = 0 as socklen_t;
-    let status = u_getsockname_ocall(&mut result as * mut c_int,
-                                     &mut error as * mut c_int,
+    let status = u_getsockname_ocall(&mut result as *mut c_int,
+                                     &mut error as *mut c_int,
                                      sockfd,
                                      address,
                                      len_in,
-                                     &mut len_out as * mut socklen_t);
+                                     &mut len_out as *mut socklen_t);
 
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -2323,8 +2558,8 @@ pub unsafe fn getsockname(sockfd: c_int, address: * mut sockaddr, addrlen: * mut
 pub unsafe fn shutdown(sockfd: c_int, how: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_shutdown_ocall(&mut result as * mut c_int,
-                                  &mut error as * mut c_int,
+    let status = u_shutdown_ocall(&mut result as *mut c_int,
+                                  &mut error as *mut c_int,
                                   sockfd,
                                   how);
 
@@ -2339,10 +2574,13 @@ pub unsafe fn shutdown(sockfd: c_int, how: c_int) -> c_int {
     result
 }
 
-pub unsafe fn getaddrinfo(node: * const c_char, service: * const c_char, hints: * const addrinfo, res: * mut * mut addrinfo) -> c_int {
+pub unsafe fn getaddrinfo(node: *const c_char,
+                          service: *const c_char,
+                          hints: *const addrinfo,
+                          res: *mut *mut addrinfo) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let mut ret_res: * mut addrinfo = ptr::null_mut();
+    let mut ret_res: *mut addrinfo = ptr::null_mut();
     let hint: addrinfo = addrinfo {
         ai_flags: (*hints).ai_flags,
         ai_family: (*hints).ai_family,
@@ -2354,16 +2592,16 @@ pub unsafe fn getaddrinfo(node: * const c_char, service: * const c_char, hints:
         ai_next: ptr::null_mut(),
     };
 
-    let status = u_getaddrinfo_ocall(&mut result as * mut c_int,
-                                     &mut error as * mut c_int,
+    let status = u_getaddrinfo_ocall(&mut result as *mut c_int,
+                                     &mut error as *mut c_int,
                                      node,
                                      service,
-                                     &hint as * const addrinfo,
-                                     &mut ret_res as * mut * mut addrinfo);
+                                     &hint as *const addrinfo,
+                                     &mut ret_res as *mut *mut addrinfo);
     if status == sgx_status_t::SGX_SUCCESS {
         if result == 0 {
             *res = ptr::null_mut();
-            let mut cur_ptr: * mut addrinfo = ret_res;
+            let mut cur_ptr: *mut addrinfo = ret_res;
             let mut addrinfo_vec: Vec<Box<addrinfo>> = Vec::new();
             while cur_ptr != ptr::null_mut() {
                 let cur: &addrinfo = &*cur_ptr;
@@ -2380,21 +2618,21 @@ pub unsafe fn getaddrinfo(node: * const c_char, service: * const c_char, hints:
 
                 if !cur.ai_addr.is_null() && cur.ai_addrlen > 0 {
                     let mut addr_vec = vec![0u8; cur.ai_addrlen as usize];
-                    let addr_slice: &[u8] = slice::from_raw_parts(cur.ai_addr as * const u8, cur.ai_addrlen as usize);
+                    let addr_slice: &[u8] = slice::from_raw_parts(cur.ai_addr as *const u8, cur.ai_addrlen as usize);
                     addr_vec.copy_from_slice(addr_slice);
                     addr_vec.shrink_to_fit();
                     info.ai_addrlen = cur.ai_addrlen;
-                    info.ai_addr = addr_vec.as_mut_ptr() as * mut sockaddr;
+                    info.ai_addr = addr_vec.as_mut_ptr() as *mut sockaddr;
                     mem::forget(addr_vec);
                 }
 
                 if !cur.ai_canonname.is_null() {
                     let len: usize = strlen(cur.ai_canonname) + 1;
                     let mut name_vec = vec![0u8; len];
-                    let name_slice: &[u8] = slice::from_raw_parts(cur.ai_canonname as * const u8, len);
+                    let name_slice: &[u8] = slice::from_raw_parts(cur.ai_canonname as *const u8, len);
                     name_vec.copy_from_slice(name_slice);
                     name_vec.shrink_to_fit();
-                    info.ai_canonname = name_vec.as_mut_ptr() as * mut c_char;
+                    info.ai_canonname = name_vec.as_mut_ptr() as *mut c_char;
                     mem::forget(name_vec);
                 }
 
@@ -2404,9 +2642,9 @@ pub unsafe fn getaddrinfo(node: * const c_char, service: * const c_char, hints:
 
             if addrinfo_vec.len() > 0 {
                 for i in 0..addrinfo_vec.len() - 1 {
-                    addrinfo_vec[i].ai_next = addrinfo_vec[i + 1].as_mut() as * mut addrinfo;
+                    addrinfo_vec[i].ai_next = addrinfo_vec[i + 1].as_mut() as *mut addrinfo;
                 }
-                *res = addrinfo_vec[0].as_mut() as * mut addrinfo;
+                *res = addrinfo_vec[0].as_mut() as *mut addrinfo;
 
                 for info in addrinfo_vec {
                     let _ = Box::into_raw(info);
@@ -2424,18 +2662,18 @@ pub unsafe fn getaddrinfo(node: * const c_char, service: * const c_char, hints:
     result
 }
 
-pub unsafe fn freeaddrinfo(res: * mut addrinfo ) {
-    let mut cur_ptr: * mut addrinfo = res;
+pub unsafe fn freeaddrinfo(res: *mut addrinfo ) {
+    let mut cur_ptr: *mut addrinfo = res;
     let mut addrinfo_vec: Vec<Box<addrinfo>> = Vec::new();
     while cur_ptr != ptr::null_mut() {
         let cur: &addrinfo = &*cur_ptr;
         if !cur.ai_addr.is_null() && cur.ai_addrlen > 0 {
-            let addr_vec = Vec::from_raw_parts(cur.ai_addr as * mut u8, cur.ai_addrlen as usize, cur.ai_addrlen as usize);
+            let addr_vec = Vec::from_raw_parts(cur.ai_addr as *mut u8, cur.ai_addrlen as usize, cur.ai_addrlen as usize);
             drop(addr_vec);
         }
         if !cur.ai_canonname.is_null() {
             let len: usize = strlen(cur.ai_canonname) + 1;
-            let name_vec = Vec::from_raw_parts(cur.ai_canonname as * mut u8, len, len);
+            let name_vec = Vec::from_raw_parts(cur.ai_canonname as *mut u8, len, len);
             drop(name_vec);
         }
         addrinfo_vec.push(Box::from_raw(cur_ptr));
@@ -2444,20 +2682,20 @@ pub unsafe fn freeaddrinfo(res: * mut addrinfo ) {
     drop(addrinfo_vec);
 }
 
-pub unsafe fn gai_strerror(errcode: c_int) -> * const c_char {
-    let mut result: * const c_char = ptr::null();
-    let status = u_gai_strerror_ocall(&mut result as * mut * const c_char, errcode);
+pub unsafe fn gai_strerror(errcode: c_int) -> *const c_char {
+    let mut result: *const c_char = ptr::null();
+    let status = u_gai_strerror_ocall(&mut result as *mut *const c_char, errcode);
     if status != sgx_status_t::SGX_SUCCESS {
         set_errno(ESGX);
     }
     result
 }
 
-pub unsafe fn poll(fds: * mut pollfd, nfds: nfds_t, timeout: c_int) -> c_int {
+pub unsafe fn poll(fds: *mut pollfd, nfds: nfds_t, timeout: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_poll_ocall(&mut result as * mut c_int,
-                              &mut error as * mut c_int,
+    let status = u_poll_ocall(&mut result as *mut c_int,
+                              &mut error as *mut c_int,
                               fds,
                               nfds,
                               timeout);
@@ -2476,8 +2714,8 @@ pub unsafe fn poll(fds: * mut pollfd, nfds: nfds_t, timeout: c_int) -> c_int {
 pub unsafe fn epoll_create1(flags: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_epoll_create1_ocall(&mut result as * mut c_int,
-                                       &mut error as * mut c_int,
+    let status = u_epoll_create1_ocall(&mut result as *mut c_int,
+                                       &mut error as *mut c_int,
                                        flags);
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -2490,11 +2728,14 @@ pub unsafe fn epoll_create1(flags: c_int) -> c_int {
     result
 }
 
-pub unsafe fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: * mut epoll_event) -> c_int {
+pub unsafe fn epoll_ctl(epfd: c_int,
+                        op: c_int,
+                        fd: c_int,
+                        event: *mut epoll_event) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_epoll_ctl_ocall(&mut result as * mut c_int,
-                                   &mut error as * mut c_int,
+    let status = u_epoll_ctl_ocall(&mut result as *mut c_int,
+                                   &mut error as *mut c_int,
                                    epfd,
                                    op,
                                    fd,
@@ -2510,11 +2751,14 @@ pub unsafe fn epoll_ctl(epfd: c_int, op: c_int, fd: c_int, event: * mut epoll_ev
     result
 }
 
-pub unsafe fn epoll_wait(epfd: c_int, events: * mut epoll_event, maxevents: c_int, timeout: c_int) -> c_int {
+pub unsafe fn epoll_wait(epfd: c_int,
+                         events: *mut epoll_event,
+                         maxevents: c_int,
+                         timeout: c_int) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_epoll_wait_ocall(&mut result as * mut c_int,
-                                    &mut error as * mut c_int,
+    let status = u_epoll_wait_ocall(&mut result as *mut c_int,
+                                    &mut error as *mut c_int,
                                     epfd,
                                     events,
                                     maxevents,
@@ -2533,8 +2777,8 @@ pub unsafe fn epoll_wait(epfd: c_int, events: * mut epoll_event, maxevents: c_in
 pub unsafe fn sysconf(name: c_int) -> c_long {
     let mut result: c_long = 0;
     let mut error: c_int = 0;
-    let status = u_sysconf_ocall(&mut result as * mut c_long,
-                                 &mut error as * mut c_int,
+    let status = u_sysconf_ocall(&mut result as *mut c_long,
+                                 &mut error as *mut c_int,
                                  name);
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
@@ -2554,8 +2798,8 @@ pub unsafe fn prctl(option: c_int,
                     arg5: c_ulong) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_prctl_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
+    let status = u_prctl_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
                                option,
                                arg2,
                                arg3,
@@ -2572,13 +2816,14 @@ pub unsafe fn prctl(option: c_int,
     result
 }
 
-
-pub unsafe fn pipe(fds: * mut c_int) -> c_int {
+pub unsafe fn sched_setaffinity(pid: pid_t, cpusetsize: size_t, mask: *const cpu_set_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_pipe_ocall(&mut result as * mut c_int,
-                              &mut error as * mut c_int,
-                              fds);
+    let status = u_sched_setaffinity_ocall(&mut result as *mut c_int,
+                                           &mut error as *mut c_int,
+                                           pid,
+                                           cpusetsize,
+                                           mask);
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
             set_errno(error);
@@ -2590,13 +2835,14 @@ pub unsafe fn pipe(fds: * mut c_int) -> c_int {
     result
 }
 
-pub unsafe fn pipe2(fds: * mut c_int, flags: c_int) -> c_int {
+pub unsafe fn sched_getaffinity(pid: pid_t, cpusetsize: size_t, mask: *mut cpu_set_t) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_pipe2_ocall(&mut result as * mut c_int,
-                               &mut error as * mut c_int,
-                               fds,
-                               flags);
+    let status = u_sched_getaffinity_ocall(&mut result as *mut c_int,
+                                           &mut error as *mut c_int,
+                                           pid,
+                                           cpusetsize,
+                                           mask);
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
             set_errno(error);
@@ -2608,40 +2854,37 @@ pub unsafe fn pipe2(fds: * mut c_int, flags: c_int) -> c_int {
     result
 }
 
-pub unsafe fn pthread_create(native: * mut pthread_t,
-                             attr: * const pthread_attr_t,
-                             f: * mut c_void,
-                             value: * mut c_void,
-                             len: c_int) -> c_int {
-    let mut result: c_int = 0;
-    let status = u_pthread_create_ocall(&mut result as * mut c_int,
-                                        native,
-                                        attr,
-                                        f,
-                                        value,
-                                        len);
-    if status != sgx_status_t::SGX_SUCCESS {
-       result = ESGX;
-    }
-    result
-}
-
-pub unsafe fn pthread_join(native: pthread_t, value: * mut * mut c_void) -> c_int {
+pub unsafe fn pipe(fds: *mut c_int) -> c_int {
     let mut result: c_int = 0;
-    let status = u_pthread_join_ocall(&mut result as * mut c_int,
-                                      native,
-                                      value);
-    if status != sgx_status_t::SGX_SUCCESS {
-       result = ESGX;
+    let mut error: c_int = 0;
+    let status = u_pipe_ocall(&mut result as *mut c_int,
+                              &mut error as *mut c_int,
+                              fds);
+    if status == sgx_status_t::SGX_SUCCESS {
+        if result == -1 {
+            set_errno(error);
+        }
+    } else {
+        set_errno(ESGX);
+        result = -1;
     }
     result
 }
 
-pub unsafe fn pthread_detach(native: pthread_t) -> c_int {
+pub unsafe fn pipe2(fds: *mut c_int, flags: c_int) -> c_int {
     let mut result: c_int = 0;
-    let status = u_pthread_detach_ocall(&mut result as * mut c_int, native);
-    if status != sgx_status_t::SGX_SUCCESS {
-       result = ESGX;
+    let mut error: c_int = 0;
+    let status = u_pipe2_ocall(&mut result as *mut c_int,
+                               &mut error as *mut c_int,
+                               fds,
+                               flags);
+    if status == sgx_status_t::SGX_SUCCESS {
+        if result == -1 {
+            set_errno(error);
+        }
+    } else {
+        set_errno(ESGX);
+        result = -1;
     }
     result
 }
@@ -2649,8 +2892,8 @@ pub unsafe fn pthread_detach(native: pthread_t) -> c_int {
 pub unsafe fn sched_yield() -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_sched_yield_ocall(&mut result as * mut c_int,
-                                     &mut error as * mut c_int);
+    let status = u_sched_yield_ocall(&mut result as *mut c_int,
+                                     &mut error as *mut c_int);
     if status == sgx_status_t::SGX_SUCCESS {
         if result == -1 {
             set_errno(error);
@@ -2662,11 +2905,11 @@ pub unsafe fn sched_yield() -> c_int {
     result
 }
 
-pub unsafe fn nanosleep(rqtp: * const timespec, rmtp: * mut timespec) -> c_int {
+pub unsafe fn nanosleep(rqtp: *const timespec, rmtp: *mut timespec) -> c_int {
     let mut result: c_int = 0;
     let mut error: c_int = 0;
-    let status = u_nanosleep_ocall(&mut result as * mut c_int,
-                                   &mut error as * mut c_int,
+    let status = u_nanosleep_ocall(&mut result as *mut c_int,
+                                   &mut error as *mut c_int,
                                    rqtp,
                                    rmtp);
     if status == sgx_status_t::SGX_SUCCESS {
diff --git a/sgx_no_tstd/Cargo.toml b/sgx_no_tstd/Cargo.toml
index ab2badb..4e41e12 100644
--- a/sgx_no_tstd/Cargo.toml
+++ b/sgx_no_tstd/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_no_tstd"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 build = "build.rs"
 repository = "https://github.com/apache/teaclave-sgx-sdk"
diff --git a/sgx_no_tstd/build.rs b/sgx_no_tstd/build.rs
index 4bdb9b3..e1f40f2 100644
--- a/sgx_no_tstd/build.rs
+++ b/sgx_no_tstd/build.rs
@@ -30,7 +30,20 @@ fn main() {
 }
 
 fn build_libunwind(host: &str, target: &str) -> Result<(), ()> {
-    let native = native_lib_boilerplate("sgx_unwind/libunwind", "libunwind", "unwind", "src/.libs")?;
+    let filter = vec![
+        "config",
+        "autom4te.cache",
+        "Makefile.in",
+        "config.h.in",
+        "configure",
+        "aclocal.m4",
+        "INSTALL"];
+    let native = native_lib_boilerplate(
+                    "sgx_unwind/libunwind",
+                    "libunwind",
+                    "unwind",
+                    "src/.libs",
+                    &filter)?;
     let cflags = env::var("CFLAGS").unwrap_or_default() + " -fvisibility=hidden -O2";
 
     run(Command::new("sh")
diff --git a/sgx_panic_unwind/lib.rs b/sgx_panic_unwind/lib.rs
index a2b9ba4..2166bb6 100644
--- a/sgx_panic_unwind/lib.rs
+++ b/sgx_panic_unwind/lib.rs
@@ -71,5 +71,5 @@ pub unsafe extern "C" fn __rust_maybe_catch_panic(f: fn(*mut u8),
 #[unwind(allowed)]
 pub unsafe extern "C" fn __rust_start_panic(payload: usize) -> u32 {
     let payload = payload as *mut &mut dyn BoxMeUp;
-    imp::panic(Box::from_raw((*payload).box_me_up()))
+    imp::panic(Box::from_raw((*payload).take_box()))
 }
diff --git a/sgx_rand/Cargo.toml b/sgx_rand/Cargo.toml
index e3fc9ec..efa52e3 100644
--- a/sgx_rand/Cargo.toml
+++ b/sgx_rand/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_rand"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_rand_derive/Cargo.toml b/sgx_rand_derive/Cargo.toml
index 568a7a4..22c6d90 100644
--- a/sgx_rand_derive/Cargo.toml
+++ b/sgx_rand_derive/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_rand_derive"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_serialize/Cargo.toml b/sgx_serialize/Cargo.toml
index 97f7e4b..7ae2120 100644
--- a/sgx_serialize/Cargo.toml
+++ b/sgx_serialize/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_serialize"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_serialize_derive/Cargo.toml b/sgx_serialize_derive/Cargo.toml
index ba84c4c..e765162 100644
--- a/sgx_serialize_derive/Cargo.toml
+++ b/sgx_serialize_derive/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_serialize_derive"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_serialize_derive_internals/Cargo.toml b/sgx_serialize_derive_internals/Cargo.toml
index c42353b..dd75733 100644
--- a/sgx_serialize_derive_internals/Cargo.toml
+++ b/sgx_serialize_derive_internals/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_serialize_derive_internals"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tcrypto/Cargo.toml b/sgx_tcrypto/Cargo.toml
index 6d66f3c..7a1363f 100644
--- a/sgx_tcrypto/Cargo.toml
+++ b/sgx_tcrypto/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tcrypto"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tcrypto/src/crypto.rs b/sgx_tcrypto/src/crypto.rs
index 9474d07..aa3403a 100644
--- a/sgx_tcrypto/src/crypto.rs
+++ b/sgx_tcrypto/src/crypto.rs
@@ -78,7 +78,7 @@ pub fn rsgx_sha256_msg<T>(src: &T) -> SgxResult<sgx_sha256_hash_t>
     }
 
     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),
@@ -100,7 +100,7 @@ pub fn rsgx_sha256_slice<T>(src: &[T]) -> SgxResult<sgx_sha256_hash_t>
     }
 
     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),
@@ -109,7 +109,7 @@ pub fn rsgx_sha256_slice<T>(src: &[T]) -> SgxResult<sgx_sha256_hash_t>
 
 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)
+        sgx_sha256_init(sha_handle as *mut sgx_sha_state_handle_t)
     }
 }
 
@@ -125,7 +125,7 @@ fn rsgx_sha256_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx
     }
 
     unsafe {
-        sgx_sha256_update(src as * const _ as * const u8, size as u32, sha_handle)
+        sgx_sha256_update(src as *const _ as *const u8, size as u32, sha_handle)
     }
 }
 
@@ -140,12 +140,12 @@ fn rsgx_sha256_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) ->
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_sha256_update(src.as_ptr() as * const u8, size as u32, sha_handle)
+        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 {
-    unsafe { sgx_sha256_get_hash(sha_handle, hash as * mut sgx_sha256_hash_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 {
@@ -164,7 +164,7 @@ pub fn rsgx_sha1_msg<T>(src: &T) -> SgxResult<sgx_sha1_hash_t>
     }
 
     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),
@@ -183,7 +183,7 @@ pub fn rsgx_sha1_slice<T>(src: &[T]) -> SgxResult<sgx_sha1_hash_t>
     }
 
     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),
@@ -192,7 +192,7 @@ pub fn rsgx_sha1_slice<T>(src: &[T]) -> SgxResult<sgx_sha1_hash_t>
 
 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)
+        sgx_sha1_init(sha_handle as *mut sgx_sha_state_handle_t)
     }
 }
 
@@ -208,7 +208,7 @@ fn rsgx_sha1_update_msg<T>(src: &T, sha_handle: sgx_sha_state_handle_t) -> sgx_s
     }
 
     unsafe {
-        sgx_sha1_update(src as * const _ as * const u8, size as u32, sha_handle)
+        sgx_sha1_update(src as *const _ as *const u8, size as u32, sha_handle)
     }
 }
 
@@ -223,12 +223,12 @@ fn rsgx_sha1_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> s
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_sha1_update(src.as_ptr() as * const u8, size as u32, sha_handle)
+        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 {
-    unsafe { sgx_sha1_get_hash(sha_handle, hash as * mut sgx_sha1_hash_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 {
@@ -698,7 +698,7 @@ pub fn rsgx_rijndael128GCM_encrypt(key: &sgx_aes_gcm_128bit_key_t,
             (ptr::null(), ptr::null_mut())
         };
 
-        sgx_rijndael128GCM_encrypt(key as * const sgx_aes_gcm_128bit_key_t,
+        sgx_rijndael128GCM_encrypt(key as *const sgx_aes_gcm_128bit_key_t,
                                    p_src,
                                    src_len as u32,
                                    p_dst,
@@ -706,7 +706,7 @@ pub fn rsgx_rijndael128GCM_encrypt(key: &sgx_aes_gcm_128bit_key_t,
                                    iv_len as u32,
                                    p_aad,
                                    aad_len as u32,
-                                   mac as * mut sgx_aes_gcm_128bit_tag_t)
+                                   mac as *mut sgx_aes_gcm_128bit_tag_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -825,7 +825,7 @@ pub fn rsgx_rijndael128GCM_decrypt(key: &sgx_aes_gcm_128bit_key_t,
             (ptr::null(), ptr::null_mut())
         };
 
-        sgx_rijndael128GCM_decrypt(key as * const sgx_aes_gcm_128bit_key_t,
+        sgx_rijndael128GCM_decrypt(key as *const sgx_aes_gcm_128bit_key_t,
                                    p_src,
                                    src_len as u32,
                                    p_dst,
@@ -833,7 +833,7 @@ pub fn rsgx_rijndael128GCM_decrypt(key: &sgx_aes_gcm_128bit_key_t,
                                    iv_len as u32,
                                    p_aad,
                                    aad_len as u32,
-                                   mac as * const sgx_aes_gcm_128bit_tag_t)
+                                   mac as *const sgx_aes_gcm_128bit_tag_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -898,10 +898,10 @@ pub fn rsgx_rijndael128_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> Sgx
 
     let mut mac = sgx_cmac_128bit_tag_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as * const sgx_cmac_128bit_key_t,
-                                 src as * const _ as * const u8,
+        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
+                                 src as *const _ as *const u8,
                                  size as u32,
-                                 &mut mac as * mut sgx_cmac_128bit_tag_t)
+                                 &mut mac as *mut sgx_cmac_128bit_tag_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(mac),
@@ -922,10 +922,10 @@ pub fn rsgx_rijndael128_align_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T)
 
     let mut align_mac = sgx_align_mac_128bit_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as * const sgx_cmac_128bit_key_t,
-                                 src as * const _ as * const u8,
+        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
+                                 src as *const _ as *const u8,
                                  size as u32,
-                                 &mut align_mac.mac as * mut sgx_cmac_128bit_tag_t)
+                                 &mut align_mac.mac as *mut sgx_cmac_128bit_tag_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_mac),
@@ -949,10 +949,10 @@ pub fn rsgx_rijndael128_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) ->
 
     let mut mac = sgx_cmac_128bit_tag_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as * const sgx_cmac_128bit_key_t,
-                                 src.as_ptr() as * const u8,
+        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
+                                 src.as_ptr() as *const u8,
                                  size as u32,
-                                 &mut mac as * mut sgx_cmac_128bit_tag_t)
+                                 &mut mac as *mut sgx_cmac_128bit_tag_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(mac),
@@ -973,10 +973,10 @@ pub fn rsgx_rijndael128_align_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[
 
     let mut align_mac = sgx_align_mac_128bit_t::default();
     let ret = unsafe {
-        sgx_rijndael128_cmac_msg(key as * const sgx_cmac_128bit_key_t,
-                                 src.as_ptr() as * const u8,
+        sgx_rijndael128_cmac_msg(key as *const sgx_cmac_128bit_key_t,
+                                 src.as_ptr() as *const u8,
                                  size as u32,
-                                 &mut align_mac.mac as * mut sgx_cmac_128bit_tag_t)
+                                 &mut align_mac.mac as *mut sgx_cmac_128bit_tag_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_mac),
@@ -986,8 +986,8 @@ pub fn rsgx_rijndael128_align_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[
 
 fn rsgx_cmac128_init(key: &sgx_cmac_128bit_key_t, cmac_handle: &mut sgx_cmac_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_cmac128_init(key as * const sgx_cmac_128bit_key_t,
-                         cmac_handle as * mut sgx_cmac_state_handle_t)
+        sgx_cmac128_init(key as *const sgx_cmac_128bit_key_t,
+                         cmac_handle as *mut sgx_cmac_state_handle_t)
     }
 }
 
@@ -1002,7 +1002,7 @@ fn rsgx_cmac128_update_msg<T>(src: &T, cmac_handle: sgx_cmac_state_handle_t) ->
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_cmac128_update(src as * const _ as * const u8, size as u32, cmac_handle)
+        sgx_cmac128_update(src as *const _ as *const u8, size as u32, cmac_handle)
     }
 }
 
@@ -1017,12 +1017,12 @@ fn rsgx_cmac128_update_slice<T>(src: &[T], cmac_handle: sgx_cmac_state_handle_t)
         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 {
-    unsafe { sgx_cmac128_final(cmac_handle, hash as * mut sgx_cmac_128bit_tag_t) }
+    unsafe { sgx_cmac128_final(cmac_handle, hash as *mut sgx_cmac_128bit_tag_t) }
 }
 
 fn rsgx_cmac128_close(cmac_handle: sgx_cmac_state_handle_t) -> sgx_status_t {
@@ -1310,11 +1310,11 @@ pub fn rsgx_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResul
 
     let mut mac = sgx_hmac_256bit_tag_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src as * const _ as * const u8,
+        sgx_hmac_sha256_msg(src as *const _ as *const u8,
                             size as i32,
-                            key as * const u8,
+                            key as *const u8,
                             SGX_HMAC256_KEY_SIZE as i32,
-                            &mut mac as * mut sgx_hmac_256bit_tag_t as * mut u8,
+                            &mut mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
                             SGX_HMAC256_MAC_SIZE as i32)
     };
     match ret {
@@ -1336,11 +1336,11 @@ pub fn rsgx_align_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> Sg
 
     let mut align_mac = sgx_align_mac_256bit_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src as * const _ as * const u8,
+        sgx_hmac_sha256_msg(src as *const _ as *const u8,
                             size as i32,
-                            key as * const u8,
+                            key as *const u8,
                             SGX_HMAC256_KEY_SIZE as i32,
-                            &mut align_mac.mac as * mut sgx_hmac_256bit_tag_t as * mut u8,
+                            &mut align_mac.mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
                             SGX_HMAC256_MAC_SIZE as i32)
     };
     match ret {
@@ -1362,11 +1362,11 @@ pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxR
 
     let mut mac = sgx_hmac_256bit_tag_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src.as_ptr() as * const u8,
+        sgx_hmac_sha256_msg(src.as_ptr() as *const u8,
                             size as i32,
-                            key as * const u8,
+                            key as *const u8,
                             SGX_HMAC256_KEY_SIZE as i32,
-                            &mut mac as * mut sgx_hmac_256bit_tag_t as * mut u8,
+                            &mut mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
                             SGX_HMAC256_MAC_SIZE as i32)
     };
     match ret {
@@ -1388,11 +1388,11 @@ pub fn rsgx_align_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -
 
     let mut align_mac = sgx_align_mac_256bit_t::default();
     let ret = unsafe {
-        sgx_hmac_sha256_msg(src.as_ptr() as * const u8,
+        sgx_hmac_sha256_msg(src.as_ptr() as *const u8,
                             size as i32,
-                            key as * const u8,
+                            key as *const u8,
                             SGX_HMAC256_KEY_SIZE as i32,
-                            &mut align_mac.mac as * mut sgx_hmac_256bit_tag_t as * mut u8,
+                            &mut align_mac.mac as *mut sgx_hmac_256bit_tag_t as *mut u8,
                             SGX_HMAC256_MAC_SIZE as i32)
     };
     match ret {
@@ -1403,9 +1403,9 @@ pub fn rsgx_align_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -
 
 fn rsgx_hmac256_init(key: &sgx_hmac_256bit_key_t, hmac_handle: &mut sgx_hmac_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_hmac256_init(key as * const sgx_hmac_256bit_key_t as * const u8,
+        sgx_hmac256_init(key as *const sgx_hmac_256bit_key_t as *const u8,
                          SGX_HMAC256_KEY_SIZE as i32,
-                         hmac_handle as * mut sgx_hmac_state_handle_t)
+                         hmac_handle as *mut sgx_hmac_state_handle_t)
     }
 }
 
@@ -1420,7 +1420,7 @@ fn rsgx_hmac256_update_msg<T>(src: &T, hmac_handle: sgx_hmac_state_handle_t) ->
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     unsafe {
-        sgx_hmac256_update(src as * const _ as * const u8, size as i32, hmac_handle)
+        sgx_hmac256_update(src as *const _ as *const u8, size as i32, hmac_handle)
     }
 }
 
@@ -1435,13 +1435,13 @@ fn rsgx_hmac256_update_slice<T>(src: &[T], hmac_handle: sgx_hmac_state_handle_t)
         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 {
     unsafe {
-        sgx_hmac256_final(hash as * mut sgx_hmac_256bit_tag_t as * mut u8,
+        sgx_hmac256_final(hash as *mut sgx_hmac_256bit_tag_t as *mut u8,
                           SGX_HMAC256_MAC_SIZE as i32,
                           hmac_handle)
     }
@@ -1654,10 +1654,10 @@ pub fn rsgx_aes_ctr_encrypt(key: &sgx_aes_ctr_128bit_key_t,
     }
 
     let ret = unsafe {
-        sgx_aes_ctr_encrypt(key as * const sgx_aes_ctr_128bit_key_t,
+        sgx_aes_ctr_encrypt(key as *const sgx_aes_ctr_128bit_key_t,
                             src.as_ptr(),
                             src_len as u32,
-                            ctr as * const sgx_aes_ctr_128bit_ctr_t as * const u8,
+                            ctr as *const sgx_aes_ctr_128bit_ctr_t as *const u8,
                             ctr_inc_bits,
                             dst.as_mut_ptr())
     };
@@ -1747,10 +1747,10 @@ pub fn rsgx_aes_ctr_decrypt(key: &sgx_aes_ctr_128bit_key_t,
     }
 
     let ret = unsafe {
-        sgx_aes_ctr_decrypt(key as * const sgx_aes_ctr_128bit_key_t,
+        sgx_aes_ctr_decrypt(key as *const sgx_aes_ctr_128bit_key_t,
                             src.as_ptr(),
                             src.len() as u32,
-                            ctr as * const sgx_aes_ctr_128bit_ctr_t as * const u8,
+                            ctr as *const sgx_aes_ctr_128bit_ctr_t as *const u8,
                             ctr_inc_bits,
                             dst.as_mut_ptr())
     };
@@ -1761,7 +1761,7 @@ pub fn rsgx_aes_ctr_decrypt(key: &sgx_aes_ctr_128bit_key_t,
 }
 
 fn rsgx_ecc256_open_context(ecc_handle: &mut sgx_ecc_state_handle_t) -> sgx_status_t {
-    unsafe { sgx_ecc256_open_context(ecc_handle as * mut _ as * mut sgx_ecc_state_handle_t) }
+    unsafe { sgx_ecc256_open_context(ecc_handle as *mut _ as *mut sgx_ecc_state_handle_t) }
 }
 
 fn rsgx_ecc256_close_context(ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
@@ -1772,14 +1772,14 @@ fn rsgx_ecc256_create_key_pair(private: &mut sgx_ec256_private_t,
                                public: &mut sgx_ec256_public_t,
                                ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_ecc256_create_key_pair(private as * mut sgx_ec256_private_t,
-                                   public as * mut sgx_ec256_public_t,
+        sgx_ecc256_create_key_pair(private as *mut sgx_ec256_private_t,
+                                   public as *mut sgx_ec256_public_t,
                                    ecc_handle)
     }
 }
 
 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) }
+    unsafe { sgx_ecc256_check_point(point as *const sgx_ec256_public_t, ecc_handle, valid as *mut i32) }
 }
 
 fn rsgx_ecc256_compute_shared_dhkey(private_b: &sgx_ec256_private_t,
@@ -1787,9 +1787,9 @@ fn rsgx_ecc256_compute_shared_dhkey(private_b: &sgx_ec256_private_t,
                                     shared_key: &mut sgx_ec256_dh_shared_t,
                                     ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_ecc256_compute_shared_dhkey(private_b as * const _ as * mut sgx_ec256_private_t,
-                                        public_ga as * const _ as * mut sgx_ec256_public_t,
-                                        shared_key as * mut sgx_ec256_dh_shared_t,
+        sgx_ecc256_compute_shared_dhkey(private_b as *const _ as *mut sgx_ec256_private_t,
+                                        public_ga as *const _ as *mut sgx_ec256_public_t,
+                                        shared_key as *mut sgx_ec256_dh_shared_t,
                                         ecc_handle)
     }
 }
@@ -1800,9 +1800,9 @@ fn rsgx_ecc256_compute_shared_dhkey512(private_b: &sgx_ec256_private_t,
                                        shared_key: &mut sgx_ec256_dh_shared512_t,
                                        ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_ecc256_compute_shared_dhkey512(private_b as * const _ as * mut sgx_ec256_private_t,
-                                           public_ga as * const _ as * mut sgx_ec256_public_t,
-                                           shared_key as * mut sgx_ec256_dh_shared512_t,
+        sgx_ecc256_compute_shared_dhkey512(private_b as *const _ as *mut sgx_ec256_private_t,
+                                           public_ga as *const _ as *mut sgx_ec256_public_t,
+                                           shared_key as *mut sgx_ec256_dh_shared512_t,
                                            ecc_handle)
     }
 }
@@ -1823,10 +1823,10 @@ fn rsgx_ecdsa_sign_msg<T>(data: &T,
     }
 
     unsafe {
-        sgx_ecdsa_sign(data as * const _  as * const u8,
+        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,
+                       private as *const _ as *mut sgx_ec256_private_t,
+                       signature as *mut sgx_ec256_signature_t,
                        ecc_handle)
     }
 }
@@ -1846,10 +1846,10 @@ fn rsgx_ecdsa_sign_slice<T>(data: &[T],
     }
 
     unsafe {
-        sgx_ecdsa_sign(data.as_ptr() as * const _  as * const u8,
+        sgx_ecdsa_sign(data.as_ptr() as *const _  as *const u8,
                        size as u32,
-                       private as * const _ as * mut sgx_ec256_private_t,
-                       signature as * mut sgx_ec256_signature_t,
+                       private as *const _ as *mut sgx_ec256_private_t,
+                       signature as *mut sgx_ec256_signature_t,
                        ecc_handle)
     }
 }
@@ -1871,11 +1871,11 @@ fn rsgx_ecdsa_verify_msg<T>(data: &T,
 
     unsafe {
         let mut verify: u8 = 0;
-        let ret = sgx_ecdsa_verify(data as * const _ as * const u8,
+        let ret = sgx_ecdsa_verify(data as *const _ as *const u8,
                                    size as u32,
-                                   public as * const sgx_ec256_public_t,
-                                   signature as * const _ as * mut sgx_ec256_signature_t,
-                                   &mut verify as * mut u8,
+                                   public as *const sgx_ec256_public_t,
+                                   signature as *const _ as *mut sgx_ec256_signature_t,
+                                   &mut verify as *mut u8,
                                    ecc_handle);
         match ret {
             sgx_status_t::SGX_SUCCESS => {
@@ -1905,11 +1905,11 @@ fn rsgx_ecdsa_verify_slice<T>(data: &[T],
 
     unsafe {
         let mut verify: u8 = 0;
-        let ret = sgx_ecdsa_verify(data.as_ptr() as * const _ as * const u8,
+        let ret = sgx_ecdsa_verify(data.as_ptr() as *const _ as *const u8,
                                    size as u32,
-                                   public as * const sgx_ec256_public_t,
-                                   signature as * const _ as * mut sgx_ec256_signature_t,
-                                   &mut verify as * mut u8,
+                                   public as *const sgx_ec256_public_t,
+                                   signature as *const _ as *mut sgx_ec256_signature_t,
+                                   &mut verify as *mut u8,
                                    ecc_handle);
         match ret {
             sgx_status_t::SGX_SUCCESS => {
@@ -1929,10 +1929,10 @@ fn rsgx_ecdsa_verify_hash(hash: &sgx_sha256_hash_t,
                           ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
     unsafe {
         let mut verify: u8 = 0;
-        let ret = sgx_ecdsa_verify_hash(hash as * const sgx_sha256_hash_t as * const u8,
-                                        public as * const sgx_ec256_public_t,
-                                        signature as * const _ as * mut sgx_ec256_signature_t,
-                                        &mut verify as * mut u8,
+        let ret = sgx_ecdsa_verify_hash(hash as *const sgx_sha256_hash_t as *const u8,
+                                        public as *const sgx_ec256_public_t,
+                                        signature as *const _ as *mut sgx_ec256_signature_t,
+                                        &mut verify as *mut u8,
                                         ecc_handle);
         match ret {
             sgx_status_t::SGX_SUCCESS => {
@@ -2664,10 +2664,10 @@ pub fn rsgx_rsa3072_sign_msg<T>(data: &T, key: &sgx_rsa3072_key_t) -> SgxResult<
 
     let mut sign = sgx_rsa3072_signature_t::default();
     let ret = unsafe {
-        sgx_rsa3072_sign(data as * const _ as * const u8,
+        sgx_rsa3072_sign(data as *const _ as *const u8,
                          size as u32,
-                         key as * const sgx_rsa3072_key_t,
-                         &mut sign as * mut sgx_rsa3072_signature_t)
+                         key as *const sgx_rsa3072_key_t,
+                         &mut sign as *mut sgx_rsa3072_signature_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(sign),
@@ -2691,10 +2691,10 @@ pub fn rsgx_rsa3072_sign_slice<T>(data: &[T], key: &sgx_rsa3072_key_t) -> SgxRes
 
     let mut sign = sgx_rsa3072_signature_t::default();
     let ret = unsafe {
-        sgx_rsa3072_sign(data.as_ptr() as * const _ as * const u8,
+        sgx_rsa3072_sign(data.as_ptr() as *const _ as *const u8,
                          size as u32,
-                         key as * const sgx_rsa3072_key_t,
-                         &mut sign as * mut sgx_rsa3072_signature_t)
+                         key as *const sgx_rsa3072_key_t,
+                         &mut sign as *mut sgx_rsa3072_signature_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(sign),
@@ -2770,11 +2770,11 @@ pub fn rsgx_rsa3072_verify_msg<T>(data: &T,
     unsafe {
 
         let mut verify = sgx_rsa_result_t::SGX_RSA_INVALID_SIGNATURE;
-        let ret = sgx_rsa3072_verify(data as * const _ as * const u8,
+        let ret = sgx_rsa3072_verify(data as *const _ as *const u8,
                                      size as u32,
-                                     public as * const sgx_rsa3072_public_key_t,
-                                     signature as * const sgx_rsa3072_signature_t,
-                                     &mut verify as * mut sgx_rsa_result_t);
+                                     public as *const sgx_rsa3072_public_key_t,
+                                     signature as *const sgx_rsa3072_signature_t,
+                                     &mut verify as *mut sgx_rsa_result_t);
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 match verify {
@@ -2806,11 +2806,11 @@ pub fn rsgx_rsa3072_verify_slice<T>(data: &[T],
     unsafe {
 
         let mut verify = sgx_rsa_result_t::SGX_RSA_INVALID_SIGNATURE;
-        let ret = sgx_rsa3072_verify(data.as_ptr() as * const _ as * const u8,
+        let ret = sgx_rsa3072_verify(data.as_ptr() as *const _ as *const u8,
                                      size as u32,
-                                     public as * const sgx_rsa3072_public_key_t,
-                                     signature as * const sgx_rsa3072_signature_t,
-                                     &mut verify as * mut sgx_rsa_result_t);
+                                     public as *const sgx_rsa3072_public_key_t,
+                                     signature as *const sgx_rsa3072_signature_t,
+                                     &mut verify as *mut sgx_rsa_result_t);
         match ret {
             sgx_status_t::SGX_SUCCESS => {
                 match verify {
@@ -2920,7 +2920,7 @@ fn rsgx_create_rsa_priv2_key(mod_size: i32,
                                  dmp1.as_ptr(),
                                  dmq1.as_ptr(),
                                  iqmp.as_ptr(),
-                                 new_pri_key as * mut sgx_rsa_key_t)
+                                 new_pri_key as *mut sgx_rsa_key_t)
     }
 }
 
@@ -2951,7 +2951,7 @@ fn rsgx_create_rsa_priv1_key(n_size: i32,
                                  n.as_ptr(),
                                  e.as_ptr(),
                                  d.as_ptr(),
-                                 new_pri_key as * mut sgx_rsa_key_t)
+                                 new_pri_key as *mut sgx_rsa_key_t)
     }
 }
 
@@ -2975,7 +2975,7 @@ fn rsgx_create_rsa_pub1_key(mod_size: i32,
                                 exp_size,
                                 n.as_ptr(),
                                 e.as_ptr(),
-                                new_pub_key as * mut sgx_rsa_key_t)
+                                new_pub_key as *mut sgx_rsa_key_t)
     }
 }
 
@@ -3004,7 +3004,7 @@ fn rsgx_rsa_priv_decrypt_sha256(rsa_key: sgx_rsa_key_t,
     }
 
     unsafe {
-        let p_out_data: * mut u8 = if *out_len != 0 {
+        let p_out_data: *mut u8 = if *out_len != 0 {
             out_data.as_mut_ptr()
         } else {
             ptr::null_mut()
@@ -3012,7 +3012,7 @@ fn rsgx_rsa_priv_decrypt_sha256(rsa_key: sgx_rsa_key_t,
 
         sgx_rsa_priv_decrypt_sha256(rsa_key,
                                     p_out_data,
-                                    out_len as * mut usize,
+                                    out_len as *mut usize,
                                     in_data.as_ptr(),
                                     in_data.len())
     }
@@ -3030,7 +3030,7 @@ fn rsgx_rsa_pub_encrypt_sha256(rsa_key: sgx_rsa_key_t,
     }
 
     unsafe {
-        let p_out_data: * mut u8 = if *out_len != 0 {
+        let p_out_data: *mut u8 = if *out_len != 0 {
             out_data.as_mut_ptr()
         } else {
             ptr::null_mut()
@@ -3038,7 +3038,7 @@ fn rsgx_rsa_pub_encrypt_sha256(rsa_key: sgx_rsa_key_t,
 
         sgx_rsa_pub_encrypt_sha256(rsa_key,
                                    p_out_data,
-                                   out_len as * mut usize,
+                                   out_len as *mut usize,
                                    in_data.as_ptr(),
                                    in_data.len())
     }
@@ -3365,8 +3365,8 @@ pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
 pub fn rsgx_ecc256_calculate_pub_from_priv(priv_key: &sgx_ec256_private_t,
                                            pub_key: &mut sgx_ec256_public_t) -> SgxError {
     let ret = unsafe {
-        sgx_ecc256_calculate_pub_from_priv(priv_key as * const sgx_ec256_private_t,
-                                           pub_key as * mut sgx_ec256_public_t)
+        sgx_ecc256_calculate_pub_from_priv(priv_key as *const sgx_ec256_private_t,
+                                           pub_key as *mut sgx_ec256_public_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -3388,7 +3388,7 @@ pub fn rsgx_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxRes
                                      hash_drg.len() as i32,
                                      sgx_nistp256_r_m1.as_ptr(),
                                      sgx_nistp256_r_m1.len() as i32,
-                                     &mut priv_key as * mut sgx_ec256_private_t as * mut u8,
+                                     &mut priv_key as *mut sgx_ec256_private_t as *mut u8,
                                      mem::size_of::<sgx_ec256_private_t>() as i32)
     };
     match ret {
@@ -3411,7 +3411,7 @@ pub fn rsgx_align_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) ->
                                      hash_drg.len() as i32,
                                      sgx_nistp256_r_m1.as_ptr(),
                                      sgx_nistp256_r_m1.len() as i32,
-                                     &mut align_priv_key.key as * mut sgx_ec256_private_t as * mut u8,
+                                     &mut align_priv_key.key as *mut sgx_ec256_private_t as *mut u8,
                                      mem::size_of::<sgx_ec256_private_t>() as i32)
     };
     match ret {
@@ -3423,8 +3423,8 @@ pub fn rsgx_align_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) ->
 pub fn rsgx_ecc256_pub_from_priv(priv_key: &sgx_ec256_private_t) -> SgxResult<sgx_ec256_public_t> {
     let mut pub_key = sgx_ec256_public_t::default();
     let ret = unsafe {
-        sgx_ecc256_calculate_pub_from_priv(priv_key as * const sgx_ec256_private_t,
-                                           &mut pub_key as * mut sgx_ec256_public_t)
+        sgx_ecc256_calculate_pub_from_priv(priv_key as *const sgx_ec256_private_t,
+                                           &mut pub_key as *mut sgx_ec256_public_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(pub_key),
@@ -3447,12 +3447,12 @@ fn rsgx_aes_gcm128_enc_init(key: &sgx_aes_gcm_128bit_key_t,
 
     unsafe {
         let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
-        sgx_aes_gcm128_enc_init(key as * const sgx_aes_gcm_128bit_key_t as * const u8,
+        sgx_aes_gcm128_enc_init(key as *const sgx_aes_gcm_128bit_key_t as *const u8,
                                 iv.as_ptr(),
                                 iv_len as u32,
                                 p_aad,
                                 aad_len as u32,
-                                aes_gcm_state as * mut sgx_aes_state_handle_t)
+                                aes_gcm_state as *mut sgx_aes_state_handle_t)
     }
 }
 
@@ -3485,7 +3485,7 @@ fn rsgx_aes_gcm128_enc_update(src: &[u8],
 fn rsgx_aes_gcm128_enc_get_mac(mac: &mut sgx_aes_gcm_128bit_tag_t,
                                aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
     unsafe {
-        sgx_aes_gcm128_enc_get_mac(mac as * mut sgx_aes_gcm_128bit_tag_t as * mut u8, aes_gcm_state)
+        sgx_aes_gcm128_enc_get_mac(mac as *mut sgx_aes_gcm_128bit_tag_t as *mut u8, aes_gcm_state)
     }
 }
 
diff --git a/sgx_tcrypto_helper/Cargo.toml b/sgx_tcrypto_helper/Cargo.toml
index c7fba70..2e3f71a 100644
--- a/sgx_tcrypto_helper/Cargo.toml
+++ b/sgx_tcrypto_helper/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tcrypto_helper"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
@@ -16,43 +16,5 @@ crate-type = ["staticlib","rlib"]
 default = ["mesalock_sgx"]
 mesalock_sgx = []
 
-[target.'cfg(not(target_env = "sgx"))'.dependencies]
-sgx_tcrypto = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
-sgx_tstd    = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
-sgx_types   = { rev = "v1.1.0", git = "https://github.com/apache/teaclave-sgx-sdk.git" }
-
 [dependencies]
-serde = { git = "https://github.com/mesalock-linux/serde-sgx" }
-serde_derive = { git = "https://github.com/mesalock-linux/serde-sgx" }
-itertools = { version = "*", default-features = false }
-serde-big-array = { git = "https://github.com/mesalock-linux/serde-big-array-sgx" }
-
-[patch.'https://github.com/apache/teaclave-sgx-sdk.git']
-sgx_alloc = { path = "../sgx_alloc" }
-sgx_backtrace = { path = "../sgx_backtrace" }
-sgx_backtrace_sys = { path = "../sgx_backtrace_sys" }
-sgx_build_helper = { path = "../sgx_build_helper" }
-sgx_cov = { path = "../sgx_cov" }
-sgx_crypto_helper = { path = "../sgx_crypto_helper" }
-sgx_demangle = { path = "../sgx_demangle" }
-sgx_libc = { path = "../sgx_libc" }
-sgx_rand = { path = "../sgx_rand" }
-sgx_rand_derive = { path = "../sgx_rand_derive" }
-sgx_serialize = { path = "../sgx_serialize" }
-sgx_serialize_derive = { path = "../sgx_serialize_derive" }
-sgx_serialize_derive_internals = { path = "../sgx_serialize_derive_internals" }
-sgx_tcrypto = { path = "../sgx_tcrypto" }
-sgx_tcrypto_helper = { path = "../sgx_tcrypto_helper" }
-sgx_tdh = { path = "../sgx_tdh" }
-sgx_tkey_exchange = { path = "../sgx_tkey_exchange" }
-sgx_tprotected_fs = { path = "../sgx_tprotected_fs" }
-sgx_trts = { path = "../sgx_trts" }
-sgx_tse = { path = "../sgx_tse" }
-sgx_tseal = { path = "../sgx_tseal" }
-sgx_tservice = { path = "../sgx_tservice" }
-sgx_tstd = { path = "../sgx_tstd" }
-sgx_tunittest = { path = "../sgx_tunittest" }
-sgx_types = { path = "../sgx_types" }
-#sgx_ucrypto = { path = "../sgx_ucrypto" }
-sgx_unwind = { path = "../sgx_unwind" }
-#sgx_urts = { path = "../sgx_urts" }
+sgx_crypto_helper = { path = "../sgx_crypto_helper", default-features = false, features = ["mesalock_sgx"] }
diff --git a/sgx_tcrypto_helper/src/lib.rs b/sgx_tcrypto_helper/src/lib.rs
index 43d22f5..aff4f3b 100644
--- a/sgx_tcrypto_helper/src/lib.rs
+++ b/sgx_tcrypto_helper/src/lib.rs
@@ -27,51 +27,7 @@
 //! other trusted libraries included in the SDK.
 //!
 
-#![allow(non_camel_case_types)]
-#![allow(non_snake_case)]
-#![allow(clippy::too_many_arguments)]
-
 #![cfg_attr(all(feature = "mesalock_sgx", not(target_env = "sgx")), no_std)]
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
-#![cfg_attr(test, feature(test))]
-
-#[cfg(all(feature = "mesalock_sgx", not(target_env = "sgx")))]
-#[macro_use]
-extern crate sgx_tstd as std;
-
-extern crate sgx_types;
-#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
-extern crate sgx_tcrypto as crypto;
-#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
-extern crate sgx_ucrypto as crypto;
-
-use std::prelude::v1::*;
-use sgx_types::SgxResult;
-use crypto::SgxRsaPrivKey;
-use crypto::SgxRsaPubKey;
-
-/// A trait to express the ability to create a RSA keypair with default e
-/// (65537) or customized e, and to_privkey/to_pubkey, encryption/decryption API.
-pub trait RsaKeyPair {
-    /// Create a new RSA keypair with default e = 65537.
-    fn new() -> SgxResult<Self> where Self: std::marker::Sized;
-    /// Create a new RSA keypair with customized e
-    fn new_with_e(e: u32) -> SgxResult<Self> where Self: std::marker::Sized;
-    /// Get a private key instance typed `SgxRsaPrivKey` which is defined in sgx_tcrypto/sgx_ucrypto.
-    fn to_privkey(self) -> SgxResult<SgxRsaPrivKey>;
-    /// get a public key instance typed `SgxPubPrivKey` which is defined in sgx_tcrypto/sgx_ucrypto.
-    fn to_pubkey(self) -> SgxResult<SgxRsaPubKey>;
-    /// Encrypt a u8 slice to a Vec<u8>. Returns the length of ciphertext if OK.
-    fn encrypt_buffer(self, plaintext: &[u8], ciphertext: &mut Vec<u8>) -> SgxResult<usize>;
-    /// Decrypt a u8 slice to a Vec<u8>. Returns the length of plaintext if OK.
-    fn decrypt_buffer(self, ciphertext: &[u8], plaintext: &mut Vec<u8>) -> SgxResult<usize>;
-}
-
-extern crate serde;
-extern crate serde_derive;
-extern crate itertools;
-#[macro_use]
-extern crate serde_big_array;
 
-pub mod rsa2048;
-pub mod rsa3072;
+pub use sgx_crypto_helper::*;
\ No newline at end of file
diff --git a/sgx_tcrypto_helper/src/rsa2048.rs b/sgx_tcrypto_helper/src/rsa2048.rs
deleted file mode 100644
index 0a5223f..0000000
--- a/sgx_tcrypto_helper/src/rsa2048.rs
+++ /dev/null
@@ -1,472 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License..
-
-//! # Cryptography Library Helper
-//!
-//! This crate provides helper functions to simplify key distribution and
-//! encryption/decryption. It utilizes sgx_tcrypto to provide
-//! a interface to enclave app. It provides key
-//! serialization/deserialization by serde.
-//!
-
-use crypto::rsgx_create_rsa_key_pair;
-use crypto::{SgxRsaPrivKey, SgxRsaPubKey};
-use itertools::Itertools;
-use sgx_types::{sgx_status_t, size_t, SgxResult};
-pub const SGX_RSA2048_KEY_SIZE: size_t     = 256;
-pub const SGX_RSA2048_PRI_EXP_SIZE: size_t = 256;
-pub const SGX_RSA2048_PUB_EXP_SIZE: size_t = 4;
-pub const SGX_RSA2048_DEFAULT_E: [u8;SGX_RSA2048_PUB_EXP_SIZE]    = [0x01, 0x00, 0x00, 0x01]; // 65537
-use std::fmt;
-
-use std::prelude::v1::*;
-use crate::RsaKeyPair;
-use serde_derive::*;
-
-big_array! { BigArray; }
-
-/// Data structure of RSA 2048 Keypair (RSA-OAEP).
-/// RSA 2048 Keypair provides block cipher encryption/decryption
-/// implementations. The block size of plain text is 190 bytes
-/// and the block size of cipher text is 256 bytes.
-/// 190 byte = 2048bit - 2*SHA256_BYTE - 2
-#[derive(Serialize, Deserialize, Clone, Copy)]
-pub struct Rsa2048KeyPair {
-    #[serde(with = "BigArray")]
-    n: [u8; SGX_RSA2048_KEY_SIZE],
-    #[serde(with = "BigArray")]
-    d: [u8; SGX_RSA2048_PRI_EXP_SIZE],
-    e: [u8; SGX_RSA2048_PUB_EXP_SIZE],
-    #[serde(with = "BigArray")]
-    p: [u8; SGX_RSA2048_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    q: [u8; SGX_RSA2048_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    dmp1: [u8; SGX_RSA2048_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    dmq1: [u8; SGX_RSA2048_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    iqmp: [u8; SGX_RSA2048_KEY_SIZE / 2],
-}
-
-impl Default for Rsa2048KeyPair {
-    fn default() -> Self {
-        Rsa2048KeyPair {
-            n: [0; SGX_RSA2048_KEY_SIZE],
-            d: [0; SGX_RSA2048_PRI_EXP_SIZE],
-            e: SGX_RSA2048_DEFAULT_E,
-            p: [0; SGX_RSA2048_KEY_SIZE / 2],
-            q: [0; SGX_RSA2048_KEY_SIZE / 2],
-            dmp1: [0; SGX_RSA2048_KEY_SIZE / 2],
-            dmq1: [0; SGX_RSA2048_KEY_SIZE / 2],
-            iqmp: [0; SGX_RSA2048_KEY_SIZE / 2],
-        }
-    }
-}
-
-impl fmt::Debug for Rsa2048KeyPair {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, r#"Rsa2048KeyPair: {{ n:{:02X}, d:{:02X}, e:{:02X}, p:{:02X}, q:{:02X}, dmp1:{:02X}, dmq:{:02X}, iqmp:{:02X} }}"#,
-            self.n.iter().format(""),
-            self.d.iter().format(""),
-            self.e.iter().format(""),
-            self.p.iter().format(""),
-            self.q.iter().format(""),
-            self.dmp1.iter().format(""),
-            self.dmq1.iter().format(""),
-            self.iqmp.iter().format(""))
-    }
-}
-
-impl RsaKeyPair for Rsa2048KeyPair {
-    fn new() -> SgxResult<Self> {
-        let mut newkey = Self::default();
-        match rsgx_create_rsa_key_pair(
-            SGX_RSA2048_KEY_SIZE as i32,
-            SGX_RSA2048_PUB_EXP_SIZE as i32,
-            &mut newkey.n,
-            &mut newkey.d,
-            &mut newkey.e,
-            &mut newkey.p,
-            &mut newkey.q,
-            &mut newkey.dmp1,
-            &mut newkey.dmq1,
-            &mut newkey.iqmp,
-        ) {
-            Ok(()) => Ok(newkey),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn new_with_e(e: u32) -> SgxResult<Self> {
-        let mut newkey = Self::default();
-        newkey.e = e.to_le_bytes();
-        match rsgx_create_rsa_key_pair(
-            SGX_RSA2048_KEY_SIZE as i32,
-            SGX_RSA2048_PUB_EXP_SIZE as i32,
-            &mut newkey.n,
-            &mut newkey.d,
-            &mut newkey.e,
-            &mut newkey.p,
-            &mut newkey.q,
-            &mut newkey.dmp1,
-            &mut newkey.dmq1,
-            &mut newkey.iqmp,
-        ) {
-            Ok(()) => Ok(newkey),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn to_privkey(self) -> SgxResult<SgxRsaPrivKey> {
-        let result = SgxRsaPrivKey::new();
-        match result.create(
-            SGX_RSA2048_KEY_SIZE as i32,
-            SGX_RSA2048_PRI_EXP_SIZE as i32,
-            &self.e,
-            &self.p,
-            &self.q,
-            &self.dmp1,
-            &self.dmq1,
-            &self.iqmp,
-        ) {
-            Ok(()) => Ok(result),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn to_pubkey(self) -> SgxResult<SgxRsaPubKey> {
-        let result = SgxRsaPubKey::new();
-        match result.create(
-            SGX_RSA2048_KEY_SIZE as i32,
-            SGX_RSA2048_PUB_EXP_SIZE as i32,
-            &self.n,
-            &self.e,
-        ) {
-            Ok(()) => Ok(result),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn encrypt_buffer(self, plaintext: &[u8], ciphertext: &mut Vec<u8>) -> SgxResult<usize> {
-        let pubkey = self.to_pubkey()?;
-        let bs = 256;
-
-        // The magic number 190 comes from RSA-OAEP:
-        // #define RSA_2048_KEY_BYTE    256
-        // #define SHA_SIZE_BIT         256
-        // #define RSAOAEP_ENCRYPT_MAXLEN RSA_2048_KEY_BYTE - 2*SHA_SIZE_BIT/8 - 2 /* 190 */
-        // RSA_2048_KEY_BYTE - 2*SHA_SIZE_BIT/8 - 2
-        let bs_plain = bs - 2 * 256 / 8 - 2;
-        let count = (plaintext.len() + bs_plain - 1) / bs_plain;
-        ciphertext.resize(bs * count, 0);
-
-        for i in 0..count {
-            let cipher_slice = &mut ciphertext[i * bs..i * bs + bs];
-            let mut out_len = bs;
-            let plain_slice =
-                &plaintext[i * bs_plain..std::cmp::min(i * bs_plain + bs_plain, plaintext.len())];
-
-            pubkey.encrypt_sha256(cipher_slice, &mut out_len, plain_slice)?;
-        }
-
-        Ok(ciphertext.len())
-    }
-
-    fn decrypt_buffer(self, ciphertext: &[u8], plaintext: &mut Vec<u8>) -> SgxResult<usize> {
-        let privkey = self.to_privkey()?;
-        let bs = 256;
-        if ciphertext.len() % bs != 0 {
-            return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
-        }
-        // The magic number 190 comes from RSA-OAEP:
-        // #define RSA_2048_KEY_BYTE    256
-        // #define SHA_SIZE_BIT         256
-        // #define RSAOAEP_ENCRYPT_MAXLEN RSA_2048_KEY_BYTE - 2*SHA_SIZE_BIT/8 - 2 /* 190 */
-        // RSA_2048_KEY_BYTE - 2*SHA_SIZE_BIT/8 - 2
-        //let bs_plain = 256 - 2 * 256 / 8 - 2;
-        let bs_plain = bs;
-        let count = ciphertext.len() / bs;
-        plaintext.clear();
-
-        for i in 0..count {
-            let cipher_slice = &ciphertext[i * bs..i * bs + bs];
-            let plain_slice = &mut vec![0;bs_plain];
-            let mut plain_len = bs_plain;
-
-            privkey.decrypt_sha256(plain_slice, &mut plain_len, cipher_slice)?;
-            let mut decoded_vec = plain_slice[..plain_len].to_vec();
-            plaintext.append(&mut decoded_vec);
-        }
-
-        Ok(plaintext.len())
-    }
-
-}
-
-impl Rsa2048KeyPair {
-    pub fn export_pubkey(self) -> SgxResult<Rsa2048PubKey> {
-        Ok(Rsa2048PubKey {
-            n: self.n,
-            e: self.e,
-        })
-    }
-}
-
-#[derive(Serialize, Deserialize, Clone, Copy)]
-pub struct Rsa2048PubKey {
-    #[serde(with = "BigArray")]
-    n: [u8; SGX_RSA2048_KEY_SIZE],
-    e: [u8; SGX_RSA2048_PUB_EXP_SIZE],
-}
-
-impl Default for Rsa2048PubKey {
-    fn default() -> Self {
-        Rsa2048PubKey {
-            n: [0; SGX_RSA2048_KEY_SIZE],
-            e: SGX_RSA2048_DEFAULT_E,
-        }
-    }
-}
-
-impl Rsa2048PubKey {
-    pub fn to_pubkey(self) -> SgxResult<SgxRsaPubKey> {
-        let result = SgxRsaPubKey::new();
-        match result.create(
-            SGX_RSA2048_KEY_SIZE as i32,
-            SGX_RSA2048_PUB_EXP_SIZE as i32,
-            &self.n,
-            &self.e,
-        ) {
-            Ok(()) => Ok(result),
-            Err(x) => Err(x),
-        }
-    }
-
-    pub fn encrypt_buffer(self, plaintext: &[u8], ciphertext: &mut Vec<u8>) -> SgxResult<usize> {
-        let pubkey = self.to_pubkey()?;
-        let bs = 256;
-
-        // The magic number 190 comes from RSA-OAEP:
-        // #define RSA_2048_KEY_BYTE    256
-        // #define SHA_SIZE_BIT         256
-        // #define RSAOAEP_ENCRYPT_MAXLEN RSA_2048_KEY_BYTE - 2*SHA_SIZE_BIT/8 - 2 /* 190 */
-        // RSA_2048_KEY_BYTE - 2*SHA_SIZE_BIT/8 - 2
-        let bs_plain = bs - 2 * 256 / 8 - 2;
-        let count = (plaintext.len() + bs_plain - 1) / bs_plain;
-        ciphertext.resize(bs * count, 0);
-
-        for i in 0..count {
-            let cipher_slice = &mut ciphertext[i * bs..i * bs + bs];
-            let mut out_len = bs;
-            let plain_slice =
-                &plaintext[i * bs_plain..std::cmp::min(i * bs_plain + bs_plain, plaintext.len())];
-
-            pubkey.encrypt_sha256(cipher_slice, &mut out_len, plain_slice)?;
-        }
-
-        Ok(ciphertext.len())
-    }
-}
-
-impl fmt::Debug for Rsa2048PubKey {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, r#"Rsa2048KeyPair: {{ n:{:02X}, e:{:02X} }}"#,
-            self.n.iter().format(""),
-            self.e.iter().format(""))
-    }
-}
-
-
-#[cfg(test)]
-mod tests {
-    extern crate rdrand;
-    extern crate rand_core;
-    extern crate test;
-
-    use self::rdrand::RdRand;
-    use self::rand_core::RngCore;
-    use crate::RsaKeyPair;
-    use crate::rsa2048::Rsa2048KeyPair;
-    use crate::rsa2048::Rsa2048PubKey;
-    use crate::rsa2048::SgxRsaPrivKey;
-    use crate::rsa2048::SgxRsaPubKey;
-    use crypto::rsgx_create_rsa_key_pair;
-    use sgx_types::sgx_status_t;
-    use self::test::Bencher;
-
-    #[test]
-    fn rsa2048_new() {
-        let keypair = Rsa2048KeyPair::new();
-        assert!(keypair.is_ok());
-        let keypair = Rsa2048KeyPair::new_with_e(3);
-        assert!(keypair.is_ok());
-        let keypair = Rsa2048KeyPair::new_with_e(65537);
-        assert!(keypair.is_ok());
-    }
-
-    #[test]
-    fn rsa2048_new_fail() {
-        let keypair = Rsa2048KeyPair::new_with_e(4);
-        assert_eq!(keypair.unwrap_err(), sgx_status_t::SGX_ERROR_UNEXPECTED);
-        let keypair = Rsa2048KeyPair::new_with_e(65536);
-        assert_eq!(keypair.unwrap_err(), sgx_status_t::SGX_ERROR_UNEXPECTED); }
-
-    #[test]
-    fn rsa2048_to_sgx_rsa_pub_key() {
-        let keypair = Rsa2048KeyPair::default();
-        assert!(keypair.to_pubkey().is_err());
-        let keypair = Rsa2048KeyPair::new().unwrap();
-        assert!(keypair.to_pubkey().is_ok());
-        let keypair = Rsa2048KeyPair::new_with_e(3).unwrap();
-        assert!(keypair.to_pubkey().is_ok());
-        let keypair = Rsa2048KeyPair::new_with_e(65537).unwrap();
-        assert!(keypair.to_pubkey().is_ok());
-    }
-
-    #[test]
-    fn rsa2048_to_sgx_rsa_priv_key() {
-        let keypair = Rsa2048KeyPair::default();
-        assert!(keypair.to_privkey().is_err());
-        let keypair = Rsa2048KeyPair::new().unwrap();
-        assert!(keypair.to_privkey().is_ok());
-        let keypair = Rsa2048KeyPair::new_with_e(3).unwrap();
-        assert!(keypair.to_privkey().is_ok());
-        let keypair = Rsa2048KeyPair::new_with_e(65537).unwrap();
-        assert!(keypair.to_privkey().is_ok());
-    }
-
-    #[test]
-    fn rsa_encrypt_decrypt() {
-        let text = String::from("abc");
-        let text_slice = &text.into_bytes();
-
-        let mod_size: i32 = 256;
-        let exp_size: i32 = 4;
-        let mut n: Vec<u8> = vec![0_u8; mod_size as usize];
-        let mut d: Vec<u8> = vec![0_u8; mod_size as usize];
-        let mut e: Vec<u8> = vec![1, 0, 1, 0];
-        let mut p: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut q: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut dmp1: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut dmq1: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut iqmp: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-
-        assert!(rsgx_create_rsa_key_pair(
-            mod_size,
-            exp_size,
-            n.as_mut_slice(),
-            d.as_mut_slice(),
-            e.as_mut_slice(),
-            p.as_mut_slice(),
-            q.as_mut_slice(),
-            dmp1.as_mut_slice(),
-            dmq1.as_mut_slice(),
-            iqmp.as_mut_slice()
-        )
-        .is_ok());
-
-        let privkey = SgxRsaPrivKey::new();
-        let pubkey = SgxRsaPubKey::new();
-
-        assert!(pubkey
-            .create(mod_size, exp_size, n.as_slice(), e.as_slice())
-            .is_ok());
-
-        assert!(privkey
-            .create(
-                mod_size,
-                exp_size,
-                e.as_slice(),
-                p.as_slice(),
-                q.as_slice(),
-                dmp1.as_slice(),
-                dmq1.as_slice(),
-                iqmp.as_slice()
-            )
-            .is_ok());
-
-        let mut ciphertext: Vec<u8> = vec![0_u8; 256];
-        let mut chipertext_len: usize = ciphertext.len();
-        assert!(pubkey
-            .encrypt_sha256(ciphertext.as_mut_slice(), &mut chipertext_len, text_slice)
-            .is_ok());
-
-        let mut plaintext: Vec<u8> = vec![0_u8; 256];
-        let mut plaintext_len: usize = plaintext.len();
-        assert!(privkey
-            .decrypt_sha256(
-                plaintext.as_mut_slice(),
-                &mut plaintext_len,
-                ciphertext.as_slice()
-            )
-            .is_ok());
-
-        assert_eq!(plaintext[..plaintext_len], text_slice[..])
-    }
-
-    #[test]
-    fn buffer_enc_dec() {
-        let plaintext: Vec<u8> = "A".repeat(1000).into_bytes();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        let kp = Rsa2048KeyPair::new().unwrap();
-        assert!(kp.encrypt_buffer(&plaintext, &mut ciphertext).is_ok());
-        let mut decrypted: Vec<u8> = Vec::new();
-        assert!(kp.decrypt_buffer(&ciphertext, &mut decrypted).is_ok());
-        assert_eq!("A".repeat(1000), String::from_utf8(decrypted).unwrap());
-    }
-
-    #[test]
-    fn export_test() {
-        let plaintext: Vec<u8> = "T".repeat(1000).into_bytes();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        let kp = Rsa2048KeyPair::new().unwrap();
-        let exported_pub_key = kp.export_pubkey();
-        assert!(exported_pub_key.is_ok());
-
-        let exported_pub_key = exported_pub_key.unwrap();
-        let serialized_pub_key = serde_json::to_string(&exported_pub_key).unwrap();
-        let deserialized_pub_key: Rsa2048PubKey = serde_json::from_str(&serialized_pub_key).unwrap();
-
-        assert!(deserialized_pub_key.encrypt_buffer(&plaintext, &mut ciphertext).is_ok());
-        let mut decrypted: Vec<u8> = Vec::new();
-        assert!(kp.decrypt_buffer(&ciphertext, &mut decrypted).is_ok());
-        assert_eq!("T".repeat(1000), String::from_utf8(decrypted).unwrap());
-    }
-
-    #[bench]
-    fn encrypt_speed_bench(b: &mut Bencher) {
-        let mut rng = RdRand::new().unwrap();
-        let mut buffer = vec![0;1*1024*1024];
-        let kp = Rsa2048KeyPair::new().unwrap();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        rng.fill_bytes(&mut buffer);
-        b.iter(|| kp.encrypt_buffer(&buffer, &mut ciphertext));
-    }
-
-    #[bench]
-    fn decrypt_speed_bench(b: &mut Bencher) {
-        let mut rng = RdRand::new().unwrap();
-        let mut buffer = vec![0;1*1024*1024];
-        let kp = Rsa2048KeyPair::new().unwrap();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        rng.fill_bytes(&mut buffer);
-        kp.encrypt_buffer(&buffer, &mut ciphertext).unwrap();
-        let mut decrypted: Vec<u8> = Vec::new();
-        b.iter(|| kp.decrypt_buffer(&ciphertext, &mut decrypted));
-    }
-}
diff --git a/sgx_tcrypto_helper/src/rsa3072.rs b/sgx_tcrypto_helper/src/rsa3072.rs
deleted file mode 100644
index 6564ef4..0000000
--- a/sgx_tcrypto_helper/src/rsa3072.rs
+++ /dev/null
@@ -1,461 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License..
-
-//! # Cryptography Library Helper
-//!
-//! This crate provides helper functions to simplify key distribution and
-//! encryption/decryption. It utilizes sgx_tcrypto to provide
-//! a interface to enclave app. It provides key
-//! serialization/deserialization by serde.
-//!
-
-use crypto::rsgx_create_rsa_key_pair;
-use crypto::{SgxRsaPrivKey, SgxRsaPubKey};
-use itertools::Itertools;
-use sgx_types::sgx_status_t;
-use sgx_types::SgxResult;
-use sgx_types::{SGX_RSA3072_KEY_SIZE, SGX_RSA3072_PRI_EXP_SIZE, SGX_RSA3072_PUB_EXP_SIZE};
-pub const SGX_RSA3072_DEFAULT_E: [u8;SGX_RSA3072_PUB_EXP_SIZE]    = [0x01, 0x00, 0x00, 0x01]; // 65537
-use std::fmt;
-
-use std::prelude::v1::*;
-use crate::RsaKeyPair;
-use serde_derive::*;
-
-big_array! { BigArray; }
-
-/// Data structure of RSA 3072 Keypair (RSA-OAEP).
-/// RSA 3072 Keypair provides block cipher encryption/decryption
-/// implementations. The block size of plain text is 318 bytes
-/// and the block size of cipher text is 256 bytes.
-/// 318 byte = 3072bit - 2*SHA256_BYTE -2
-#[derive(Serialize, Deserialize, Clone, Copy)]
-pub struct Rsa3072KeyPair {
-    #[serde(with = "BigArray")]
-    n: [u8; SGX_RSA3072_KEY_SIZE],
-    #[serde(with = "BigArray")]
-    d: [u8; SGX_RSA3072_PRI_EXP_SIZE],
-    e: [u8; SGX_RSA3072_PUB_EXP_SIZE],
-    #[serde(with = "BigArray")]
-    p: [u8; SGX_RSA3072_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    q: [u8; SGX_RSA3072_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    dmp1: [u8; SGX_RSA3072_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    dmq1: [u8; SGX_RSA3072_KEY_SIZE / 2],
-    #[serde(with = "BigArray")]
-    iqmp: [u8; SGX_RSA3072_KEY_SIZE / 2],
-}
-
-impl Default for Rsa3072KeyPair {
-    fn default() -> Self {
-        Rsa3072KeyPair {
-            n: [0; SGX_RSA3072_KEY_SIZE],
-            d: [0; SGX_RSA3072_PRI_EXP_SIZE],
-            e: SGX_RSA3072_DEFAULT_E,
-            p: [0; SGX_RSA3072_KEY_SIZE / 2],
-            q: [0; SGX_RSA3072_KEY_SIZE / 2],
-            dmp1: [0; SGX_RSA3072_KEY_SIZE / 2],
-            dmq1: [0; SGX_RSA3072_KEY_SIZE / 2],
-            iqmp: [0; SGX_RSA3072_KEY_SIZE / 2],
-        }
-    }
-}
-
-impl fmt::Debug for Rsa3072KeyPair {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, r#"Rsa3072KeyPair: {{ n:{:02X}, d:{:02X}, e:{:02X}, p:{:02X}, q:{:02X}, dmp1:{:02X}, dmq:{:02X}, iqmp:{:02X} }}"#,
-            self.n.iter().format(""),
-            self.d.iter().format(""),
-            self.e.iter().format(""),
-            self.p.iter().format(""),
-            self.q.iter().format(""),
-            self.dmp1.iter().format(""),
-            self.dmq1.iter().format(""),
-            self.iqmp.iter().format(""))
-    }
-}
-
-impl RsaKeyPair for Rsa3072KeyPair {
-    fn new() -> SgxResult<Self> {
-        let mut newkey = Self::default();
-        match rsgx_create_rsa_key_pair(
-            SGX_RSA3072_KEY_SIZE as i32,
-            SGX_RSA3072_PUB_EXP_SIZE as i32,
-            &mut newkey.n,
-            &mut newkey.d,
-            &mut newkey.e,
-            &mut newkey.p,
-            &mut newkey.q,
-            &mut newkey.dmp1,
-            &mut newkey.dmq1,
-            &mut newkey.iqmp,
-        ) {
-            Ok(()) => Ok(newkey),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn new_with_e(e: u32) -> SgxResult<Self> {
-        let mut newkey = Self::default();
-        newkey.e = e.to_le_bytes();
-        match rsgx_create_rsa_key_pair(
-            SGX_RSA3072_KEY_SIZE as i32,
-            SGX_RSA3072_PUB_EXP_SIZE as i32,
-            &mut newkey.n,
-            &mut newkey.d,
-            &mut newkey.e,
-            &mut newkey.p,
-            &mut newkey.q,
-            &mut newkey.dmp1,
-            &mut newkey.dmq1,
-            &mut newkey.iqmp,
-        ) {
-            Ok(()) => Ok(newkey),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn to_privkey(self) -> SgxResult<SgxRsaPrivKey> {
-        let result = SgxRsaPrivKey::new();
-        match result.create(
-            SGX_RSA3072_KEY_SIZE as i32,
-            SGX_RSA3072_PRI_EXP_SIZE as i32,
-            &self.e,
-            &self.p,
-            &self.q,
-            &self.dmp1,
-            &self.dmq1,
-            &self.iqmp,
-        ) {
-            Ok(()) => Ok(result),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn to_pubkey(self) -> SgxResult<SgxRsaPubKey> {
-        let result = SgxRsaPubKey::new();
-        match result.create(
-            SGX_RSA3072_KEY_SIZE as i32,
-            SGX_RSA3072_PUB_EXP_SIZE as i32,
-            &self.n,
-            &self.e,
-        ) {
-            Ok(()) => Ok(result),
-            Err(x) => Err(x),
-        }
-    }
-
-    fn encrypt_buffer(self, plaintext: &[u8], ciphertext: &mut Vec<u8>) -> SgxResult<usize> {
-        let pubkey = self.to_pubkey()?;
-        let bs = 384;
-
-        let bs_plain = bs - 2 * 256 / 8 - 2;
-        let count = (plaintext.len() + bs_plain - 1) / bs_plain;
-        ciphertext.resize(bs * count, 0);
-
-        for i in 0..count {
-            let cipher_slice = &mut ciphertext[i * bs..i * bs + bs];
-            let mut out_len = bs;
-            let plain_slice =
-                &plaintext[i * bs_plain..std::cmp::min(i * bs_plain + bs_plain, plaintext.len())];
-
-            pubkey.encrypt_sha256(cipher_slice, &mut out_len, plain_slice)?;
-        }
-
-        Ok(ciphertext.len())
-    }
-
-    fn decrypt_buffer(self, ciphertext: &[u8], plaintext: &mut Vec<u8>) -> SgxResult<usize> {
-        let privkey = self.to_privkey()?;
-        let bs = 384;
-
-        if ciphertext.len() % bs != 0 {
-            return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
-        }
-
-        // Additional one byte is required in 1.0.9
-        // let bs_plain = bs - 2 * 256 / 8 - 2;
-        // In 2.6, we need a longer buf to put the decrypted data.
-        // The output length is exactly bs_plain above, but it results in
-        // SGX_ERROR_INVALID_PARAMETER.
-        let bs_plain = bs;
-        let count = ciphertext.len() / bs;
-        plaintext.clear();
-
-        for i in 0..count {
-            let cipher_slice = &ciphertext[i * bs..i * bs + bs];
-            let plain_slice = &mut vec![0;bs_plain];
-            let mut plain_len = bs_plain;
-
-            privkey.decrypt_sha256(plain_slice, &mut plain_len, cipher_slice)?;
-            let mut decoded_vec = plain_slice[..plain_len].to_vec();
-            plaintext.append(&mut decoded_vec);
-        }
-
-        Ok(plaintext.len())
-    }
-}
-
-impl Rsa3072KeyPair {
-    pub fn export_pubkey(self) -> SgxResult<Rsa3072PubKey> {
-        Ok(Rsa3072PubKey {
-            n: self.n,
-            e: self.e,
-        })
-    }
-}
-
-#[derive(Serialize, Deserialize, Clone, Copy)]
-pub struct Rsa3072PubKey {
-    #[serde(with = "BigArray")]
-    n: [u8; SGX_RSA3072_KEY_SIZE],
-    e: [u8; SGX_RSA3072_PUB_EXP_SIZE],
-}
-
-impl Default for Rsa3072PubKey {
-    fn default() -> Self {
-        Rsa3072PubKey {
-            n: [0; SGX_RSA3072_KEY_SIZE],
-            e: SGX_RSA3072_DEFAULT_E,
-        }
-    }
-}
-
-impl Rsa3072PubKey {
-    fn to_pubkey(self) -> SgxResult<SgxRsaPubKey> {
-        let result = SgxRsaPubKey::new();
-        match result.create(
-            SGX_RSA3072_KEY_SIZE as i32,
-            SGX_RSA3072_PUB_EXP_SIZE as i32,
-            &self.n,
-            &self.e,
-        ) {
-            Ok(()) => Ok(result),
-            Err(x) => Err(x),
-        }
-    }
-
-    pub fn encrypt_buffer(self, plaintext: &[u8], ciphertext: &mut Vec<u8>) -> SgxResult<usize> {
-        let pubkey = self.to_pubkey()?;
-        let bs = 384;
-
-        let bs_plain = bs - 2 * 256 / 8 - 2;
-        let count = (plaintext.len() + bs_plain - 1) / bs_plain;
-        ciphertext.resize(bs * count, 0);
-
-        for i in 0..count {
-            let cipher_slice = &mut ciphertext[i * bs..i * bs + bs];
-            let mut out_len = bs;
-            let plain_slice =
-                &plaintext[i * bs_plain..std::cmp::min(i * bs_plain + bs_plain, plaintext.len())];
-
-            pubkey.encrypt_sha256(cipher_slice, &mut out_len, plain_slice)?;
-        }
-
-        Ok(ciphertext.len())
-    }
-}
-
-impl fmt::Debug for Rsa3072PubKey {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, r#"Rsa3072KeyPair: {{ n:{:02X}, e:{:02X} }}"#,
-            self.n.iter().format(""),
-            self.e.iter().format(""))
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    extern crate rdrand;
-    extern crate rand_core;
-    extern crate test;
-
-    use self::test::Bencher;
-    use self::rdrand::RdRand;
-    use self::rand_core::RngCore;
-    use crate::RsaKeyPair;
-    use crate::rsa3072::Rsa3072KeyPair;
-    use crate::rsa3072::Rsa3072PubKey;
-    use crate::rsa3072::SgxRsaPrivKey;
-    use crate::rsa3072::SgxRsaPubKey;
-    use crypto::rsgx_create_rsa_key_pair;
-    use sgx_types::sgx_status_t;
-
-    #[test]
-    fn rsa3072_new() {
-        let keypair = Rsa3072KeyPair::new();
-        assert!(keypair.is_ok());
-        let keypair = Rsa3072KeyPair::new_with_e(3);
-        assert!(keypair.is_ok());
-        let keypair = Rsa3072KeyPair::new_with_e(65537);
-        assert!(keypair.is_ok());
-    }
-
-    #[test]
-    fn rsa3072_new_fail() {
-        let keypair = Rsa3072KeyPair::new_with_e(4);
-        assert_eq!(keypair.unwrap_err(), sgx_status_t::SGX_ERROR_UNEXPECTED);
-        let keypair = Rsa3072KeyPair::new_with_e(65536);
-        assert_eq!(keypair.unwrap_err(), sgx_status_t::SGX_ERROR_UNEXPECTED);
-    }
-
-    #[test]
-    fn rsa3072_to_sgx_rsa_pub_key() {
-        let keypair = Rsa3072KeyPair::default();
-        assert!(keypair.to_pubkey().is_err());
-        let keypair = Rsa3072KeyPair::new().unwrap();
-        assert!(keypair.to_pubkey().is_ok());
-        let keypair = Rsa3072KeyPair::new_with_e(3).unwrap();
-        assert!(keypair.to_pubkey().is_ok());
-        let keypair = Rsa3072KeyPair::new_with_e(65537).unwrap();
-        assert!(keypair.to_pubkey().is_ok());
-    }
-
-    #[test]
-    fn rsa3072_to_sgx_rsa_priv_key() {
-        let keypair = Rsa3072KeyPair::default();
-        assert!(keypair.to_privkey().is_err());
-        let keypair = Rsa3072KeyPair::new().unwrap();
-        assert!(keypair.to_privkey().is_ok());
-        let keypair = Rsa3072KeyPair::new_with_e(3).unwrap();
-        assert!(keypair.to_privkey().is_ok());
-        let keypair = Rsa3072KeyPair::new_with_e(65537).unwrap();
-        assert!(keypair.to_privkey().is_ok());
-    }
-
-    #[test]
-    fn rsa_encrypt_decrypt() {
-        let text = String::from("abc");
-        let text_slice = &text.into_bytes();
-
-        let mod_size: i32 = 256;
-        let exp_size: i32 = 4;
-        let mut n: Vec<u8> = vec![0_u8; mod_size as usize];
-        let mut d: Vec<u8> = vec![0_u8; mod_size as usize];
-        let mut e: Vec<u8> = vec![1, 0, 1, 0];
-        let mut p: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut q: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut dmp1: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut dmq1: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-        let mut iqmp: Vec<u8> = vec![0_u8; mod_size as usize / 2];
-
-        assert!(rsgx_create_rsa_key_pair(
-            mod_size,
-            exp_size,
-            n.as_mut_slice(),
-            d.as_mut_slice(),
-            e.as_mut_slice(),
-            p.as_mut_slice(),
-            q.as_mut_slice(),
-            dmp1.as_mut_slice(),
-            dmq1.as_mut_slice(),
-            iqmp.as_mut_slice()
-        )
-        .is_ok());
-
-        let privkey = SgxRsaPrivKey::new();
-        let pubkey = SgxRsaPubKey::new();
-
-        assert!(pubkey
-            .create(mod_size, exp_size, n.as_slice(), e.as_slice())
-            .is_ok());
-
-        assert!(privkey
-            .create(
-                mod_size,
-                exp_size,
-                e.as_slice(),
-                p.as_slice(),
-                q.as_slice(),
-                dmp1.as_slice(),
-                dmq1.as_slice(),
-                iqmp.as_slice()
-            )
-            .is_ok());
-
-        let mut ciphertext: Vec<u8> = vec![0_u8; 256];
-        let mut chipertext_len: usize = ciphertext.len();
-        assert!(pubkey
-            .encrypt_sha256(ciphertext.as_mut_slice(), &mut chipertext_len, text_slice)
-            .is_ok());
-
-        let mut plaintext: Vec<u8> = vec![0_u8; 256];
-        let mut plaintext_len: usize = plaintext.len();
-        assert!(privkey
-            .decrypt_sha256(
-                plaintext.as_mut_slice(),
-                &mut plaintext_len,
-                ciphertext.as_slice()
-            )
-            .is_ok());
-
-        assert_eq!(plaintext[..plaintext_len], text_slice[..])
-    }
-
-    #[test]
-    fn buffer_enc_dec() {
-        let plaintext: Vec<u8> = "A".repeat(1000).into_bytes();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        let kp = Rsa3072KeyPair::new().unwrap();
-        assert!(kp.encrypt_buffer(&plaintext, &mut ciphertext).is_ok());
-        let mut decrypted: Vec<u8> = Vec::new();
-        assert!(kp.decrypt_buffer(&ciphertext, &mut decrypted).is_ok());
-        assert_eq!("A".repeat(1000), String::from_utf8(decrypted).unwrap());
-    }
-
-    #[test]
-    fn export_test() {
-        let plaintext: Vec<u8> = "T".repeat(1000).into_bytes();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        let kp = Rsa3072KeyPair::new().unwrap();
-        let exported_pub_key = kp.export_pubkey();
-        assert!(exported_pub_key.is_ok());
-
-        let exported_pub_key = exported_pub_key.unwrap();
-        let serialized_pub_key = serde_json::to_string(&exported_pub_key).unwrap();
-        let deserialized_pub_key: Rsa3072PubKey = serde_json::from_str(&serialized_pub_key).unwrap();
-
-        assert!(deserialized_pub_key.encrypt_buffer(&plaintext, &mut ciphertext).is_ok());
-        let mut decrypted: Vec<u8> = Vec::new();
-        assert!(kp.decrypt_buffer(&ciphertext, &mut decrypted).is_ok());
-        assert_eq!("T".repeat(1000), String::from_utf8(decrypted).unwrap());
-    }
-
-    #[bench]
-    fn encrypt_speed_bench(b: &mut Bencher) {
-        let mut rng = RdRand::new().unwrap();
-        let mut buffer = vec![0;1*1024*1024];
-        let kp = Rsa3072KeyPair::new().unwrap();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        rng.fill_bytes(&mut buffer);
-        b.iter(|| kp.encrypt_buffer(&buffer, &mut ciphertext));
-    }
-
-    #[bench]
-    fn decrypt_speed_bench(b: &mut Bencher) {
-        let mut rng = RdRand::new().unwrap();
-        let mut buffer = vec![0;1*1024*1024];
-        let kp = Rsa3072KeyPair::new().unwrap();
-        let mut ciphertext: Vec<u8> = Vec::new();
-        rng.fill_bytes(&mut buffer);
-        kp.encrypt_buffer(&buffer, &mut ciphertext).unwrap();
-        let mut decrypted: Vec<u8> = Vec::new();
-        b.iter(|| kp.decrypt_buffer(&ciphertext, &mut decrypted));
-    }
-}
diff --git a/sgx_tdh/Cargo.toml b/sgx_tdh/Cargo.toml
index 4069a61..e7f3f8f 100644
--- a/sgx_tdh/Cargo.toml
+++ b/sgx_tdh/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tdh"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tdh/src/dh.rs b/sgx_tdh/src/dh.rs
index da0dbde..c5f822e 100644
--- a/sgx_tdh/src/dh.rs
+++ b/sgx_tdh/src/dh.rs
@@ -102,12 +102,12 @@ impl SgxDhMsg3 {
     ///
     /// The parameters p and len are not available for the conversion.
     ///
-    pub unsafe fn to_raw_dh_msg3_t(&self, p: * mut sgx_dh_msg3_t, len: u32) -> Option<* mut sgx_dh_msg3_t> {
+    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;
         }
-        if !rsgx_raw_is_within_enclave(p as * mut u8, len as usize) {
+        if !rsgx_raw_is_within_enclave(p as *mut u8, len as usize) {
             return None;
         }
 
@@ -126,7 +126,7 @@ impl SgxDhMsg3 {
         dh_msg3.msg3_body.additional_prop_length = additional_prop_len as u32;
 
         if additional_prop_len > 0 {
-            let raw_msg3 = slice::from_raw_parts_mut(p as * mut u8, len as usize);
+            let raw_msg3 = slice::from_raw_parts_mut(p as *mut u8, len as usize);
             raw_msg3[dh_msg3_size..].copy_from_slice(&self.msg3_body.additional_prop);
         }
         Some(p)
@@ -155,12 +155,12 @@ impl SgxDhMsg3 {
     ///
     /// The parameters p and len are not available for the conversion.
     ///
-    pub unsafe fn from_raw_dh_msg3_t(p: * mut sgx_dh_msg3_t, len: u32) -> Option<Self> {
+    pub unsafe fn from_raw_dh_msg3_t(p: *mut sgx_dh_msg3_t, len: u32) -> Option<Self> {
 
         if p.is_null() {
             return None;
         }
-        if !rsgx_raw_is_within_enclave(p as * mut u8, len as usize) {
+        if !rsgx_raw_is_within_enclave(p as *mut u8, len as usize) {
             return None;
         }
 
@@ -180,7 +180,7 @@ impl SgxDhMsg3 {
 
         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;
+            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);
             dh_msg3.msg3_body.additional_prop = additional_prop.into_boxed_slice();
         }
@@ -376,7 +376,7 @@ impl SgxDhResponder {
         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>()) {
+           !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);
@@ -760,7 +760,7 @@ impl SgxDhInitiator {
         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>()) ||
+        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();
@@ -963,8 +963,8 @@ impl SgxLAv2ProtoSpec {
             return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
         }
 
-        let d = ti as * mut sgx_target_info_t as * mut u8;
-        let f = rpt as * const sgx_report_t as * const u8;
+        let d = ti as *mut sgx_target_info_t as *mut u8;
+        let f = rpt as *const sgx_report_t as *const u8;
         rsgx_lfence();
 
         let mut to: i32 = 0;
diff --git a/sgx_tkey_exchange/Cargo.toml b/sgx_tkey_exchange/Cargo.toml
index 1d34f92..b83b0bc 100644
--- a/sgx_tkey_exchange/Cargo.toml
+++ b/sgx_tkey_exchange/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tkey_exchange"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tkey_exchange/src/lib.rs b/sgx_tkey_exchange/src/lib.rs
index b22019f..a039fa3 100644
--- a/sgx_tkey_exchange/src/lib.rs
+++ b/sgx_tkey_exchange/src/lib.rs
@@ -43,9 +43,7 @@ use sgx_types::*;
 ///
 /// **b_pse**
 ///
-/// If true, platform service information is needed in message 3. The caller should make sure a PSE session
-/// has been established using rsgx_create_pse_session before attempting to establish a remote attestation
-/// and key exchange session involving platform service information.
+/// Reserved for backward compatibility.
 ///
 /// # Requirements
 ///
@@ -77,12 +75,11 @@ use sgx_types::*;
 /// Indicates that an unexpected error occurred.
 ///
 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,
+        sgx_ra_init(p_pub_key as *const sgx_ec256_public_t,
                     b_pse,
-                    &mut context as * mut sgx_ra_context_t)
+                    &mut context as *mut sgx_ra_context_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(context),
@@ -107,9 +104,7 @@ pub fn rsgx_ra_init(p_pub_key: &sgx_ec256_public_t, b_pse: i32) -> SgxResult<sgx
 ///
 /// **b_pse**
 ///
-/// If true, platform service information is needed in message 3. The caller should make sure a PSE session
-/// has been established using rsgx_create_pse_session before attempting to establish a remote attestation
-/// and key exchange session involving platform service information.
+/// Reserved for backward compatibility.
 ///
 /// **derive_key_cb**
 ///
@@ -149,13 +144,12 @@ pub fn rsgx_ra_init(p_pub_key: &sgx_ec256_public_t, b_pse: i32) -> SgxResult<sgx
 pub fn rsgx_ra_init_ex(p_pub_key: &sgx_ec256_public_t,
                        b_pse: i32,
                        derive_key_cb: sgx_ra_derive_secret_keys_t) -> SgxResult<sgx_ra_context_t> {
-
     let mut context: sgx_ra_context_t = 0;
     let ret = unsafe {
-        sgx_ra_init_ex(p_pub_key as * const sgx_ec256_public_t,
+        sgx_ra_init_ex(p_pub_key as *const sgx_ec256_public_t,
                        b_pse,
                        derive_key_cb,
-                       &mut context as * mut sgx_ra_context_t)
+                       &mut context as *mut sgx_ra_context_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(context),
@@ -206,10 +200,9 @@ pub fn rsgx_ra_init_ex(p_pub_key: &sgx_ec256_public_t,
 /// 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> {
-
     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)
+        sgx_ra_get_keys(context, keytype, &mut key as *mut sgx_ra_key_128_t)
     };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(key),
@@ -247,7 +240,6 @@ pub fn rsgx_ra_get_keys(context: sgx_ra_context_t, keytype: sgx_ra_key_type_t) -
 /// Indicates an error that the input parameters are invalid.
 ///
 pub fn rsgx_ra_close(context: sgx_ra_context_t) -> SgxError {
-
     let ret = unsafe { sgx_ra_close(context) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
diff --git a/sgx_tprotected_fs/Cargo.toml b/sgx_tprotected_fs/Cargo.toml
index 2c5bbb8..28d8678 100644
--- a/sgx_tprotected_fs/Cargo.toml
+++ b/sgx_tprotected_fs/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tprotected_fs"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tprotected_fs/src/fs.rs b/sgx_tprotected_fs/src/fs.rs
index e64c2c4..7cbb24e 100644
--- a/sgx_tprotected_fs/src/fs.rs
+++ b/sgx_tprotected_fs/src/fs.rs
@@ -27,7 +27,7 @@ fn max_len() -> 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 {
@@ -50,7 +50,7 @@ unsafe fn rsgx_fwrite(stream: SGX_FILE, buf: &[u8]) -> SysResult<usize> {
     }
 
     let write_size = cmp::min(buf.len(), max_len());
-    let ret_size = sgx_fwrite(buf.as_ptr() as * const c_void, 1, write_size, stream);
+    let ret_size = sgx_fwrite(buf.as_ptr() as *const c_void, 1, write_size, stream);
     if ret_size != write_size {
         Err(rsgx_ferror(stream))
     } else {
@@ -64,7 +64,7 @@ unsafe fn rsgx_fread(stream: SGX_FILE, buf: &mut [u8]) -> SysResult<usize> {
     }
 
     let read_size = cmp::min(buf.len(), max_len());
-    let ret_size = sgx_fread(buf.as_mut_ptr() as * mut c_void, 1, read_size, stream);
+    let ret_size = sgx_fread(buf.as_mut_ptr() as *mut c_void, 1, read_size, stream);
 
     if ret_size != read_size {
         let is_eof = rsgx_feof(stream)?;
@@ -175,7 +175,7 @@ unsafe fn rsgx_remove(filename: &CStr) -> SysError {
 }
 
 unsafe fn rsgx_fexport_auto_key(filename: &CStr, key: &mut sgx_key_128bit_t) -> SysError {
-    let ret = sgx_fexport_auto_key(filename.as_ptr(), key as * mut sgx_key_128bit_t);
+    let ret = sgx_fexport_auto_key(filename.as_ptr(), key as *mut sgx_key_128bit_t);
     if ret == 0 {
         Ok(())
     } else {
@@ -184,7 +184,7 @@ unsafe fn rsgx_fexport_auto_key(filename: &CStr, key: &mut sgx_key_128bit_t) ->
 }
 
 unsafe fn rsgx_fimport_auto_key(filename: &CStr, key: &sgx_key_128bit_t) -> SysError {
-    let ret = sgx_fimport_auto_key(filename.as_ptr(), key as * const sgx_key_128bit_t);
+    let ret = sgx_fimport_auto_key(filename.as_ptr(), key as *const sgx_key_128bit_t);
     if ret == 0 {
         Ok(())
     } else {
diff --git a/sgx_trts/Cargo.toml b/sgx_trts/Cargo.toml
index 45a73de..c040996 100644
--- a/sgx_trts/Cargo.toml
+++ b/sgx_trts/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_trts"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_trts/src/c_str.rs b/sgx_trts/src/c_str.rs
index 728dd55..914cd5a 100644
--- a/sgx_trts/src/c_str.rs
+++ b/sgx_trts/src/c_str.rs
@@ -571,7 +571,7 @@ impl CStr {
     /// performing any sanity checks. The provided slice **must** be nul-terminated
     /// and not contain any interior nul bytes.
     ///
-    #[rustc_const_unstable(feature = "const_cstr_unchecked")]
+    //#[rustc_const_unstable(feature = "const_cstr_unchecked")]
     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
         &*(bytes as *const [u8] as *const CStr)
     }
diff --git a/sgx_trts/src/cpu_feature.rs b/sgx_trts/src/cpu_feature.rs
index 639adab..f47c884 100644
--- a/sgx_trts/src/cpu_feature.rs
+++ b/sgx_trts/src/cpu_feature.rs
@@ -14,6 +14,7 @@
 // KIND, either express or implied.  See the License for the
 // specific language governing permissions and limitations
 // under the License..
+
 use sgx_types::impl_enum;
 use crate::enclave;
 
@@ -209,102 +210,102 @@ impl_enum! {
     #[repr(u32)]
     #[derive(Copy, Clone, PartialEq, Eq)]
     pub enum Feature {
-        none = 0,
-        ia32 = 1,             /* 0x00000001 */
-        fpu = 2,              /* 0x00000002 */
-        cmov = 3,             /* 0x00000004 */
-        mmx = 4,              /* 0x00000008 */
-        fxsave = 5,           /* 0x00000010 */
-        sse = 6,              /* 0x00000020 */
-        sse2 = 7,             /* 0x00000040 */
-        sse3 = 8,             /* 0x00000080 */
-        ssse3 = 9,            /* 0x00000100 */
-        sse4_1 = 10,          /* 0x00000200 */
-        sse4_2 = 11,          /* 0x00000400 */
-        movbe = 12,           /* 0x00000800 */
-        popcnt = 13,          /* 0x00001000 */
-        pclmulqdq = 14,       /* 0x00002000 */
-        aes = 15,             /* 0x00004000 */
+        none            = 0,
+        ia32            = 1,        /* 0x00000001 */
+        fpu             = 2,        /* 0x00000002 */
+        cmov            = 3,        /* 0x00000004 */
+        mmx             = 4,        /* 0x00000008 */
+        fxsave          = 5,        /* 0x00000010 */
+        sse             = 6,        /* 0x00000020 */
+        sse2            = 7,        /* 0x00000040 */
+        sse3            = 8,        /* 0x00000080 */
+        ssse3           = 9,        /* 0x00000100 */
+        sse4_1          = 10,       /* 0x00000200 */
+        sse4_2          = 11,       /* 0x00000400 */
+        movbe           = 12,       /* 0x00000800 */
+        popcnt          = 13,       /* 0x00001000 */
+        pclmulqdq       = 14,       /* 0x00002000 */
+        aes             = 15,       /* 0x00004000 */
 
         /* 16-bit floating-point conversions instructions */
-        f16c = 16,            /* 0x00008000 */
+        f16c            = 16,       /* 0x00008000 */
         /* AVX instructions - SNB */
-        avx = 17,            /* 0x00010000 */
+        avx             = 17,       /* 0x00010000 */
         /* RDRND (read random value) instruction */
-        rdrand = 18,          /* 0x00020000 */
+        rdrand          = 18,       /* 0x00020000 */
         /* FMA, may need more precise name - HSW */
-        fma = 19,             /* 0x00040000 */
+        fma             = 19,       /* 0x00040000 */
         /* two groups of advanced bit manipulation extensions */
-        bmi = 20,             /* 0x00080000 */
+        bmi             = 20,       /* 0x00080000 */
         /* LZCNT (leading zeroes count) */
-        lzcnt = 21,           /* 0x00100000 */
+        lzcnt           = 21,       /* 0x00100000 */
         /* HLE (hardware lock elision) */
-        hle = 22,             /* 0x00200000 */
+        hle             = 22,       /* 0x00200000 */
         /* RTM (restricted transactional memory) */
-        rtm = 23,             /* 0x00400000 */
+        rtm             = 23,       /* 0x00400000 */
         /* AVX2 instructions - HSW */
-        avx2 = 24,            /* 0x00800000 */
+        avx2            = 24,       /* 0x00800000 */
         /* AVX512DQ - SKX 512-bit dword/qword vector instructions */
-        avx512dq = 25,        /* 0x01000000 */
+        avx512dq        = 25,       /* 0x01000000 */
         /* Unused, remained from KNF */
-        ptwrite = 26,         /* 0x02000000 */
+        ptwrite         = 26,       /* 0x02000000 */
         /* KNC new instructions */
-        kncni = 27,           /* 0x04000000 */
+        kncni           = 27,       /* 0x04000000 */
         /* AVX-512 foundation instructions - KNL and SKX */
-        avx512f = 28,         /* 0x08000000 */
+        avx512f         = 28,       /* 0x08000000 */
         /* uint add with OF or CF flags (ADOX, ADCX) - BDW */
-        adx = 29,             /* 0x10000000 */
+        adx             = 29,       /* 0x10000000 */
         /* Enhanced non-deterministic rand generator - BDW */
-        rdseed = 30,          /* 0x20000000 */
+        rdseed          = 30,       /* 0x20000000 */
         /* AVX512IFMA52:  vpmadd52huq and vpmadd52luq. */
-        avx512ifma = 31,      /* 0x40000000 */
+        avx512ifma      = 31,       /* 0x40000000 */
         /* Full inorder (like Silverthorne) processor */
-        full_inorder = 32,    /* 0x80000000 */
+        full_inorder    = 32,       /* 0x80000000 */
         /* AVX-512 exponential and reciprocal instructions - KNL */
-        avx512er = 33,        /* 0x100000000 */
+        avx512er        = 33,       /* 0x100000000 */
         /* AVX-512 gather/scatter prefetch instructions - KNL */
-        avx512pf = 34,        /* 0x200000000 */
+        avx512pf        = 34,       /* 0x200000000 */
         /* AVX-512 conflict detection instructions - KNL */
-        avx512cd = 35,        /* 0x400000000 */
+        avx512cd        = 35,       /* 0x400000000 */
         /* Secure Hash Algorithm instructions (SHA) */
-        sha = 36,             /* 0x800000000 */
+        sha             = 36,       /* 0x800000000 */
         /* Memory Protection Extensions (MPX) */
-        mpx = 37,             /* 0x1000000000 */
+        mpx             = 37,       /* 0x1000000000 */
         /* AVX512BW - SKX 512-bit byte/word vector instructions */
-        avx512bw = 38,        /* 0x2000000000 */
+        avx512bw        = 38,       /* 0x2000000000 */
         /* AVX512VL - adds 128/256-bit vector support of other AVX512 instructions. */
-        avx512vl = 39,        /* 0x4000000000 */
+        avx512vl        = 39,       /* 0x4000000000 */
         /* AVX512VBMI:  vpermb, vpermi2b, vpermt2b and vpmultishiftqb. */
-        avx512vbmi = 40,      /* 0x8000000000 */
+        avx512vbmi      = 40,       /* 0x8000000000 */
         /* AVX512_4FMAPS: Single Precision FMA for multivector(4 vector) operand. */
-        avx512_4fmaps = 41,   /* 0x10000000000 */
+        avx512_4fmaps   = 41,       /* 0x10000000000 */
         /* AVX512_4VNNIW: Vector Neural Network Instructions for
         *  multivector(4 vector) operand with word elements. */
-        avx512_4vnniw = 42,   /* 0x20000000000 */
+        avx512_4vnniw   = 42,       /* 0x20000000000 */
         /* AVX512_VPOPCNTDQ: 512-bit vector POPCNT. */
-        avx512_vpopcntdq = 43,   /* 0x40000000000 */
+        avx512_vpopcntdq = 43,      /* 0x40000000000 */
         /* AVX512_BITALG: vector bit algebra in AVX512. */
-        avx512_bitalg = 44,   /* 0x80000000000 */
+        avx512_bitalg   = 44,       /* 0x80000000000 */
         /* AVX512_VBMI2: additional byte, word, dword and qword capabilities */
-        avx512vbmi2 = 45,     /* 0x100000000000 */
+        avx512vbmi2     = 45,       /* 0x100000000000 */
         /* GFNI: Galois Field New Instructions. */
-        gfni = 46,            /* 0x200000000000 */
+        gfni            = 46,       /* 0x200000000000 */
         /* VAES: vector AES instructions */
-        vaes = 47,            /* 0x400000000000 */
+        vaes            = 47,       /* 0x400000000000 */
         /* VPCLMULQDQ: vector PCLMULQDQ instructions. */
-        vpclmulqdq = 48,      /* 0x800000000000 */
+        vpclmulqdq      = 48,       /* 0x800000000000 */
         /* AVX512_VNNI: vector Neural Network Instructions. */
-        avx512vnni = 49,      /* 0x1000000000000 */
+        avx512vnni      = 49,       /* 0x1000000000000 */
         /* CLWB: Cache Line Write Back. */
-        clwb = 50,            /* 0x2000000000000 */
+        clwb            = 50,       /* 0x2000000000000 */
         /* RDPID: Read Processor ID. */
-        rdpid = 51,           /* 0x4000000000000 */
-        ibt = 52,             /* 0x8000000000000 */
-        shstk = 53,
-        sgx = 54,
-        wbnoinvd = 55,
-        pconfig = 56,
-        end = 57,
+        rdpid           = 51,       /* 0x4000000000000 */
+        ibt             = 52,       /* 0x8000000000000 */
+        shstk           = 53,
+        sgx             = 54,
+        wbnoinvd        = 55,
+        pconfig         = 56,
+        end             = 57,
     }
 }
 
diff --git a/sgx_tstd/src/cpuid.rs b/sgx_trts/src/cpuid.rs
similarity index 95%
copy from sgx_tstd/src/cpuid.rs
copy to sgx_trts/src/cpuid.rs
index a02495c..521a8c3 100644
--- a/sgx_tstd/src/cpuid.rs
+++ b/sgx_trts/src/cpuid.rs
@@ -13,7 +13,6 @@
 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 // KIND, either express or implied.  See the License for the
 // specific language governing permissions and limitations
-// under the License..
 
 use sgx_types::*;
 
@@ -68,9 +67,8 @@ use sgx_types::*;
 /// Indicates the parameter is invalid.
 ///
 pub fn rsgx_cpuid(leaf: i32) -> SgxResult<sgx_cpuinfo_t> {
-
     let mut cpuinfo = [0_i32; 4];
-    let ret = unsafe { sgx_cpuid(&mut cpuinfo as * mut sgx_cpuinfo_t, leaf) };
+    let ret = unsafe { sgx_cpuid(&mut cpuinfo as *mut sgx_cpuinfo_t, leaf) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(cpuinfo),
         _ => Err(ret),
@@ -132,11 +130,10 @@ pub fn rsgx_cpuid(leaf: i32) -> SgxResult<sgx_cpuinfo_t> {
 /// Indicates the parameter is invalid.
 ///
 pub fn rsgx_cpuidex(leaf: i32, subleaf: i32) -> SgxResult<sgx_cpuinfo_t> {
-
     let mut cpuinfo = [0_i32; 4];
-    let ret = unsafe { sgx_cpuidex(&mut cpuinfo as * mut sgx_cpuinfo_t, leaf, subleaf) };
+    let ret = unsafe { sgx_cpuidex(&mut cpuinfo as *mut sgx_cpuinfo_t, leaf, subleaf) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(cpuinfo),
         _ => Err(ret),
     }
-}
\ No newline at end of file
+}
diff --git a/sgx_trts/src/enclave.rs b/sgx_trts/src/enclave.rs
index 15d4c56..aa7c5f9 100644
--- a/sgx_trts/src/enclave.rs
+++ b/sgx_trts/src/enclave.rs
@@ -29,11 +29,14 @@ pub const LAYOUT_ENTRY_NUM : usize = 42;
 extern {
     static g_global_data: global_data_t;
     static g_cpu_feature_indicator: uint64_t;
+    static g_cpu_core_num: uint32_t;
     static EDMM_supported: c_int;
-    pub fn get_thread_data() -> * const c_void;
-    pub fn get_enclave_base() -> * const c_void;
-    pub fn get_heap_base() -> * const c_void;
+    pub fn get_thread_data() -> *const c_void;
+    pub fn get_enclave_base() -> *const c_void;
+    pub fn get_heap_base() -> *const c_void;
     pub fn get_heap_size() -> size_t;
+    pub fn get_rsrv_base() -> *const c_void;
+    pub fn get_rsrv_size() -> size_t;
 }
 
 #[repr(C)]
@@ -43,9 +46,11 @@ pub struct global_data_t {
     pub heap_size: usize,
     pub rsrv_offset: usize,
     pub rsrv_size: usize,
+    pub rsrv_executable: usize,
     pub thread_policy: usize,
+    pub tcs_max_num: usize,
     pub td_template: thread_data_t,
-    pub tcs_template: [u8; TCS_TEMPLATE_SIZE], // 72
+    pub tcs_template: [u8; TCS_TEMPLATE_SIZE],
     pub layout_entry_num: u32,
     pub reserved: u32,
     pub layout_table: [layout_t; LAYOUT_ENTRY_NUM],
@@ -77,10 +82,14 @@ pub struct SgxGlobalData {
     heap_base: usize,
     heap_offset: usize,
     heap_size: usize,
+    rsrv_base: usize,
+    rsrv_offset: usize,
+    rsrv_size: usize,
     thread_policy: SgxThreadPolicy,
     static_tcs_num: u32,  // minpool thread + utility thread
     eremove_tcs_num: u32,
     dyn_tcs_num: u32,
+    max_tcs_num: u32,
 }
 
 impl Default for SgxGlobalData {
@@ -106,10 +115,14 @@ impl SgxGlobalData {
            heap_base: rsgx_get_heap_base() as usize,
            heap_offset: rsgx_get_heap_offset(),
            heap_size: rsgx_get_heap_size(),
+           rsrv_base: rsgx_get_rsrv_base() as usize,
+           rsrv_offset: rsgx_get_rsrv_offset(),
+           rsrv_size: rsgx_get_rsrv_size(),
            thread_policy: rsgx_get_thread_policy(),
            static_tcs_num: static_num,
            eremove_tcs_num: eremove_num,
            dyn_tcs_num: dyn_num,
+           max_tcs_num: rsgx_get_tcs_max_num(),
         }
     }
 
@@ -164,6 +177,36 @@ impl SgxGlobalData {
         self.heap_size
     }
     ///
+    /// rsrv_base is to get rsrv base address.
+    ///
+    /// **Note**
+    ///
+    /// This API is only an experimental funtion.
+    ///
+    pub fn rsrv_base(&self) -> usize {
+        self.rsrv_base
+    }
+    ///
+    /// rsrv_offset is to get heap offset.
+    ///
+    /// **Note**
+    ///
+    /// This API is only an experimental funtion.
+    ///
+    pub fn rsrv_offset(&self) -> usize {
+        self.rsrv_offset
+    }
+    ///
+    /// rsrv_size is to get heap size.
+    ///
+    /// **Note**
+    ///
+    /// This API is only an experimental funtion.
+    ///
+    pub fn rsrv_size(&self) -> usize {
+        self.rsrv_size
+    }
+    ///
     /// thread_policy is to get TCS policy.
     ///
     /// **Note**
@@ -187,15 +230,16 @@ impl SgxGlobalData {
     }
 
     pub fn get_tcs_max_num(&self) -> u32 {
-        if rsgx_is_supported_EDMM() {
-            if self.dyn_tcs_num != 0 {
-                self.static_tcs_num + self.dyn_tcs_num - 1 // - 1 is utility thread
-            } else {
-                self.static_tcs_num
-            }
-        } else {
-            self.static_tcs_num + self.eremove_tcs_num
-        }
+        self.max_tcs_num
+        //if rsgx_is_supported_EDMM() {
+        //    if self.dyn_tcs_num != 0 {
+        //        self.static_tcs_num + self.dyn_tcs_num - 1 // - 1 is utility thread
+        //    } else {
+        //        self.static_tcs_num
+        //    }
+        //} else {
+        //    self.static_tcs_num + self.eremove_tcs_num
+        //}
     }
 }
 
@@ -248,7 +292,7 @@ impl SgxThreadData {
     }
 
     pub unsafe fn from_raw(raw: sgx_thread_t) -> Self {
-        let p = raw as * const thread_data_t;
+        let p = raw as *const thread_data_t;
         let td = &*p;
         SgxThreadData {
             td_addr: td.self_addr,
@@ -346,8 +390,8 @@ pub enum SgxThreadPolicy {
 /// This API is only an experimental funtion.
 ///
 #[inline]
-pub fn rsgx_get_thread_data() -> * const thread_data_t {
-    unsafe { get_thread_data() as * const thread_data_t }
+pub fn rsgx_get_thread_data() -> *const thread_data_t {
+    unsafe { get_thread_data() as *const thread_data_t }
 }
 
 ///
@@ -358,8 +402,8 @@ pub fn rsgx_get_thread_data() -> * const thread_data_t {
 /// This API is only an experimental funtion.
 ///
 #[inline]
-pub fn rsgx_get_enclave_base() -> * const u8 {
-    unsafe { get_enclave_base() as * const u8 }
+pub fn rsgx_get_enclave_base() -> *const u8 {
+    unsafe { get_enclave_base() as *const u8 }
 }
 
 ///
@@ -382,8 +426,8 @@ pub fn rsgx_get_enclave_size() -> usize {
 /// This API is only an experimental funtion.
 ///
 #[inline]
-pub fn rsgx_get_heap_base() -> * const u8 {
-    unsafe { get_heap_base() as * const u8 }
+pub fn rsgx_get_heap_base() -> *const u8 {
+    unsafe { get_heap_base() as *const u8 }
 }
 
 ///
@@ -411,6 +455,42 @@ pub fn rsgx_get_heap_size() -> usize {
 }
 
 ///
+/// rsgx_get_rsrv_base is to get enclave rsrv base address.
+///
+/// **Note**
+///
+/// This API is only an experimental funtion.
+///
+#[inline]
+pub fn rsgx_get_rsrv_base() -> *const u8 {
+    unsafe { get_rsrv_base() as *const u8 }
+}
+
+///
+/// rsgx_get_rsrv_offset is to get enclave rsrv offset.
+///
+/// **Note**
+///
+/// This API is only an experimental funtion.
+///
+#[inline]
+pub fn rsgx_get_rsrv_offset() -> usize {
+    unsafe{ g_global_data.rsrv_offset }
+}
+
+///
+/// rsgx_get_rsrv_size is to get enclave rsrv size.
+///
+/// **Note**
+///
+/// This API is only an experimental funtion.
+///
+#[inline]
+pub fn rsgx_get_rsrv_size() -> usize {
+    unsafe { get_rsrv_size() }
+}
+
+///
 /// rsgx_get_thread_policy is to get TCS management policy.
 ///
 /// **Note**
@@ -436,8 +516,20 @@ pub fn rsgx_get_thread_policy() -> SgxThreadPolicy {
 /// This API is only an experimental funtion.
 ///
 #[inline]
-pub fn rsgx_get_global_data() -> * const global_data_t {
-    unsafe { &g_global_data as * const global_data_t }
+pub fn rsgx_get_global_data() -> *const global_data_t {
+    unsafe { &g_global_data as *const global_data_t }
+}
+
+///
+/// rsgx_get_tcs_max_num is to get max tcs number.
+///
+/// **Note**
+///
+/// This API is only an experimental funtion.
+///
+#[inline]
+pub fn rsgx_get_tcs_max_num() -> u32 {
+    unsafe { g_global_data.tcs_max_num as u32 }
 }
 
 pub fn rsgx_get_tcs_num() -> (u32, u32, u32) {
@@ -482,10 +574,19 @@ pub fn rsgx_get_tcs_num() -> (u32, u32, u32) {
 
 #[inline]
 pub fn rsgx_is_supported_EDMM() -> bool {
+    // cpu support
+    // sgx driver support
+    // sgx sdk support ( uRTS and enclave metadata)
+    // hw mode
     unsafe { EDMM_supported != 0 }
 }
 
 #[inline]
 pub fn rsgx_get_cpu_feature() -> u64 {
     unsafe { g_cpu_feature_indicator }
+}
+
+#[inline]
+pub fn rsgx_get_cpu_core_num() -> u32 {
+    unsafe { g_cpu_core_num }
 }
\ No newline at end of file
diff --git a/sgx_trts/src/lib.rs b/sgx_trts/src/lib.rs
index 7096ee5..45dbc42 100644
--- a/sgx_trts/src/lib.rs
+++ b/sgx_trts/src/lib.rs
@@ -68,9 +68,9 @@
 
 #![feature(allocator_api)]
 #![feature(asm)]
-#![feature(rustc_const_unstable)]
+//#![feature(rustc_const_unstable)]
 #![feature(const_raw_ptr_deref)]
-#![feature(const_cstr_unchecked)]
+//#![feature(const_cstr_unchecked)]
 #![allow(non_camel_case_types)]
 #![allow(non_upper_case_globals)]
 #![allow(overflowing_literals)]
@@ -96,6 +96,7 @@ pub mod memchr;
 pub mod ascii;
 pub mod c_str;
 pub mod cpu_feature;
+pub mod cpuid;
 
 #[cfg(not(target_env = "sgx"))]
 pub use sgx_libc as libc;
diff --git a/sgx_trts/src/memchr.rs b/sgx_trts/src/memchr.rs
index 1118fd8..a1bdb96 100644
--- a/sgx_trts/src/memchr.rs
+++ b/sgx_trts/src/memchr.rs
@@ -37,7 +37,6 @@
 // }
 
 pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
-
     let p = unsafe {
         sgx_libc::memchr(
             haystack.as_ptr(),
@@ -54,7 +53,6 @@ pub fn memchr(needle: u8, haystack: &[u8]) -> Option<usize> {
 pub fn memrchr(needle: u8, haystack: &[u8]) -> Option<usize> {
 
     fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option<usize> {
-
         // GNU's memrchr() will - unlike memchr() - error if haystack is empty.
         if haystack.is_empty() {return None}
         let p = unsafe {
diff --git a/sgx_trts/src/memeq.rs b/sgx_trts/src/memeq.rs
index 4388014..f52e624 100644
--- a/sgx_trts/src/memeq.rs
+++ b/sgx_trts/src/memeq.rs
@@ -27,15 +27,12 @@ use alloc::slice;
 
 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) }
 }
 
 impl<T> ConsttimeMemEq<[T]> for [T]
-    where T: Eq + BytewiseEquality
-{
+    where T: Eq + BytewiseEquality {
     fn consttime_memeq(&self, other: &[T]) -> bool {
-
         if self.len() != other.len() {
             return false;
         }
@@ -43,37 +40,40 @@ impl<T> ConsttimeMemEq<[T]> for [T]
             return true;
         }
         let size = mem::size_of_val(self);
-        consttime_memequal(self.as_ptr() as * const u8,
-                           other.as_ptr() as * const u8,
-                           size) != 0
+        unsafe {
+            consttime_memequal(self.as_ptr() as *const u8,
+                               other.as_ptr() as *const u8,
+                               size) != 0
+        }
     }
 }
 
 impl<T> ConsttimeMemEq<T> for T
-    where T: Eq + BytewiseEquality
-{
+    where T: Eq + BytewiseEquality {
     fn consttime_memeq(&self, other: &T) -> bool {
-
         let size = mem::size_of_val(self);
         if size == 0 {
             return true;
         }
-        consttime_memequal(self as * const T as * const u8,
-                           other as * const T as * const u8,
-                           size) != 0
+        unsafe {
+            consttime_memequal(self as *const T as *const u8,
+                               other as *const T as *const u8,
+                               size) != 0
+        }
     }
 }
 
-fn consttime_memequal(b1: * const u8, b2: * const u8, l: usize) -> i32
-{
-    let mut res: i32 = 0;
+unsafe fn consttime_memequal(b1: *const u8,
+                             b2: *const u8,
+                             l: usize) -> i32 {
+    let mut res: u32 = 0;
     let mut len = l;
-    let p1 = unsafe { slice::from_raw_parts(b1, l) };
-    let p2 = unsafe { slice::from_raw_parts(b2, l) };
+    let p1 = slice::from_raw_parts(b1, l);
+    let p2 = slice::from_raw_parts(b2, l);
 
     while len > 0 {
         len -= 1;
-        res |= i32::from(p1[len] ^ p2[len]);
+        res |= (p1[len] ^ p2[len]) as u32;
     }
     /*
      * Map 0 to 1 and [1, 256) to 0 using only constant-time
@@ -84,5 +84,5 @@ fn consttime_memequal(b1: * const u8, b2: * const u8, l: usize) -> i32
      * advantage of them, certain compilers generate branches on
      * certain CPUs for `!res'.
      */
-    (1 & ((res - 1) >> 8))
+    (1 & ((res - 1) >> 8)) as i32
 }
diff --git a/sgx_trts/src/oom.rs b/sgx_trts/src/oom.rs
index c63278e..e09a8dc 100644
--- a/sgx_trts/src/oom.rs
+++ b/sgx_trts/src/oom.rs
@@ -20,7 +20,7 @@ use core::sync::atomic::{AtomicPtr, Ordering};
 use core::mem;
 use core::alloc::AllocErr;
 
-static SGX_OOM_HANDLER: AtomicPtr<()> = AtomicPtr::new(default_oom_handler as * mut ());
+static SGX_OOM_HANDLER: AtomicPtr<()> = AtomicPtr::new(default_oom_handler as *mut ());
 
 #[allow(clippy::needless_pass_by_value)]
 fn default_oom_handler( _err: AllocErr) -> ! {
@@ -38,5 +38,5 @@ pub fn rsgx_oom(err: AllocErr) -> ! {
 /// To avoid recursive OOM failures, it is critical that the OOM handler does
 /// not allocate any memory itself.
 pub fn set_panic_handler(handler: fn(AllocErr) -> !) {
-    SGX_OOM_HANDLER.store(handler as * mut (), Ordering::SeqCst);
+    SGX_OOM_HANDLER.store(handler as *mut (), Ordering::SeqCst);
 }
diff --git a/sgx_trts/src/trts.rs b/sgx_trts/src/trts.rs
index b8e304c..5095996 100644
--- a/sgx_trts/src/trts.rs
+++ b/sgx_trts/src/trts.rs
@@ -18,6 +18,7 @@
 use sgx_types::*;
 use sgx_types::marker::ContiguousMemory;
 use core::mem;
+use crate::libc;
 
 ///
 /// rsgx_read_rand function is used to generate a random number inside the enclave.
@@ -51,7 +52,6 @@ use core::mem;
 /// Indicates an unexpected error occurs during the valid random number generation process.
 ///
 pub fn rsgx_read_rand(rand: &mut [u8]) -> SgxError {
-
     let ret = unsafe { sgx_read_rand(rand.as_mut_ptr(), rand.len()) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -64,8 +64,7 @@ pub fn rsgx_read_rand(rand: &mut [u8]) -> SgxError {
 ///
 #[inline]
 pub fn rsgx_data_is_within_enclave<T: Copy + ContiguousMemory>(data: &T) -> bool {
-
-    rsgx_raw_is_within_enclave(data as * const _ as * const u8, mem::size_of::<T>())
+    rsgx_raw_is_within_enclave(data as *const _ as *const u8, mem::size_of::<T>())
 }
 
 ///
@@ -73,8 +72,7 @@ pub fn rsgx_data_is_within_enclave<T: Copy + ContiguousMemory>(data: &T) -> bool
 ///
 #[inline]
 pub fn rsgx_slice_is_within_enclave<T: Copy + ContiguousMemory>(data: &[T]) -> bool {
-
-    rsgx_raw_is_within_enclave(data.as_ptr() as * const u8, mem::size_of_val(data))
+    rsgx_raw_is_within_enclave(data.as_ptr() as *const u8, mem::size_of_val(data))
 }
 
 ///
@@ -114,9 +112,8 @@ pub fn rsgx_slice_is_within_enclave<T: Copy + ContiguousMemory>(data: &[T]) -> b
 ///
 /// The whole buffer or part of the buffer is not within the enclave, or the buffer is wrapped around.
 ///
-pub fn rsgx_raw_is_within_enclave(addr: * const u8, size: usize) -> bool {
-
-    let ret = unsafe { sgx_is_within_enclave(addr as * const c_void, size) };
+pub fn rsgx_raw_is_within_enclave(addr: *const u8, size: usize) -> bool {
+    let ret = unsafe { sgx_is_within_enclave(addr as *const c_void, size) };
     ret != 0
 }
 
@@ -125,8 +122,7 @@ pub fn rsgx_raw_is_within_enclave(addr: * const u8, size: usize) -> bool {
 ///
 #[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>())
 }
 
 ///
@@ -134,8 +130,7 @@ pub fn rsgx_data_is_outside_enclave<T: Copy + ContiguousMemory>(data: &T) -> boo
 ///
 #[inline]
 pub fn rsgx_slice_is_outside_enclave<T: Copy + ContiguousMemory>(data: &[T]) -> bool {
-
-    rsgx_raw_is_outside_enclave(data.as_ptr() as * const u8, mem::size_of_val(data))
+    rsgx_raw_is_outside_enclave(data.as_ptr() as *const u8, mem::size_of_val(data))
 }
 
 ///
@@ -173,33 +168,24 @@ pub fn rsgx_slice_is_outside_enclave<T: Copy + ContiguousMemory>(data: &[T]) ->
 ///
 /// The whole buffer or part of the buffer is not outside the enclave, or the buffer is wrapped around.
 ///
-pub fn rsgx_raw_is_outside_enclave(addr: * const u8, size: usize) -> bool {
-
-    let ret = unsafe { sgx_is_outside_enclave(addr as * const c_void, size) };
+pub fn rsgx_raw_is_outside_enclave(addr: *const u8, size: usize) -> bool {
+    let ret = unsafe { sgx_is_outside_enclave(addr as *const c_void, size) };
     ret != 0
 }
 
 pub fn rsgx_is_enclave_crashed() -> bool {
-
     let ret = unsafe { sgx_is_enclave_crashed() };
     ret != 0
 }
 
-pub type exit_function_t = extern "C" fn();
-
-#[link(name = "sgx_trts")]
-extern {
-    pub fn abort() -> !;
-    pub fn atexit(fun: exit_function_t) -> c_int;
-}
+pub use libc::exit_function_t;
 
 pub fn rsgx_abort() -> ! {
-    unsafe { abort() }
+    unsafe { libc::abort() }
 }
 
 pub fn rsgx_atexit(fun: exit_function_t) -> bool {
-
-    let ret = unsafe { atexit(fun) };
+    let ret = unsafe { libc::atexit(fun) };
     ret >= 0
 }
 
diff --git a/sgx_trts/src/veh.rs b/sgx_trts/src/veh.rs
index b321d1b..83b1a2f 100644
--- a/sgx_trts/src/veh.rs
+++ b/sgx_trts/src/veh.rs
@@ -17,7 +17,7 @@
 
 use sgx_types::*;
 
-pub type exception_handle = * const c_void;
+pub type exception_handle = *const c_void;
 
 ///
 /// rsgx_register_exception_handler registers an exception handler.
@@ -66,12 +66,14 @@ pub type exception_handle = * const c_void;
 /// 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)
     };
-
-    if handle.is_null() { None } else { Some(handle) }
+    if handle.is_null() {
+        None
+    } else {
+        Some(handle)
+    }
 }
 
 ///
@@ -105,7 +107,6 @@ pub fn rsgx_register_exception_handler(is_first_handler: u32, exception_handler:
 /// The exception handler was not unregistered (not a valid pointer, handler not found).
 ///
 pub fn rsgx_unregister_exception_handler(handle: exception_handle) -> bool {
-
     let ret = unsafe { sgx_unregister_exception_handler(handle) };
     ret != 0
 }
diff --git a/sgx_tse/Cargo.toml b/sgx_tse/Cargo.toml
index d2e427c..a0b2162 100644
--- a/sgx_tse/Cargo.toml
+++ b/sgx_tse/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tse"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tse/src/lib.rs b/sgx_tse/src/lib.rs
index 6d5b08b..2fdba39 100644
--- a/sgx_tse/src/lib.rs
+++ b/sgx_tse/src/lib.rs
@@ -23,13 +23,8 @@
 #![no_std]
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
 #![allow(non_camel_case_types)]
-#![feature(ptr_internals)]
-#![feature(dropck_eyepatch)]
 
-extern crate alloc;
 extern crate sgx_types;
 
 mod se;
 pub use self::se::*;
-pub mod alignalloc;
-pub mod alignbox;
diff --git a/sgx_tse/src/se.rs b/sgx_tse/src/se.rs
index 687b018..e10950d 100644
--- a/sgx_tse/src/se.rs
+++ b/sgx_tse/src/se.rs
@@ -77,9 +77,9 @@ use sgx_types::*;
 pub fn rsgx_create_report(target_info: &sgx_target_info_t, report_data: &sgx_report_data_t) -> SgxResult<sgx_report_t> {
     let mut report = sgx_report_t::default();
     let ret = unsafe {
-        sgx_create_report(target_info as * const sgx_target_info_t,
-                          report_data as * const sgx_report_data_t,
-                          &mut report as * mut sgx_report_t)
+        sgx_create_report(target_info as *const sgx_target_info_t,
+                          report_data as *const sgx_report_data_t,
+                          &mut report as *mut sgx_report_t)
 
     };
     match ret {
@@ -124,7 +124,7 @@ pub fn rsgx_create_report(target_info: &sgx_target_info_t, report_data: &sgx_rep
 /// Indicates an unexpected error occurs during the report verification process.
 ///
 pub fn rsgx_verify_report(report: &sgx_report_t) -> SgxError {
-    let ret = unsafe { sgx_verify_report(report as * const sgx_report_t) };
+    let ret = unsafe { sgx_verify_report(report as *const sgx_report_t) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
         _ => Err(ret),
@@ -192,7 +192,7 @@ pub fn rsgx_verify_report(report: &sgx_report_t) -> SgxError {
 ///
 pub fn rsgx_get_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_key_128bit_t> {
     let mut key = sgx_key_128bit_t::default();
-    let ret = unsafe { sgx_get_key(key_request as * const sgx_key_request_t, &mut key as * mut sgx_key_128bit_t) };
+    let ret = unsafe { sgx_get_key(key_request as *const sgx_key_request_t, &mut key as *mut sgx_key_128bit_t) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(key),
         _ => Err(ret),
@@ -201,7 +201,7 @@ pub fn rsgx_get_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_key_128bit
 
 pub fn rsgx_get_align_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_align_key_128bit_t> {
     let mut align_key = sgx_align_key_128bit_t::default();
-    let ret = unsafe { sgx_get_key(key_request as * const sgx_key_request_t, &mut align_key.key as * mut sgx_key_128bit_t) };
+    let ret = unsafe { sgx_get_key(key_request as *const sgx_key_request_t, &mut align_key.key as *mut sgx_key_128bit_t) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(align_key),
         _ => Err(ret),
diff --git a/sgx_tseal/Cargo.toml b/sgx_tseal/Cargo.toml
index ba71a0d..5ac6ace 100644
--- a/sgx_tseal/Cargo.toml
+++ b/sgx_tseal/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "sgx_tseal"
-version = "1.1.0"
+version = "1.1.1"
 authors = ["The Teaclave Authors"]
 repository = "https://github.com/apache/teaclave-sgx-sdk"
 license-file = "LICENSE"
diff --git a/sgx_tseal/src/aad.rs b/sgx_tseal/src/aad.rs
index 66054e9..40f236b 100644
--- a/sgx_tseal/src/aad.rs
+++ b/sgx_tseal/src/aad.rs
@@ -105,7 +105,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
             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);
@@ -188,7 +188,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
             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,
@@ -255,14 +255,14 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
 
         self.inner.unmac_aadata().map(|x| {
             let ptr = Box::into_raw(x.additional);
-            unsafe{Box::from_raw(ptr as * mut T)}
+            unsafe{Box::from_raw(ptr as *mut T)}
         })
     }
 
     ///
     /// Convert a pointer of sgx_sealed_data_t buffer to SgxMacAadata.
     ///
-    pub unsafe fn from_raw_sealed_data_t(p: * mut sgx_sealed_data_t, len: u32) -> Option<Self> {
+    pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
 
         let size = mem::size_of::<T>();
         if size == 0 {
@@ -287,7 +287,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
     ///
     /// # Error
     ///
-    /// **Some(* mut sgx_sealed_data_t)**
+    /// **Some(*mut sgx_sealed_data_t)**
     ///
     /// Indicates the conversion is successfully. The return value is the pointer of sgx_sealed_data_t.
     ///
@@ -295,7 +295,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, T> {
     ///
     /// 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)
     }
 }
@@ -313,7 +313,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
             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)
+            slice::from_raw_parts(additional_text.as_ptr() as *const u8, len)
         };
 
         let result = SgxInternalSealedData::mac_aadata(aad_slice);
@@ -335,7 +335,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
             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)
+            slice::from_raw_parts(additional_text.as_ptr() as *const u8, len)
         };
         let result = SgxInternalSealedData::mac_aadata_ex(key_policy,
                                                           attribute_mask,
@@ -364,7 +364,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
             let ptr = Box::into_raw(x.additional);
             unsafe {
                 let slice = slice::from_raw_parts_mut(ptr as *mut T, aad_len/size);
-                Box::from_raw(slice as * mut [T])
+                Box::from_raw(slice as *mut [T])
             }
         })
     }
@@ -372,7 +372,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
     ///
     /// Convert a pointer of sgx_sealed_data_t buffer to SgxMacAadata.
     ///
-    pub unsafe fn from_raw_sealed_data_t(p: * mut sgx_sealed_data_t, len: u32) -> Option<Self> {
+    pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
 
         let size = mem::size_of::<T>();
         if size == 0 {
@@ -397,7 +397,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
     ///
     /// # Error
     ///
-    /// **Some(* mut sgx_sealed_data_t)**
+    /// **Some(*mut sgx_sealed_data_t)**
     ///
     /// Indicates the conversion is successfully. The return value is the pointer of sgx_sealed_data_t.
     ///
@@ -405,7 +405,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxMacAadata<'a, [T]> {
     ///
     /// 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)
     }
 }
diff --git a/sgx_tseal/src/internal.rs b/sgx_tseal/src/internal.rs
index 6a257e0..4101df9 100644
--- a/sgx_tseal/src/internal.rs
+++ b/sgx_tseal/src/internal.rs
@@ -25,7 +25,7 @@ use alloc::boxed::Box;
 use alloc::vec::Vec;
 
 /* 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 {
@@ -131,13 +131,13 @@ impl SgxInternalSealedData {
         }
     }
 
-    pub unsafe fn to_raw_sealed_data_t(&self, p: * mut sgx_sealed_data_t, len: u32) -> Option<* mut sgx_sealed_data_t> {
+    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;
         }
 
@@ -178,13 +178,13 @@ impl SgxInternalSealedData {
     }
 
     #[allow(clippy::cast_ptr_alignment)]
-    pub unsafe fn from_raw_sealed_data_t(p: * mut sgx_sealed_data_t, len: u32) -> Option<Self> {
+    pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
 
         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;
         }
 
@@ -197,9 +197,9 @@ impl SgxInternalSealedData {
             return None;
         }
 
-        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);
+        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()) {
             return None;
         }
@@ -220,7 +220,7 @@ impl SgxInternalSealedData {
         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()
@@ -230,7 +230,7 @@ impl SgxInternalSealedData {
             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()
@@ -356,7 +356,7 @@ impl SgxInternalSealedData {
         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()) {
@@ -472,7 +472,7 @@ impl SgxInternalSealedData {
             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()) {
diff --git a/sgx_tseal/src/seal.rs b/sgx_tseal/src/seal.rs
index aefd29c..c96d888 100644
--- a/sgx_tseal/src/seal.rs
+++ b/sgx_tseal/src/seal.rs
@@ -188,7 +188,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
             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| {
@@ -284,7 +284,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
             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,
@@ -361,7 +361,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
             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,
             }
@@ -395,7 +395,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
     ///
     /// Maybe the size of T is zero.
     ///
-    pub unsafe fn from_raw_sealed_data_t(p: * mut sgx_sealed_data_t, len: u32) -> Option<Self> {
+    pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
 
         let size = mem::size_of::<T>();
         if size == 0 {
@@ -424,7 +424,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
     ///
     /// # Error
     ///
-    /// **Some(* mut sgx_sealed_data_t)**
+    /// **Some(*mut sgx_sealed_data_t)**
     ///
     /// Indicates the conversion is successfully. The return value is the pointer of sgx_sealed_data_t.
     ///
@@ -432,7 +432,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, T> {
     ///
     /// 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)
     }
 }
@@ -505,7 +505,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
             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)
+            slice::from_raw_parts(encrypt_text.as_ptr() as *const u8, len)
         };
 
         let result = SgxInternalSealedData::seal_data(additional_text, encrypt_slice);
@@ -603,7 +603,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
             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)
+            slice::from_raw_parts(encrypt_text.as_ptr() as *const u8, len)
         };
 
         let result = SgxInternalSealedData::seal_data_ex(key_policy,
@@ -683,10 +683,10 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
 
         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,
             }
@@ -720,7 +720,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
     ///
     /// Maybe the size of T is zero.
     ///
-    pub unsafe fn from_raw_sealed_data_t(p: * mut sgx_sealed_data_t, len: u32) -> Option<Self> {
+    pub unsafe fn from_raw_sealed_data_t(p: *mut sgx_sealed_data_t, len: u32) -> Option<Self> {
 
         let size = mem::size_of::<T>();
         if size == 0 {
@@ -749,7 +749,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
     ///
     /// # Error
     ///
-    /// **Some(* mut sgx_sealed_data_t)**
+    /// **Some(*mut sgx_sealed_data_t)**
     ///
     /// Indicates the conversion is successfully. The return value is the pointer of sgx_sealed_data_t.
     ///
@@ -757,7 +757,7 @@ impl<'a, T: 'a + Copy + ContiguousMemory> SgxSealedData<'a, [T]> {
     ///
     /// 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)
     }
 }
diff --git a/sgx_tservice/Cargo.toml b/sgx_tservice/Cargo.toml
deleted file mode 100644
index fa0f4b0..0000000
--- a/sgx_tservice/Cargo.toml
+++ /dev/null
@@ -1,19 +0,0 @@
-[package]
-name = "sgx_tservice"
-version = "1.1.0"
-authors = ["The Teaclave Authors"]
-repository = "https://github.com/apache/teaclave-sgx-sdk"
-license-file = "LICENSE"
-documentation = "https://dingelish.github.io/"
-description = "Rust SGX SDK provides the ability to write Intel SGX applications in Rust Programming Language."
-edition = "2018"
-
-[lib]
-name = "sgx_tservice"
-crate-type = ["rlib"]
-
-[features]
-default = []
-
-[target.'cfg(not(target_env = "sgx"))'.dependencies]
-sgx_types = { path = "../sgx_types" }
diff --git a/sgx_tservice/src/lib.rs b/sgx_tservice/src/lib.rs
deleted file mode 100644
index 40a819e..0000000
--- a/sgx_tservice/src/lib.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License..
-
-//! # Trust Service Library
-//!
-//! The Intel(R) Software Guard Extensions SDK provides a trusted library named
-//! sgx_tservice for secure data manipulation and protection. The sgx_tservice library
-//! provides the following modules:
-//!
-//! **Trust Platform Service Functions**
-//!
-
-#![no_std]
-#![allow(non_camel_case_types)]
-#![cfg_attr(target_env = "sgx", feature(rustc_private))]
-
-extern crate sgx_types;
-
-pub mod sgxtime;
-pub mod sgxcounter;
-
-mod tae;
-pub use self::tae::*;
-
diff --git a/sgx_tservice/src/sgxcounter.rs b/sgx_tservice/src/sgxcounter.rs
deleted file mode 100644
index 0b537ce..0000000
--- a/sgx_tservice/src/sgxcounter.rs
+++ /dev/null
@@ -1,551 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License..
-
-use sgx_types::*;
-use core::cell::Cell;
-
-/// Monotonic counter ID
-pub struct SgxMonotonicCounter {
-    counter_uuid: sgx_mc_uuid_t,
-    initflag: Cell<bool>,
-}
-
-impl SgxMonotonicCounter {
-
-    ///
-    /// Rebuild a SgxMonotonicCounter from an existing uuid. Caller is responsible for the uuid.
-    ///
-    pub fn from_uuid(id: sgx_mc_uuid_t) -> Self {
-        SgxMonotonicCounter {
-            counter_uuid: id,
-            initflag: Cell::new(true),
-        }
-    }
-
-    ///
-    /// Dump the uuid of an existing SGX monotonic counter
-    ///
-    pub fn get_uuid(&self) -> Option<sgx_mc_uuid_t> {
-        if self.initflag.get() {
-            Some(self.counter_uuid)
-        } else {
-            None
-        }
-    }
-
-    ///
-    /// creates a monotonic counter with default owner policy and default user attribute mask.
-    ///
-    /// # Description
-    ///
-    /// Call new to create a monotonic counter with the default owner policy 0x1, which means enclaves
-    /// with same signing key can access the monotonic counter and default owner_attribute_mask 0xFFFFFFFFFFFFFFCB.
-    ///
-    /// The caller should call rsgx_create_pse_session to establish a session with the platform service enclave
-    /// before calling this API.
-    ///
-    /// Creating a monotonic counter (MC) involves writing to the non-volatile memory available in the platform.
-    /// Repeated write operations could cause the memory to wear out during the normal lifecycle of the platform.
-    /// Intel(R) SGX prevents this by limiting the rate at which MC operations can be performed. If you exceed
-    /// the limit, the MC operation may return SGX_ERROR_BUSY for several minutes.
-    ///
-    /// Intel(R) SGX limits the number of MCs an enclave can create. To avoid exhausting the available quota,
-    /// an SGX application should record the MC UUID that rsgx_create_monotonic_counter returns and destroy a MC
-    /// when it is not needed any more. If an enclave reaches its quota and previously created MC UUIDs have not
-    /// been recorded, you may restore the MC service after uninstalling the SGX PSW and installing it again.
-    /// This procedure deletes all MCs created by any enclave in that system.
-    ///
-    /// # Parameters
-    ///
-    /// **counter_value**
-    ///
-    /// A pointer to the buffer that receives the monotonic counter value.
-    ///
-    /// # Requirements
-    ///
-    /// Header: sgx_tae_service.edl
-    ///
-    /// Library: libsgx_tservice.a
-    ///
-    /// # Return value
-    ///
-    /// Monotonic counter ID
-    ///
-    /// # Errors
-    ///
-    /// **SGX_ERROR_INVALID_PARAMETER**
-    ///
-    /// Any of the pointers is invalid.
-    ///
-    /// **SGX_ERROR_BUSY**
-    ///
-    /// The requested service is temporarily not available.
-    ///
-    /// **SGX_ERROR_MC_OVER_QUOTA**
-    ///
-    /// The enclave has reached the quota of Monotonic Counters it can maintain.
-    ///
-    /// **SGX_ERROR_MC_USED_UP**
-    ///
-    /// Monotonic counters are used out.
-    ///
-    /// **SGX_ERROR_AE_SESSION_INVALID**
-    ///
-    /// Session is not created or has been closed by architectural enclave service.
-    ///
-    /// **SGX_ERROR_SERVICE_UNAVAILABLE**
-    ///
-    /// The AE service did not respond or the requested service is not supported.
-    ///
-    /// **SGX_ERROR_SERVICE_TIMEOUT**
-    ///
-    /// A request to the AE service timed out.
-    ///
-    /// **SGX_ERROR_NETWORK_FAILURE**
-    ///
-    /// Network connecting or proxy setting issue was encountered.
-    ///
-    /// **SGX_ERROR_OUT_OF_MEMORY**
-    ///
-    /// Not enough memory is available to complete this operation.
-    ///
-    /// **SGX_ERROR_OUT_OF_EPC**
-    ///
-    /// There is not enough EPC memory to load one of the Architecture Enclaves needed to complete this operation.
-    ///
-    /// **SGX_ERROR_UNEXPECTED**
-    ///
-    /// Indicates an unexpected error occurs.
-    ///
-    pub fn new(counter_value: &mut u32) -> SgxResult<Self> {
-
-        let mut counter_uuid = sgx_mc_uuid_t::default();
-        let ret = rsgx_create_monotonic_counter(&mut counter_uuid, counter_value);
-
-        match ret {
-            sgx_status_t::SGX_SUCCESS => Ok(SgxMonotonicCounter{
-                                            counter_uuid,
-                                            initflag: Cell::new(true),
-                                         }),
-            _ => Err(ret),
-        }
-    }
-
-    ///
-    /// creates a monotonic counter.
-    ///
-    /// # Description
-    ///
-    /// Call new_ex to create a monotonic counter with the given owner_policy and owner_attribute_mask.
-    ///
-    /// The caller should call rsgx_create_pse_session to establish a session with the platform service enclave
-    /// before calling this API.
-    ///
-    /// Creating a monotonic counter (MC) involves writing to the non-volatile memory available in the platform.
-    /// Repeated write operations could cause the memory to wear out during the normal lifecycle of the platform.
-    /// Intel(R) SGX prevents this by limiting the rate at which MC operations can be performed. If you exceed
-    /// the limit, the MC operation may return SGX_ERROR_BUSY for several minutes.
-    ///
-    /// Intel(R) SGX limits the number of MCs an enclave can create. To avoid exhausting the available quota,
-    /// an SGX application should record the MC UUID that rsgx_create_monotonic_counter_ex returns and destroy a MC
-    /// when it is not needed any more. If an enclave reaches its quota and previously created MC UUIDs have not
-    /// been recorded, you may restore the MC service after uninstalling the SGX PSW and installing it again.
-    /// This procedure deletes all MCs created by any enclave in that system.
-    ///
-    /// # Parameters
-    ///
-    /// **owner_policy**
-    ///
-    /// The owner policy of the monotonic counter.
-    ///
-    /// * 0x1 means enclave with same signing key can access the monotonic counter
-    /// * 0x2 means enclave with same measurement can access the monotonic counter
-    /// * 0x3 means enclave with same measurement as well as signing key can access the monotonic counter.
-    /// * Owner policy values of 0x0 or any bits set beyond bits 0 and 1 will cause SGX_ERROR_INVALID_PARAMETER
-    ///
-    /// **owner_attribute_mask**
-    ///
-    /// Mask of owner attribute, in the format of sgx_attributes_t.
-    ///
-    /// **counter_value**
-    ///
-    /// A pointer to the buffer that receives the monotonic counter value.
-    ///
-    /// # Requirements
-    ///
-    /// Header: sgx_tae_service.edl
-    ///
-    /// Library: libsgx_tservice.a
-    ///
-    /// # Return value
-    ///
-    /// Monotonic counter ID
-    ///
-    /// # Errors
-    ///
-    /// **SGX_ERROR_INVALID_PARAMETER**
-    ///
-    /// Any of the pointers is invalid.
-    ///
-    /// **SGX_ERROR_BUSY**
-    ///
-    /// The requested service is temporarily not available.
-    ///
-    /// **SGX_ERROR_MC_OVER_QUOTA**
-    ///
-    /// The enclave has reached the quota of Monotonic Counters it can maintain.
-    ///
-    /// **SGX_ERROR_MC_USED_UP**
-    ///
-    /// Monotonic counters are used out.
-    ///
-    /// **SGX_ERROR_AE_SESSION_INVALID**
-    ///
-    /// Session is not created or has been closed by architectural enclave service.
-    ///
-    /// **SGX_ERROR_SERVICE_UNAVAILABLE**
-    ///
-    /// The AE service did not respond or the requested service is not supported.
-    ///
-    /// **SGX_ERROR_SERVICE_TIMEOUT**
-    ///
-    /// A request to the AE service timed out.
-    ///
-    /// **SGX_ERROR_NETWORK_FAILURE**
-    ///
-    /// Network connecting or proxy setting issue was encountered.
-    ///
-    /// **SGX_ERROR_OUT_OF_MEMORY**
-    ///
-    /// Not enough memory is available to complete this operation.
-    ///
-    /// **SGX_ERROR_OUT_OF_EPC**
-    ///
-    /// There is not enough EPC memory to load one of the Architecture Enclaves needed to complete this operation.
-    ///
-    /// **SGX_ERROR_UNEXPECTED**
-    ///
-    /// Indicates an unexpected error occurs.
-    ///
-    pub fn new_ex(owner_policy: u16, owner_attribute_mask: &sgx_attributes_t, counter_value: &mut u32) -> SgxResult<Self> {
-
-        let mut counter_uuid = sgx_mc_uuid_t::default();
-        let ret = rsgx_create_monotonic_counter_ex(owner_policy, owner_attribute_mask, &mut counter_uuid, counter_value);
-
-        match ret {
-            sgx_status_t::SGX_SUCCESS => Ok(SgxMonotonicCounter{
-                                            counter_uuid,
-                                            initflag: Cell::new(true),
-                                         }),
-            _ => Err(ret),
-        }
-    }
-
-    ///
-    /// destroys a monotonic counter created by new or new_ex.
-    ///
-    /// # Description
-    ///
-    /// Calling destory after a monotonic counter is not needed anymore.
-    ///
-    /// The caller should call rsgx_create_pse_session to establish a session with the platform service enclave
-    /// before calling this API.
-    ///
-    /// destory fails if the calling enclave does not match the owner policy and the attributes specified in the
-    /// call that created the monotonic counter.
-    ///
-    /// Destroying a Monotonic Counter (MC) involves writing to the non-volatile memory available in the platform.
-    /// Repeated write operations could cause the memory to wear out during the normal lifecycle of the platform.
-    /// Intel(R) SGX prevents this by limiting the rate at which MC operations can be performed. If you exceed the
-    /// limit, the MC operation may return SGX_ERROR_BUSY for several minutes.
-    ///
-    /// # Requirements
-    ///
-    /// Header: sgx_tae_service.edl
-    ///
-    /// Library: libsgx_tservice.a
-    ///
-    /// # Errors
-    ///
-    /// **SGX_ERROR_INVALID_PARAMETER**
-    ///
-    /// Any of the pointers is invalid.
-    ///
-    /// **SGX_ERROR_BUSY**
-    ///
-    /// The requested service is temporarily not available.
-    ///
-    /// **SGX_ERROR_MC_NOT_FOUND**
-    ///
-    /// The Monotonic Counter does not exist or has been invalidated.
-    ///
-    /// **SGX_ERROR_MC_NO_ACCESS_RIGHT**
-    ///
-    /// The enclave doesn't have the access right to specified Monotonic Counter.
-    ///
-    /// **SGX_ERROR_AE_SESSION_INVALID**
-    ///
-    /// Session is not created or has been closed by architectural enclave service.
-    ///
-    /// **SGX_ERROR_SERVICE_UNAVAILABLE**
-    ///
-    /// The AE service did not respond or the requested service is not supported.
-    ///
-    /// **SGX_ERROR_SERVICE_TIMEOUT**
-    ///
-    /// A request to the AE service timed out.
-    ///
-    /// **SGX_ERROR_NETWORK_FAILURE**
-    ///
-    /// Network connecting or proxy setting issue was encountered.
-    ///
-    /// **SGX_ERROR_OUT_OF_MEMORY**
-    ///
-    /// Not enough memory is available to complete this operation.
-    ///
-    /// **SGX_ERROR_OUT_OF_EPC**
-    ///
-    /// There is not enough EPC memory to load one of the Architecture Enclaves needed to complete this operation.
-    ///
-    /// **SGX_ERROR_UNEXPECTED**
-    ///
-    /// Indicates an unexpected error occurs.
-    ///
-    pub fn destory(&self) -> SgxError {
-
-        if !self.initflag.get() {
-            return Err(sgx_status_t::SGX_ERROR_MC_NOT_FOUND);
-        }
-
-        let ret = rsgx_destroy_monotonic_counter(&self.counter_uuid);
-        if ret == sgx_status_t::SGX_SUCCESS {
-            self.initflag.set(false);
-            Ok(())
-        } else {
-            Err(ret)
-        }
-    }
-
-    ///
-    /// increments a monotonic counter value by 1.
-    ///
-    /// # Description
-    ///
-    /// Call increment to increase a monotonic counter value by 1.
-    ///
-    /// The caller should call rsgx_create_pse_session to establish a session with the platform service enclave
-    /// before calling this API.
-    ///
-    /// increment fails if the calling enclave does not match the owner policy and the attributes specified in the
-    /// call that created the monotonic counter.
-    ///
-    /// Incrementing a monotonic counter (MC) involves writing to the non-volatile memory available in the platform.
-    /// Repeated write operations could cause the memory to wear out during the normal lifecycle of the platform.
-    /// Intel(R) SGX prevents this by limiting the rate at which MC operations can be performed. If you exceed the limit,
-    /// the MC operation may return SGX_ERROR_BUSY for several minutes.
-    ///
-    /// # Requirements
-    ///
-    /// Header: sgx_tae_service.edl
-    ///
-    /// Library: libsgx_tservice.a
-    ///
-    /// # Errors
-    ///
-    /// **SGX_ERROR_INVALID_PARAMETER**
-    ///
-    /// Any of the pointers is invalid.
-    ///
-    /// **SGX_ERROR_BUSY**
-    ///
-    /// The requested service is temporarily not available.
-    ///
-    /// **SGX_ERROR_MC_NOT_FOUND**
-    ///
-    /// The Monotonic Counter does not exist or has been invalidated.
-    ///
-    /// **SGX_ERROR_MC_NO_ACCESS_RIGHT**
-    ///
-    /// The enclave doesn't have the access right to specified Monotonic Counter.
-    ///
-    /// **SGX_ERROR_AE_SESSION_INVALID**
-    ///
-    /// Session is not created or has been closed by architectural enclave service.
-    ///
-    /// **SGX_ERROR_SERVICE_UNAVAILABLE**
-    ///
-    /// The AE service did not respond or the requested service is not supported.
-    ///
-    /// **SGX_ERROR_SERVICE_TIMEOUT**
-    ///
-    /// A request to the AE service timed out.
-    ///
-    /// **SGX_ERROR_NETWORK_FAILURE**
-    ///
-    /// Network connecting or proxy setting issue was encountered.
-    ///
-    /// **SGX_ERROR_OUT_OF_MEMORY**
-    ///
-    /// Not enough memory is available to complete this operation.
-    ///
-    /// **SGX_ERROR_OUT_OF_EPC**
-    ///
-    /// There is not enough EPC memory to load one of the Architecture Enclaves needed to complete this operation.
-    ///
-    /// **SGX_ERROR_UNEXPECTED**
-    ///
-    /// Indicates an unexpected error occurs.
-    ///
-    pub fn increment(&self) -> SgxResult<u32> {
-
-        if !self.initflag.get() {
-            return Err(sgx_status_t::SGX_ERROR_MC_NOT_FOUND);
-        }
-
-        let mut counter_value: u32 = 0;
-        let ret = rsgx_increment_monotonic_counter(&self.counter_uuid, &mut counter_value);
-         match ret {
-            sgx_status_t::SGX_SUCCESS => Ok(counter_value),
-            _ => Err(ret),
-        }
-    }
-
-    ///
-    /// returns the value of a monotonic counter.
-    ///
-    /// # Description
-    ///
-    /// Call read to read the value of a monotonic counter.
-    ///
-    /// The caller should call rsgx_create_pse_session to establish a session with the platform service enclave
-    /// before calling this API.
-    ///
-    /// read fails if the calling enclave does not match the owner policy and the attributes specified in the
-    /// call that created the monotonic counter.
-    ///
-    /// # Requirements
-    ///
-    /// Header: sgx_tae_service.edl
-    ///
-    /// Library: libsgx_tservice.a
-    ///
-    /// # Return value
-    ///
-    /// Monotonic counter value
-    ///
-    /// # Errors
-    ///
-    /// **SGX_ERROR_INVALID_PARAMETER**
-    ///
-    /// Any of the pointers is invalid.
-    ///
-    /// **SGX_ERROR_MC_NOT_FOUND**
-    ///
-    /// The Monotonic Counter does not exist or has been invalidated.
-    ///
-    /// **SGX_ERROR_AE_SESSION_INVALID**
-    ///
-    /// Session is not created or has been closed by architectural enclave service.
-    ///
-    /// **SGX_ERROR_SERVICE_UNAVAILABLE**
-    ///
-    /// The AE service did not respond or the requested service is not supported.
-    ///
-    /// **SGX_ERROR_SERVICE_TIMEOUT**
-    ///
-    /// A request to the AE service timed out.
-    ///
-    /// **SGX_ERROR_NETWORK_FAILURE**
-    ///
-    /// Network connecting or proxy setting issue was encountered.
-    ///
-    /// **SGX_ERROR_OUT_OF_MEMORY**
-    ///
-    /// Not enough memory is available to complete this operation.
-    ///
-    /// **SGX_ERROR_OUT_OF_EPC**
-    ///
-    /// There is not enough EPC memory to load one of the Architecture Enclaves needed to complete this operation.
-    ///
-    /// **SGX_ERROR_UNEXPECTED**
-    ///
-    /// Indicates an unexpected error occurs.
-    ///
-    pub fn read(&self) -> SgxResult<u32> {
-
-        if !self.initflag.get() {
-            return Err(sgx_status_t::SGX_ERROR_MC_NOT_FOUND);
-        }
-
-        let mut counter_value: u32 = 0;
-        let ret = rsgx_read_monotonic_counter(&self.counter_uuid, &mut counter_value);
-        match ret {
-            sgx_status_t::SGX_SUCCESS => Ok(counter_value),
-            _ => Err(ret),
-        }
-    }
-}
-
-impl Drop for SgxMonotonicCounter {
-    ///
-    /// destroys a monotonic counter created by new or new_ex.
-    ///
-    fn drop(&mut self) {
-        let _ = self.destory();
-    }
-}
-
-fn rsgx_create_monotonic_counter_ex(owner_policy: u16,
-                                    owner_attribute_mask: &sgx_attributes_t,
-                                    counter_uuid: &mut sgx_mc_uuid_t,
-                                    counter_value: &mut u32) -> sgx_status_t {
-
-    unsafe {
-        sgx_create_monotonic_counter_ex(owner_policy,
-                                        owner_attribute_mask as * const sgx_attributes_t,
-                                        counter_uuid as * mut sgx_mc_uuid_t,
-                                        counter_value as * mut u32)
-    }
-}
-
-fn rsgx_create_monotonic_counter(counter_uuid: &mut sgx_mc_uuid_t, counter_value: &mut u32) -> sgx_status_t {
-
-    unsafe {
-        sgx_create_monotonic_counter(counter_uuid as * mut sgx_mc_uuid_t, counter_value as * mut u32)
-    }
-}
-
-fn rsgx_destroy_monotonic_counter(counter_uuid: &sgx_mc_uuid_t) -> sgx_status_t {
-
-    unsafe {
-        sgx_destroy_monotonic_counter(counter_uuid as * const sgx_mc_uuid_t)
-    }
-}
-
-fn rsgx_increment_monotonic_counter(counter_uuid: &sgx_mc_uuid_t, counter_value: &mut u32) -> sgx_status_t {
-
-    unsafe {
-        sgx_increment_monotonic_counter(counter_uuid as * const sgx_mc_uuid_t, counter_value as * mut u32)
-    }
-}
-
-fn rsgx_read_monotonic_counter(counter_uuid: &sgx_mc_uuid_t, counter_value: &mut u32) -> sgx_status_t {
-
-    unsafe {
-        sgx_read_monotonic_counter(counter_uuid as * const sgx_mc_uuid_t, counter_value as * mut u32)
-    }
-}
diff --git a/sgx_tservice/src/sgxtime.rs b/sgx_tservice/src/sgxtime.rs
deleted file mode 100644
index 56ccbff..0000000
--- a/sgx_tservice/src/sgxtime.rs
+++ /dev/null
@@ -1,200 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License..
-
-use sgx_types::*;
-use core::cmp::Ordering;
-use core::fmt;
-
-/// timestamp contains time in seconds and source_nonce contains nonce associate with the time.
-#[derive(Copy, Clone, Debug, Default)]
-pub struct SgxTime {
-    timestamp: sgx_time_t,
-    source_nonce: sgx_time_source_nonce_t,
-}
-
-pub type Duration = sgx_time_t;
-
-pub enum SgxTimeError {
-    TimeStamp(Duration),
-    TimeSourceChanged,
-    SgxStatus(sgx_status_t),
-}
-
-impl SgxTimeError {
-    pub fn __description(&self) -> &str {
-        match *self {
-           SgxTimeError::TimeStamp(_) => "other time was not earlier than self",
-           SgxTimeError::TimeSourceChanged => "time source is changed",
-           SgxTimeError::SgxStatus(ref status) => status.__description(),
-        }
-    }
-}
-
-impl fmt::Display for SgxTimeError {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        match *self {
-           SgxTimeError::TimeStamp(_) => write!(f, "second time provided was later than self"),
-           SgxTimeError::TimeSourceChanged => write!(f, "time source does not match"),
-           SgxTimeError::SgxStatus(status) => status.fmt(f),
-        }
-    }
-}
-
-impl PartialEq for SgxTime {
-    fn eq(&self, other: &SgxTime) -> bool {
-        self.timestamp == other.timestamp && self.source_nonce == other.source_nonce
-    }
-}
-
-impl Eq for SgxTime {}
-
-impl PartialOrd for SgxTime {
-
-    fn partial_cmp(&self, other: &SgxTime) -> Option<Ordering> {
-
-        if self.source_nonce == other.source_nonce {
-            Some(self.timestamp.cmp(&other.timestamp))
-        } else {
-            None
-        }
-    }
-}
-
-impl SgxTime {
-
-    pub fn now() -> Result<SgxTime, SgxTimeError> {
-
-        let mut timestamp: sgx_time_t = 0;
-        let mut source_nonce: sgx_time_source_nonce_t = Default::default();
-
-        let ret = rsgx_get_trusted_time(&mut timestamp, &mut source_nonce);
-        match ret {
-            sgx_status_t::SGX_SUCCESS => Ok(SgxTime{timestamp, source_nonce}),
-            _ => Err(SgxTimeError::SgxStatus(ret)),
-        }
-    }
-
-    pub fn duration_since(&self, earlier: &SgxTime) -> Result<Duration, SgxTimeError> {
-
-        if self.source_nonce == earlier.source_nonce {
-
-            if self.timestamp >= earlier.timestamp {
-                Ok(self.timestamp - earlier.timestamp)
-            } else {
-                Err(SgxTimeError::TimeStamp(earlier.timestamp - self.timestamp))
-            }
-        } else {
-            Err(SgxTimeError::TimeSourceChanged)
-        }
-    }
-
-    pub fn elapsed(&self) -> Result<Duration, SgxTimeError> {
-
-        SgxTime::now().and_then(|t| t.duration_since(self))
-    }
-
-    pub fn add_duration(&self, other: Duration) -> Option<SgxTime> {
-
-        self.timestamp.checked_add(other).map(|secs|
-            SgxTime{ timestamp: secs, source_nonce: self.source_nonce }
-        )
-    }
-
-    pub fn sub_duration(&self, other: Duration) -> Option<SgxTime> {
-
-        self.timestamp.checked_sub(other).map(|secs|
-            SgxTime{ timestamp: secs, source_nonce: self.source_nonce }
-        )
-    }
-
-    pub fn get_secs(&self) -> sgx_time_t { self.timestamp }
-
-    pub fn get_source_nonce(&self) -> sgx_time_source_nonce_t { self.source_nonce }
-}
-
-///
-/// rsgx_get_trusted_time gets trusted time from the AE service.
-///
-/// # Description
-///
-/// current_time contains time in seconds and time_source_nonce contains nonce associate with the time.
-/// The caller should compare time_source_nonce against the value returned from the previous call of
-/// this API if it needs to calculate the time passed between two readings of the Trusted Timer. If the
-/// time_source_nonce of the two readings do not match, the difference between the two readings does not
-/// necessarily reflect time passed.
-///
-/// The caller should call rsgx_create_pse_session to establish a session with the platform service enclave
-/// before calling this API.
-///
-/// # Parameters
-///
-/// **current_time**
-///
-/// Trusted Time Stamp in seconds relative to a reference point. The reference point does not change as long as
-/// the time_source_nonce has not changed.
-///
-/// **time_source_nonce**
-///
-/// A pointer to the buffer that receives the nonce which indicates time source.
-///
-/// # Requirements
-///
-/// Header: sgx_tae_service.edl
-///
-/// Library: libsgx_tservice.a
-///
-/// # Errors
-///
-/// **SGX_ERROR_INVALID_PARAMETER**
-///
-/// Any of the pointers is invalid.
-///
-/// **SGX_ERROR_AE_SESSION_INVALID**
-///
-/// Session is not created or has been closed by architectural enclave service.
-///
-/// **SGX_ERROR_SERVICE_UNAVAILABLE**
-///
-/// The AE service did not respond or the requested service is not supported.
-///
-/// **SGX_ERROR_SERVICE_TIMEOUT**
-///
-/// A request to the AE service timed out.
-///
-/// **SGX_ERROR_NETWORK_FAILURE**
-///
-/// Network connecting or proxy setting issue was encountered.
-///
-/// **SGX_ERROR_OUT_OF_MEMORY**
-///
-/// Not enough memory is available to complete this operation.
-///
-/// **SGX_ERROR_OUT_OF_EPC**
-///
-/// There is not enough EPC memory to load one of the Architecture Enclaves needed to complete this operation.
-///
-/// **SGX_ERROR_UNEXPECTED**
-///
-/// Indicates an unexpected error occurs.
-///
-fn rsgx_get_trusted_time(current_time: &mut sgx_time_t,
-                         time_source_nonce: &mut sgx_time_source_nonce_t) -> sgx_status_t {
-
-    unsafe {
-        sgx_get_trusted_time(current_time as * mut sgx_time_t, time_source_nonce as * mut sgx_time_source_nonce_t)
-    }
-}
diff --git a/sgx_tservice/src/tae.rs b/sgx_tservice/src/tae.rs
deleted file mode 100644
index c32fa4b..0000000
--- a/sgx_tservice/src/tae.rs
+++ /dev/null
@@ -1,201 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License..
-
-//! Trust Platform Service Functions
-//!
-//! The sgx_tservice library provides the following functions that allow an ISV
-//! to use platform services and get platform services security property.
-//!
-use sgx_types::*;
-
-///
-/// rsgx_create_pse_session creates a session with the PSE.
-///
-/// # Description
-///
-/// An Intel(R) SGX enclave first calls rsgx_create_pse_session() in the process to request platform service.
-///
-/// It's suggested that the caller should wait (typically several seconds to tens of seconds) and retry
-/// this API if SGX_ERROR_BUSY is returned.
-///
-/// # Requirements
-///
-/// Header: sgx_tae_service.edl
-///
-/// Library: libsgx_tservice.a
-///
-/// # Errors
-///
-/// **SGX_ERROR_SERVICE_UNAVAILABLE**
-///
-/// The AE service did not respond or the requested service is not supported.
-///
-/// **SGX_ERROR_SERVICE_TIMEOUT**
-///
-/// A request to the AE service timed out.
-///
-/// **SGX_ERROR_BUSY**
-///
-/// The requested service is temporarily not available.
-///
-/// **SGX_ERROR_OUT_OF_MEMORY**
-///
-/// Not enough memory is available to complete this operation.
-///
-/// **SGX_ERROR_NETWORK_FAILURE**
-///
-/// Network connecting or proxy setting issue was encountered.
-///
-/// **SGX_ERROR_OUT_OF_EPC**
-///
-/// There is not enough EPC memory to load one of the Architecture Enclaves needed to complete this operation.
-///
-/// **SGX_ERROR_UPDATE_NEEDED**
-///
-/// Intel(R) SGX needs to be updated.
-///
-/// **SGX_ERROR_UNEXPECTED**
-///
-/// Indicates an unexpected error occurred.
-///
-pub fn rsgx_create_pse_session() -> SgxError {
-
-    let ret = unsafe { sgx_create_pse_session() };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
-    }
-}
-
-///
-/// rsgx_close_pse_session closes a session created by rsgx_create_pse_ session.
-///
-/// # Description
-///
-/// An Intel(R) SGX enclave calls rsgx_close_pse_session() when there is no need to request platform service.
-///
-/// # Requirements
-///
-/// Header: sgx_tae_service.edl
-///
-/// Library: libsgx_tservice.a
-///
-/// # Errors
-///
-/// **SGX_ERROR_SERVICE_UNAVAILABLE**
-///
-/// The AE service did not respond or the requested service is not supported.
-///
-/// **SGX_ERROR_SERVICE_TIMEOUT**
-///
-/// A request to the AE service timed out.
-///
-/// **SGX_ERROR_UNEXPECTED**
-///
-/// Indicates an unexpected error occurs.
-///
-pub fn rsgx_close_pse_session() -> SgxError {
-
-    let ret = unsafe { sgx_close_pse_session() };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
-    }
-}
-
-///
... 28758 lines suppressed ...


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