You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@teaclave.apache.org by GitBox <gi...@apache.org> on 2021/06/10 21:24:37 UTC

[GitHub] [incubator-teaclave] ya0guang opened a new pull request #504: Add WebAssembly Executor Support

ya0guang opened a new pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504


   ## Description
   
   Add support for WebAssembly with embedded WebAssembly Micro Runtime. Also ships with an example of WASM.
   
   Fixes # (issue)
   
   ## Type of change (select or add applied and delete the others)
   
   - [ ] Bug fix (non-breaking change which fixes an issue)
   - [X] New feature (non-breaking change which adds functionality)
   - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
   - [ ] API change with a documentation update
   - [X] Additional test coverage
   - [ ] Code cleanup or just sync with upstream third-party crates
   
   ## How has this been tested?
   
   ## Checklist
   
   - [X] Fork the repo and create your branch from `master`.
   - [X] If you've added code that should be tested, add tests.
   - [ ] If you've changed APIs, update the documentation.
   - [ ] Ensure the tests pass (see CI results).
   - [ ] Make sure your code lints/format.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652134558



##########
File path: executor/src/mesapy.rs
##########
@@ -105,6 +105,7 @@ pub mod tests {
     }
 
     fn test_mesapy() {
+        log::debug!("IN test_mesapy start");

Review comment:
       Delete this debug log.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652170428



##########
File path: examples/webassembly/simple_add.c
##########
@@ -0,0 +1,65 @@
+/*

Review comment:
       `incubator-teaclave/examples/python/wamr_simple_add_payload/simple_add.c`




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] ya0guang commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
ya0guang commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r650194569



##########
File path: third_party/wamr.patch
##########
@@ -0,0 +1,511 @@
+diff --git a/core/shared/platform/teaclave/platform_internal.h b/core/shared/platform/teaclave/platform_internal.h
+new file mode 100644
+index 0000000..83a08f4
+--- /dev/null
++++ b/core/shared/platform/teaclave/platform_internal.h
+@@ -0,0 +1,98 @@
++/*
++ * Copyright (C) 2019 Intel Corporation.  All rights reserved.
++ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
++ */
++
++#ifndef _PLATFORM_INTERNAL_H
++#define _PLATFORM_INTERNAL_H
++
++#include <inttypes.h>
++#include <stdbool.h>
++#include <assert.h>
++#include <time.h>
++#include <string.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <math.h>
++#include <stdarg.h>
++#include <ctype.h>
++#include <pthread.h>
++#include <signal.h>
++#include <semaphore.h>
++#include <limits.h>
++#include <dirent.h>
++#include <fcntl.h>
++#include <unistd.h>
++#include <poll.h>
++#include <sched.h>
++#include <errno.h>
++#include <netinet/in.h>
++#include <sys/types.h>
++#include <sys/stat.h>
++#include <sys/mman.h>
++#include <sys/time.h>
++#include <sys/timeb.h>
++#include <sys/uio.h>
++#include <sys/ioctl.h>
++#include <sys/socket.h>
++#include <sys/resource.h>
++
++#ifdef __cplusplus
++extern "C" {
++#endif
++
++#ifndef BH_PLATFORM_TEACLAVE
++#define BH_PLATFORM_TEACLAVE
++#endif
++
++/* Stack size of applet threads's native part.  */
++#define BH_APPLET_PRESERVED_STACK_SIZE (32 * 1024)
++
++/* Default thread priority */
++#define BH_THREAD_DEFAULT_PRIORITY 0
++// #define os_thread_get_stack_boundary null
++
++typedef pthread_t korp_tid;
++typedef pthread_mutex_t korp_mutex;
++typedef pthread_cond_t korp_cond;
++typedef pthread_t korp_thread;
++
++#define os_thread_local_attribute __thread
++
++#if WASM_DISABLE_HW_BOUND_CHECK == 0
++#if defined(BUILD_TARGET_X86_64) \
++    || defined(BUILD_TARGET_AMD_64) \
++    || defined(BUILD_TARGET_AARCH64)
++
++#include <setjmp.h>
++
++#define OS_ENABLE_HW_BOUND_CHECK
++
++typedef jmp_buf korp_jmpbuf;
++
++#define os_setjmp setjmp
++#define os_longjmp longjmp
++#define os_alloca alloca
++
++#define os_getpagesize getpagesize
++
++typedef void (*os_signal_handler)(void *sig_addr);
++
++int os_thread_signal_init(os_signal_handler handler);
++
++void os_thread_signal_destroy();
++
++bool os_thread_signal_inited();
++
++void os_signal_unmask();
++
++void os_sigreturn();
++#endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64 */
++#endif /* end of WASM_DISABLE_HW_BOUND_CHECK */
++
++#ifdef __cplusplus
++}
++#endif
++
++#endif /* end of _PLATFORM_INTERNAL_H */
++
+diff --git a/core/shared/platform/teaclave/shared_platform.cmake b/core/shared/platform/teaclave/shared_platform.cmake
+new file mode 100644
+index 0000000..0b8e32a
+--- /dev/null
++++ b/core/shared/platform/teaclave/shared_platform.cmake
+@@ -0,0 +1,16 @@
++# Copyright (C) 2019 Intel Corporation.  All rights reserved.
++# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
++
++set (PLATFORM_SHARED_DIR ${CMAKE_CURRENT_LIST_DIR})
++
++add_definitions(-DBH_PLATFORM_TEACLAVE)
++
++include_directories(${PLATFORM_SHARED_DIR})
++include_directories(${PLATFORM_SHARED_DIR}/../include)
++
++file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c)
++
++set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_POSIX_SOURCE})
++
++file (GLOB header ${PLATFORM_SHARED_DIR}/../include/*.h)
++LIST (APPEND RUNTIME_LIB_HEADER_LIST ${header})
+diff --git a/core/shared/platform/teaclave/teaclave_platform.c b/core/shared/platform/teaclave/teaclave_platform.c
+new file mode 100644
+index 0000000..95cd650
+--- /dev/null
++++ b/core/shared/platform/teaclave/teaclave_platform.c

Review comment:
       Yes, I can try to integrate this source into teaclave platform. I didn't use it because the WAMR SGX platform contains ocall code, but it seems this source file can be ported into teaclave platform




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652132920



##########
File path: examples/webassembly/wasm_simple_add.py
##########
@@ -0,0 +1,97 @@
+#!/usr/bin/env python3

Review comment:
       Move `examples/webassembly/wasm_simple_add.py` to `examples/python/wasm_simple_add.py`.
   
   The `python` means using the python client sdk.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652135578



##########
File path: executor/src/wamr.rs
##########
@@ -0,0 +1,214 @@
+// 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::prelude::v1::*;
+
+use crate::context::reset_thread_context;
+use crate::context::set_thread_context;
+use crate::context::Context;
+
+use std::ffi::{c_void, CString};
+
+use teaclave_types::{FunctionArguments, FunctionRuntime, TeaclaveExecutor};
+
+// const MAXPYBUFLEN: usize = 20480;
+const DEFAULT_HEAP_SIZE: u32 = 8092;
+const DEFAULT_STACK_SIZE: u32 = 8092;
+const DEFAULT_ERROR_BUF_SIZE: usize = 128;
+
+extern "C" {
+
+    fn wasm_runtime_init() -> bool;
+
+    fn wasm_runtime_load(
+        buf: *const u8,
+        size: u32,
+        error_buf: *mut u8,
+        error_buf_size: u32,
+    ) -> *const c_void;
+
+    fn wasm_runtime_instantiate(
+        module: *const c_void,
+        stack_size: u32,
+        heap_size: u32,
+        error_buf: *mut u8,
+        error_buf_size: u32,
+    ) -> *const c_void;
+
+    fn wasm_runtime_lookup_function(
+        module_inst: *const c_void,
+        name: *const i8,
+        signature: *const u8,
+    ) -> *const c_void;
+
+    fn wasm_runtime_create_exec_env(module_inst: *const c_void, stack_size: u32) -> *const c_void;
+
+    fn wasm_runtime_call_wasm(
+        exec_env: *const c_void,
+        function: *const c_void,
+        argc: u32,
+        argv: *const u32,
+    ) -> bool;
+
+    fn wasm_runtime_module_dup_data(module_inst: *const c_void, src: *const u8, size: u32) -> u32;
+
+    fn wasm_runtime_module_free(module_inst: *const c_void, ptr: u32);
+}
+
+#[derive(Default)]
+pub struct WAMicroRuntime;
+
+impl TeaclaveExecutor for WAMicroRuntime {
+    fn execute(
+        &self,
+        _name: String,
+        arguments: FunctionArguments,
+        payload: Vec<u8>,
+        runtime: FunctionRuntime,
+    ) -> anyhow::Result<String> {
+        let wa_argv: Vec<_> = arguments.into_vec();
+
+        let mut error_buf = [0u8; DEFAULT_ERROR_BUF_SIZE];
+        let entry_name = CString::new("entrypoint").expect("CString::new failed");
+
+        set_thread_context(Context::new(runtime))?;
+
+        unsafe { wasm_runtime_init() };
+        let module = unsafe {
+            wasm_runtime_load(
+                payload.as_ptr(),
+                payload.len() as u32,
+                error_buf.as_mut_ptr(),
+                error_buf.len() as u32,
+            )
+        };
+
+        assert!((module as usize) != 0);
+
+        error_buf = [0u8; DEFAULT_ERROR_BUF_SIZE];
+        let module_instance = unsafe {
+            wasm_runtime_instantiate(
+                module,
+                DEFAULT_STACK_SIZE,
+                DEFAULT_HEAP_SIZE,
+                error_buf.as_mut_ptr(),
+                error_buf.len() as u32,
+            )
+        };
+        assert!((module_instance as usize) != 0);
+
+        let entry_func = unsafe {
+            wasm_runtime_lookup_function(module_instance, entry_name.as_ptr(), std::ptr::null())
+        };
+        assert!((entry_func as usize) != 0);
+
+        let exec_env = unsafe { wasm_runtime_create_exec_env(module_instance, DEFAULT_STACK_SIZE) };
+        assert!((exec_env as usize) != 0);
+
+        // prepare the arguments
+        // for best compatibility with Teaclave, the function signature is `int entrypoint(int argc, char* argv[])`
+        let cstr_argv: Vec<_> = wa_argv
+            .iter()
+            .map(|arg| CString::new(arg.as_str()).unwrap())
+            .collect();
+        let wasm_argc = 2;
+        let p_argv: Vec<u32> = cstr_argv
+            .iter() // do NOT into_iter()
+            .map(|arg| unsafe {
+                wasm_runtime_module_dup_data(
+                    module_instance,
+                    arg.as_ptr() as *const u8,
+                    arg.to_bytes_with_nul().len() as u32,
+                )
+            })
+            .collect();
+        let func_argv = unsafe {
+            wasm_runtime_module_dup_data(
+                module_instance,
+                p_argv.as_ptr() as *const u8,
+                (p_argv.len() * 4) as u32,
+            )
+        };
+        let wasm_argv: [u32; 2] = [p_argv.len() as u32, func_argv];
+
+        if unsafe { wasm_runtime_call_wasm(exec_env, entry_func, wasm_argc, wasm_argv.as_ptr()) } {
+            reset_thread_context()?;
+            log::debug!(
+                "IN WAMicroRuntime::execute after `wasm_runtime_call_wasm`, {:?}",
+                wasm_argv[0]
+            );
+            // clean WAMR allocated memory
+            let _ = p_argv
+                .iter()
+                .map(|addr| unsafe { wasm_runtime_module_free(module_instance, *addr) });
+            unsafe { wasm_runtime_module_free(module_instance, func_argv) };
+            Ok(wasm_argv[0].to_string())
+        } else {
+            Ok("WAMR Error".to_string())
+        }
+    }
+}
+
+#[cfg(feature = "enclave_unit_test")]
+pub mod tests {
+    use super::*;
+    use std::collections::HashMap;
+    use teaclave_crypto::*;
+    use teaclave_runtime::*;
+    use teaclave_test_utils::*;
+    use teaclave_types::*;
+
+    pub fn run_tests() -> bool {
+        run_tests!(test_wamr,)
+    }
+
+    fn test_wamr() {
+        log::debug!("IN TEST_WAMR");
+        let mut args = HashMap::new();
+
+        args.insert("adder 1".to_string(), "3".to_string());
+        args.insert("adder 2".to_string(), "4".to_string());
+        let args = FunctionArguments::from(args);
+
+        let wa_payload = include_bytes!("../../examples/webassembly/simple_add.wasm");
+
+        let wa_payload = wa_payload.to_vec();
+
+        // the input and output are currently not used for this test
+        let input = "fixtures/functions/mesapy/input.txt";
+        let output = "fixtures/functions/mesapy/output.txt";

Review comment:
       These are not needed.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun merged pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun merged pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504


   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652171466



##########
File path: examples/python/wasm_simple_add.py
##########
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+
+# 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.
+
+import sys
+
+from teaclave import (AuthenticationService, FrontendService,
+                      AuthenticationClient, FrontendClient)
+from utils import (AUTHENTICATION_SERVICE_ADDRESS, FRONTEND_SERVICE_ADDRESS,
+                   AS_ROOT_CA_CERT_PATH, ENCLAVE_INFO_PATH, USER_ID,
+                   USER_PASSWORD)
+
+
+class WASMAddExample:
+    def __init__(self, user_id, user_password):
+        self.user_id = user_id
+        self.user_password = user_password
+
+    def add(self,
+            payload_file="../webassembly/simple_add.wasm",

Review comment:
       "../wasm_simple_add_payload/simple_add.wasm"

##########
File path: examples/python/wasm_simple_add.py
##########
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+
+# 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.
+
+import sys
+
+from teaclave import (AuthenticationService, FrontendService,
+                      AuthenticationClient, FrontendClient)
+from utils import (AUTHENTICATION_SERVICE_ADDRESS, FRONTEND_SERVICE_ADDRESS,
+                   AS_ROOT_CA_CERT_PATH, ENCLAVE_INFO_PATH, USER_ID,
+                   USER_PASSWORD)
+
+
+class WASMAddExample:
+    def __init__(self, user_id, user_password):
+        self.user_id = user_id
+        self.user_password = user_password
+
+    def add(self,
+            payload_file="../webassembly/simple_add.wasm",

Review comment:
       `"../wasm_simple_add_payload/simple_add.wasm"`




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] ya0guang commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
ya0guang commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652172605



##########
File path: examples/python/wasm_simple_add.py
##########
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+
+# 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.
+
+import sys
+
+from teaclave import (AuthenticationService, FrontendService,
+                      AuthenticationClient, FrontendClient)
+from utils import (AUTHENTICATION_SERVICE_ADDRESS, FRONTEND_SERVICE_ADDRESS,
+                   AS_ROOT_CA_CERT_PATH, ENCLAVE_INFO_PATH, USER_ID,
+                   USER_PASSWORD)
+
+
+class WASMAddExample:
+    def __init__(self, user_id, user_password):
+        self.user_id = user_id
+        self.user_password = user_password
+
+    def add(self,
+            payload_file="../webassembly/simple_add.wasm",

Review comment:
       Got it!




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] m4sterchain commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
m4sterchain commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r650164329



##########
File path: third_party/wamr.patch
##########
@@ -0,0 +1,511 @@
+diff --git a/core/shared/platform/teaclave/platform_internal.h b/core/shared/platform/teaclave/platform_internal.h
+new file mode 100644
+index 0000000..83a08f4
+--- /dev/null
++++ b/core/shared/platform/teaclave/platform_internal.h
+@@ -0,0 +1,98 @@
++/*
++ * Copyright (C) 2019 Intel Corporation.  All rights reserved.
++ * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
++ */
++
++#ifndef _PLATFORM_INTERNAL_H
++#define _PLATFORM_INTERNAL_H
++
++#include <inttypes.h>
++#include <stdbool.h>
++#include <assert.h>
++#include <time.h>
++#include <string.h>
++#include <stdio.h>
++#include <stdlib.h>
++#include <math.h>
++#include <stdarg.h>
++#include <ctype.h>
++#include <pthread.h>
++#include <signal.h>
++#include <semaphore.h>
++#include <limits.h>
++#include <dirent.h>
++#include <fcntl.h>
++#include <unistd.h>
++#include <poll.h>
++#include <sched.h>
++#include <errno.h>
++#include <netinet/in.h>
++#include <sys/types.h>
++#include <sys/stat.h>
++#include <sys/mman.h>
++#include <sys/time.h>
++#include <sys/timeb.h>
++#include <sys/uio.h>
++#include <sys/ioctl.h>
++#include <sys/socket.h>
++#include <sys/resource.h>
++
++#ifdef __cplusplus
++extern "C" {
++#endif
++
++#ifndef BH_PLATFORM_TEACLAVE
++#define BH_PLATFORM_TEACLAVE
++#endif
++
++/* Stack size of applet threads's native part.  */
++#define BH_APPLET_PRESERVED_STACK_SIZE (32 * 1024)
++
++/* Default thread priority */
++#define BH_THREAD_DEFAULT_PRIORITY 0
++// #define os_thread_get_stack_boundary null
++
++typedef pthread_t korp_tid;
++typedef pthread_mutex_t korp_mutex;
++typedef pthread_cond_t korp_cond;
++typedef pthread_t korp_thread;
++
++#define os_thread_local_attribute __thread
++
++#if WASM_DISABLE_HW_BOUND_CHECK == 0
++#if defined(BUILD_TARGET_X86_64) \
++    || defined(BUILD_TARGET_AMD_64) \
++    || defined(BUILD_TARGET_AARCH64)
++
++#include <setjmp.h>
++
++#define OS_ENABLE_HW_BOUND_CHECK
++
++typedef jmp_buf korp_jmpbuf;
++
++#define os_setjmp setjmp
++#define os_longjmp longjmp
++#define os_alloca alloca
++
++#define os_getpagesize getpagesize
++
++typedef void (*os_signal_handler)(void *sig_addr);
++
++int os_thread_signal_init(os_signal_handler handler);
++
++void os_thread_signal_destroy();
++
++bool os_thread_signal_inited();
++
++void os_signal_unmask();
++
++void os_sigreturn();
++#endif /* end of BUILD_TARGET_X86_64/AMD_64/AARCH64 */
++#endif /* end of WASM_DISABLE_HW_BOUND_CHECK */
++
++#ifdef __cplusplus
++}
++#endif
++
++#endif /* end of _PLATFORM_INTERNAL_H */
++
+diff --git a/core/shared/platform/teaclave/shared_platform.cmake b/core/shared/platform/teaclave/shared_platform.cmake
+new file mode 100644
+index 0000000..0b8e32a
+--- /dev/null
++++ b/core/shared/platform/teaclave/shared_platform.cmake
+@@ -0,0 +1,16 @@
++# Copyright (C) 2019 Intel Corporation.  All rights reserved.
++# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
++
++set (PLATFORM_SHARED_DIR ${CMAKE_CURRENT_LIST_DIR})
++
++add_definitions(-DBH_PLATFORM_TEACLAVE)
++
++include_directories(${PLATFORM_SHARED_DIR})
++include_directories(${PLATFORM_SHARED_DIR}/../include)
++
++file (GLOB_RECURSE source_all ${PLATFORM_SHARED_DIR}/*.c)
++
++set (PLATFORM_SHARED_SOURCE ${source_all} ${PLATFORM_COMMON_POSIX_SOURCE})
++
++file (GLOB header ${PLATFORM_SHARED_DIR}/../include/*.h)
++LIST (APPEND RUNTIME_LIB_HEADER_LIST ${header})
+diff --git a/core/shared/platform/teaclave/teaclave_platform.c b/core/shared/platform/teaclave/teaclave_platform.c
+new file mode 100644
+index 0000000..95cd650
+--- /dev/null
++++ b/core/shared/platform/teaclave/teaclave_platform.c

Review comment:
       Could you elaborate more about this patch compared to the [linux-sgx platform](https://github.com/bytecodealliance/wasm-micro-runtime/blob/main/core/shared/platform/linux-sgx/sgx_platform.c)?
   




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652170629



##########
File path: examples/webassembly/simple_add.c
##########
@@ -0,0 +1,65 @@
+/*

Review comment:
       Same for `simple_add.wasm`

##########
File path: examples/webassembly/simple_add.c
##########
@@ -0,0 +1,65 @@
+/*

Review comment:
       `incubator-teaclave/examples/python/wasm_simple_add_payload/simple_add.c`




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652134761



##########
File path: executor/src/wamr.rs
##########
@@ -0,0 +1,214 @@
+// 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::prelude::v1::*;
+
+use crate::context::reset_thread_context;
+use crate::context::set_thread_context;
+use crate::context::Context;
+
+use std::ffi::{c_void, CString};
+
+use teaclave_types::{FunctionArguments, FunctionRuntime, TeaclaveExecutor};
+
+// const MAXPYBUFLEN: usize = 20480;

Review comment:
       Delete this commented line.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652171091



##########
File path: executor/src/wamr.rs
##########
@@ -0,0 +1,201 @@
+// 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::prelude::v1::*;
+
+use crate::context::reset_thread_context;
+use crate::context::set_thread_context;
+use crate::context::Context;
+
+use std::ffi::{c_void, CString};
+
+use teaclave_types::{FunctionArguments, FunctionRuntime, TeaclaveExecutor};
+
+const DEFAULT_HEAP_SIZE: u32 = 8092;
+const DEFAULT_STACK_SIZE: u32 = 8092;
+const DEFAULT_ERROR_BUF_SIZE: usize = 128;
+
+extern "C" {
+
+    fn wasm_runtime_init() -> bool;
+
+    fn wasm_runtime_load(
+        buf: *const u8,
+        size: u32,
+        error_buf: *mut u8,
+        error_buf_size: u32,
+    ) -> *const c_void;
+
+    fn wasm_runtime_instantiate(
+        module: *const c_void,
+        stack_size: u32,
+        heap_size: u32,
+        error_buf: *mut u8,
+        error_buf_size: u32,
+    ) -> *const c_void;
+
+    fn wasm_runtime_lookup_function(
+        module_inst: *const c_void,
+        name: *const i8,
+        signature: *const u8,
+    ) -> *const c_void;
+
+    fn wasm_runtime_create_exec_env(module_inst: *const c_void, stack_size: u32) -> *const c_void;
+
+    fn wasm_runtime_call_wasm(
+        exec_env: *const c_void,
+        function: *const c_void,
+        argc: u32,
+        argv: *const u32,
+    ) -> bool;
+
+    fn wasm_runtime_module_dup_data(module_inst: *const c_void, src: *const u8, size: u32) -> u32;
+
+    fn wasm_runtime_module_free(module_inst: *const c_void, ptr: u32);
+}
+
+#[derive(Default)]
+pub struct WAMicroRuntime;
+
+impl TeaclaveExecutor for WAMicroRuntime {
+    fn execute(
+        &self,
+        _name: String,
+        arguments: FunctionArguments,
+        payload: Vec<u8>,
+        runtime: FunctionRuntime,
+    ) -> anyhow::Result<String> {
+        let wa_argv: Vec<_> = arguments.into_vec();
+
+        let mut error_buf = [0u8; DEFAULT_ERROR_BUF_SIZE];
+        let entry_name = CString::new("entrypoint").expect("CString::new failed");
+
+        set_thread_context(Context::new(runtime))?;
+
+        unsafe { wasm_runtime_init() };
+        let module = unsafe {
+            wasm_runtime_load(
+                payload.as_ptr(),
+                payload.len() as u32,
+                error_buf.as_mut_ptr(),
+                error_buf.len() as u32,
+            )
+        };
+
+        assert!((module as usize) != 0);
+
+        error_buf = [0u8; DEFAULT_ERROR_BUF_SIZE];
+        let module_instance = unsafe {
+            wasm_runtime_instantiate(
+                module,
+                DEFAULT_STACK_SIZE,
+                DEFAULT_HEAP_SIZE,
+                error_buf.as_mut_ptr(),
+                error_buf.len() as u32,
+            )
+        };
+        assert!((module_instance as usize) != 0);
+
+        let entry_func = unsafe {
+            wasm_runtime_lookup_function(module_instance, entry_name.as_ptr(), std::ptr::null())
+        };
+        assert!((entry_func as usize) != 0);
+
+        let exec_env = unsafe { wasm_runtime_create_exec_env(module_instance, DEFAULT_STACK_SIZE) };
+        assert!((exec_env as usize) != 0);
+
+        // prepare the arguments
+        // for best compatibility with Teaclave, the function signature is `int entrypoint(int argc, char* argv[])`
+        let cstr_argv: Vec<_> = wa_argv
+            .iter()
+            .map(|arg| CString::new(arg.as_str()).unwrap())
+            .collect();
+        let wasm_argc = 2;
+        let p_argv: Vec<u32> = cstr_argv
+            .iter() // do NOT into_iter()
+            .map(|arg| unsafe {
+                wasm_runtime_module_dup_data(
+                    module_instance,
+                    arg.as_ptr() as *const u8,
+                    arg.to_bytes_with_nul().len() as u32,
+                )
+            })
+            .collect();
+        let func_argv = unsafe {
+            wasm_runtime_module_dup_data(
+                module_instance,
+                p_argv.as_ptr() as *const u8,
+                (p_argv.len() * 4) as u32,
+            )
+        };
+        let wasm_argv: [u32; 2] = [p_argv.len() as u32, func_argv];
+
+        if unsafe { wasm_runtime_call_wasm(exec_env, entry_func, wasm_argc, wasm_argv.as_ptr()) } {
+            reset_thread_context()?;
+            log::debug!(
+                "IN WAMicroRuntime::execute after `wasm_runtime_call_wasm`, {:?}",
+                wasm_argv[0]
+            );
+            // clean WAMR allocated memory
+            let _ = p_argv
+                .iter()
+                .map(|addr| unsafe { wasm_runtime_module_free(module_instance, *addr) });
+            unsafe { wasm_runtime_module_free(module_instance, func_argv) };
+            Ok(wasm_argv[0].to_string())
+        } else {
+            Ok("WAMR Error".to_string())
+        }
+    }
+}
+
+#[cfg(feature = "enclave_unit_test")]
+pub mod tests {
+    use super::*;
+    use std::collections::HashMap;
+    use teaclave_runtime::*;
+    use teaclave_test_utils::*;
+    use teaclave_types::*;
+
+    pub fn run_tests() -> bool {
+        run_tests!(test_wamr,)
+    }
+
+    fn test_wamr() {
+        let mut args = HashMap::new();
+
+        args.insert("adder 1".to_string(), "3".to_string());
+        args.insert("adder 2".to_string(), "4".to_string());
+        let args = FunctionArguments::from(args);
+
+        let wa_payload = include_bytes!("../../examples/webassembly/simple_add.wasm");

Review comment:
       => `../../examples/python/wamr_simple_add_payload/simple_add.wasm`




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652133965



##########
File path: .github/workflows/ci.yml
##########
@@ -101,6 +96,8 @@ jobs:
           cd build &&
           cmake -DRUSTFLAGS="-D warnings" -DTEST_MODE=ON ..
       - name: Code linting with Clippy
+        shell: bash

Review comment:
       This line is not needed.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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


[GitHub] [incubator-teaclave] mssun commented on a change in pull request #504: Add WebAssembly Executor Support

Posted by GitBox <gi...@apache.org>.
mssun commented on a change in pull request #504:
URL: https://github.com/apache/incubator-teaclave/pull/504#discussion_r652133638



##########
File path: examples/webassembly/wasm_simple_add.py
##########
@@ -0,0 +1,97 @@
+#!/usr/bin/env python3

Review comment:
       Also add this to the `run_examples` in `cmake/scripts/test.sh`.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



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