added __spawn_process to onyx_run
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Wed, 1 Dec 2021 20:26:14 +0000 (14:26 -0600)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Wed, 1 Dec 2021 20:26:14 +0000 (14:26 -0600)
core/runtime/onyx_run.onyx
src/wasm_runtime.c

index 8d924365dbd45dd91b7a27c6d6386a819de42ab4..ca1af5a14b96234b015f13cb8327c95cf4b9d4c2 100644 (file)
@@ -16,3 +16,5 @@ use package wasi
     #export "_thread_start" _thread_start
     #export "_thread_exit"  _thread_exit
 }
+
+__spawn_process :: (path: str) -> i32 #foreign "env" "spawn_process" ---
\ No newline at end of file
index a289bd496d936d1a48f5423232f80b1010d72da9..e8ff234d0ab1ce86c986d5b34066bd53b4b8d65b 100644 (file)
@@ -7,6 +7,7 @@
 #ifdef _BH_LINUX
     #include <pthread.h>
     #include <signal.h>
+    #include <sys/wait.h>
 #endif
 
 #ifndef WASMER_VERSION
@@ -171,6 +172,27 @@ static wasm_trap_t* onyx_kill_thread_impl(const wasm_val_vec_t* params, wasm_val
     return NULL;
 }
 
+static wasm_trap_t* onyx_spawn_process_impl(const wasm_val_vec_t* params, wasm_val_vec_t* results) {
+    char* process_str = (char *) wasm_memory_data(wasm_memory) + params->data[0].of.i32;
+    i32   process_len = params->data[1].of.i32;
+
+    char process_path[1024];
+    process_len = bh_min(1023, process_len);
+    memcpy(process_path, process_str, process_len);
+    process_path[process_len] = '\0';
+
+    #ifdef _BH_LINUX
+        if (fork() == 0) {
+            execv(process_path, NULL);
+        }
+
+        i32 status;
+        wait(&status);
+        results->data[0] = WASM_I32_VAL(WEXITSTATUS(status));
+    #endif
+
+    return NULL;
+}
 
 void onyx_run_wasm(bh_buffer wasm_bytes) {
     wasm_instance_t* instance = NULL;
@@ -271,6 +293,14 @@ void onyx_run_wasm(bh_buffer wasm_bytes) {
                 import = wasm_func_as_extern(wasm_func);
                 goto import_found;
             }
+
+            if (wasm_name_equals_string(import_name, "spawn_process")) {
+                wasm_functype_t* func_type = wasm_functype_new_2_1(wasm_valtype_new_i32(), wasm_valtype_new_i32(), wasm_valtype_new_i32());
+
+                wasm_func_t* wasm_func = wasm_func_new(wasm_store, func_type, onyx_spawn_process_impl);
+                import = wasm_func_as_extern(wasm_func);
+                goto import_found;
+            }
         }
 
         goto bad_import;