From 4af8e80018a387e0d54be3c3cf902ee12186df00 Mon Sep 17 00:00:00 2001 From: Andrew Clayton Date: Tue, 17 Oct 2023 12:53:18 +0100 Subject: Initial commit Signed-off-by: Andrew Clayton --- .gitattributes | 2 + .gitignore | 4 + LICENSE | 177 ++++++++++++++++++++++++++ Makefile | 11 ++ README | 72 +++++++++++ wasmtime-wasi-http.c | 345 +++++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 611 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README create mode 100644 wasmtime-wasi-http.c diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..45ec515 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.c diff=cpp +*.h diff=cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..35bb9cf --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.swp +*~ + +wasmtime-wasi-http diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..fa8a566 --- /dev/null +++ b/Makefile @@ -0,0 +1,11 @@ +CC = gcc +CFLAGS = -Wall -Wextra -g -DWASM_MODULE="\"$(WASM_MODULE)\"" -I$(WASMTIME_C_API)/include -L$(WASMTIME_C_API)/lib +LDFLAGS = -Wl,-rpath,$(WASMTIME_C_API)/lib + +all: wasmtime-wasi-http + +wasmtime-wasi-http: wasmtime-wasi-http.c + $(CC) $(CFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< -lwasmtime + +clean: + rm -f wasmtime-wasi-http diff --git a/README b/README new file mode 100644 index 0000000..822d1df --- /dev/null +++ b/README @@ -0,0 +1,72 @@ +Project Blackbird +================= + +Make Fermyon Spin WebAssembly Modules run on NGINX Unit. + +The repository will contain some exploratory tools. + +Quickstart +========== + +Clone the spin repository + +$ git clone https://github.com/fermyon/spin.git + +Build the wasm module. + +$ cd spin/examples/wasi-http-rust +$ cargo build --target wasm32-wasi + +Grab the Wasmtime C API + +$ wget -O- https://github.com/bytecodealliance/wasmtime/releases/download/v13.0.0/wasmtime-v13.0.0-x86_64-linux-c-api.tar.xz | tar -xvf - + +Clone this repository + +$ git clone git://git.digital-domain.net/project_blackbird.git + +Build it + +$ cd project_blackbird +$ make WASMTIME_C_API=/path/to/wasmtime-c-api WASM_MODULE=/path/to/spin/examples/wasi-http-rust/target/wasm32-wasi/debug/wasi_http_rust.wasm + +Run it + +$ ./wasmtime-wasi-http +Initializing... +Loading binary... +Compiling module... +Setting function imports... + [poll2::poll-oneoff] + [streams2::read] + [streams2::blocking-read] + [streams2::subscribe-to-input-stream] + [streams2::write] + [streams2::blocking-write] + [streams2::subscribe-to-output-stream] + [default-outgoing-HTTP2::handle] + [types2::new-fields] + [types2::fields-entries] + [types2::finish-incoming-stream] + [types2::finish-outgoing-stream] + [types2::incoming-request-method] + [types2::incoming-request-path-with-query] + [types2::incoming-request-headers] + [types2::incoming-request-consume] + [types2::new-outgoing-request] + [types2::outgoing-request-write] + [types2::set-response-outparam] + [types2::incoming-response-status] + [types2::incoming-response-headers] + [types2::incoming-response-consume] + [types2::new-outgoing-response] + [types2::outgoing-response-write] + [types2::future-incoming-response-get] + [types2::listen-to-future-incoming-response] +Initialising WASI... +Instantiating module... +Getting function exports... + [HTTP#handle] + [cabi_realloc] +Shutting down... +Done. diff --git a/wasmtime-wasi-http.c b/wasmtime-wasi-http.c new file mode 100644 index 0000000..8b8ddff --- /dev/null +++ b/wasmtime-wasi-http.c @@ -0,0 +1,345 @@ +/* + * Copyright (C) Andrew Clayton + * Copyright (C) F5, Inc. + */ + +#include +#include + +#include +#include +#include + +static void exit_with_error(const char *message, wasmtime_error_t *error, + wasm_trap_t *trap) +{ + wasm_byte_vec_t error_message; + + fprintf(stderr, "error: %s\n", message); + if (error != NULL) { + wasmtime_error_message(error, &error_message); + wasmtime_error_delete(error); + } else { + wasm_trap_message(trap, &error_message); + wasm_trap_delete(trap); + } + fprintf(stderr, "%.*s\n", (int) error_message.size, error_message.data); + wasm_byte_vec_delete(&error_message); + + exit(EXIT_FAILURE); +} + +static wasm_trap_t *dummy_func(void *env, wasmtime_caller_t *caller, + const wasmtime_val_t *args, size_t nargs, + wasmtime_val_t *results, size_t nresults) +{ + (void)env; + (void)caller; + (void)args; + (void)nargs; + (void)results; + (void)nresults; + + return NULL; +} + +static wasm_functype_t *create_wasm_func(const wasm_valkind_t *pk, + size_t nr_params, + const wasm_valkind_t *rk, + size_t nr_results) +{ + wasm_valtype_t *pt[14]; + wasm_valtype_t *rt[1]; + wasm_valtype_vec_t params; + wasm_valtype_vec_t results; + + if (nr_params > 0) { + for (size_t i = 0; i < nr_params; i++) + pt[i] = wasm_valtype_new(pk[i]); + wasm_valtype_vec_new(¶ms, nr_params, pt); + } else { + wasm_valtype_vec_new_empty(¶ms); + } + + if (nr_results > 0) { + for (size_t i = 0; i < nr_results; i++) + rt[i] = wasm_valtype_new(rk[i]); + wasm_valtype_vec_new(&results, nr_results, rt); + } else { + wasm_valtype_vec_new_empty(&results); + } + + return wasm_functype_new(¶ms, &results); +} + +static inline size_t rg(const char *s) +{ + return strlen(s); +} + +/* + * Argument counting macros gleamed from + * https://gist.github.com/christophercrouzet/db9bbb07d427381253a91210e7ddc68d + */ +#define ARG( \ + _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, ...) \ + _14 +#define COUNT_ARGS(...) \ + ARG(__VA_ARGS__, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,) + +#define SET_VALS(type, ...) \ + .type = { __VA_ARGS__ }, \ + .nr_##type = COUNT_ARGS(__VA_ARGS__) + +#define SET_FUNC(function, function_name, module) \ + .func_name = function_name, \ + .func_namelen = strlen(function_name), \ + .mod_name = module, \ + .mod_namelen = strlen(module), \ + .func = dummy_func + +static void set_function_imports(wasmtime_linker_t *linker) +{ + static const struct { + const char *func_name; + int func_namelen; + const char *mod_name; + int mod_namelen; + + wasmtime_func_callback_t func; + + wasm_valkind_t params[14]; + size_t nr_params; + wasm_valkind_t results[1]; + size_t nr_results; + } import_functions[] = { + { + SET_FUNC(poll_oneoff, "poll-oneoff", "poll2"), + SET_VALS(params, WASM_I32, WASM_I32, WASM_I32), + }, { + SET_FUNC(read, "read", "streams2"), + SET_VALS(params, WASM_I32, WASM_I64, WASM_I32), + }, { + SET_FUNC(blocking_read, "blocking-read", "streams2"), + SET_VALS(params, WASM_I32, WASM_I64, WASM_I32), + }, { + SET_FUNC(subscribe_to_input_stream, + "subscribe-to-input-stream", "streams2"), + SET_VALS(params, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(write, "write", "streams2"), + SET_VALS(params, + WASM_I32, WASM_I32, WASM_I32, WASM_I32), + }, { + SET_FUNC(blocking_write, "blocking-write", "streams2"), + SET_VALS(params, + WASM_I32, WASM_I32, WASM_I32, WASM_I32), + }, { + SET_FUNC(subscribe_to_output_stream, + "subscribe-to-output-stream", "streams2"), + SET_VALS(params, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(handle, "handle", "default-outgoing-HTTP2"), + SET_VALS(params, + WASM_I32, WASM_I32, WASM_I32, WASM_I32, + WASM_I32, WASM_I32, WASM_I32, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(new_fields, "new-fields", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(fields_entries, "fields-entries", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(finish_incoming_stream, + "finish-incoming-stream", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(finish_outgoing_stream, + "finish-outgoing-stream", "types2"), + SET_VALS(params, WASM_I32, WASM_I32, WASM_I32), + }, { + SET_FUNC(incoming_request_method, + "incoming-request-method", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(incoming_request_path_with_query, + "incoming-request-path-with-query", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(incoming_request_headers, + "incoming-request-headers", "types2"), + SET_VALS(params, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(incoming_request_consume, + "incoming-request-consume", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(new_outgoing_request, "new-outgoing-request", + "types2"), + SET_VALS(params, + WASM_I32, WASM_I32, WASM_I32, WASM_I32, + WASM_I32, WASM_I32, WASM_I32, WASM_I32, + WASM_I32, WASM_I32, WASM_I32, WASM_I32, + WASM_I32, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(outgoing_request_write, + "outgoing-request-write", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(set_response_outparam, + "set-response-outparam", "types2"), + SET_VALS(params, + WASM_I32, WASM_I32, WASM_I32, WASM_I32, + WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(incoming_response_status, + "incoming-response-status", "types2"), + SET_VALS(params, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(incoming_response_headers, + "incoming-response-headers", "types2"), + SET_VALS(params, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(incoming_response_consume, + "incoming-response-consume", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(new_outgoing_response, + "new-outgoing-response", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + SET_VALS(results, WASM_I32), + }, { + SET_FUNC(outgoing_response_write, + "outgoing-response-write", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(future_incoming_response-get, + "future-incoming-response-get", "types2"), + SET_VALS(params, WASM_I32, WASM_I32), + }, { + SET_FUNC(listen_to_fauture_incoming_response, + "listen-to-future-incoming-response", + "types2"), + SET_VALS(params, WASM_I32), + SET_VALS(results, WASM_I32), + }, + + { } + }, *imf; + + for (imf = import_functions; imf->func_name != NULL; imf++) { + wasm_functype_t *func_ty; + + printf(" [%s::%s]\n", imf->mod_name, imf->func_name); + + func_ty = create_wasm_func(imf->params, imf->nr_params, + imf->results, imf->nr_results); + wasmtime_linker_define_func(linker, + imf->mod_name, imf->mod_namelen, + imf->func_name, imf->func_namelen, + func_ty, imf->func, NULL, NULL); + wasm_functype_delete(func_ty); + } +} + +int main(void) +{ + wasm_engine_t *engine; + wasmtime_store_t *store; + wasmtime_context_t *context; + wasmtime_module_t *module = NULL; + wasmtime_linker_t *linker; + wasmtime_error_t *error; + wasm_byte_vec_t wasm; + wasmtime_extern_t item; + wasi_config_t *wasi_config; + FILE *file; + size_t file_size; + bool ok; + + printf("Initializing...\n"); + engine = wasm_engine_new(); + store = wasmtime_store_new(engine, NULL, NULL); + context = wasmtime_store_context(store); + + linker = wasmtime_linker_new(engine); + error = wasmtime_linker_define_wasi(linker); + if (error != NULL) + exit_with_error("failed to link wasi", error, NULL); + + printf("Loading binary...\n"); + file = fopen(WASM_MODULE, "r"); + if (!file) { + printf("> Error loading file!\n"); + exit(EXIT_FAILURE); + } + fseek(file, 0L, SEEK_END); + file_size = ftell(file); + wasm_byte_vec_new_uninitialized(&wasm, file_size); + fseek(file, 0L, SEEK_SET); + if (fread(wasm.data, file_size, 1, file) != 1) { + printf("> Error loading module!\n"); + exit(EXIT_FAILURE); + } + fclose(file); + + printf("Compiling module...\n"); + error = wasmtime_module_new(engine, (uint8_t*)wasm.data, wasm.size, + &module); + if (!module) + exit_with_error("failed to compile module", error, NULL); + wasm_byte_vec_delete(&wasm); + + printf("Setting function imports...\n"); + set_function_imports(linker); + + printf("Initialising WASI...\n"); + wasi_config = wasi_config_new(); + wasi_config_inherit_env(wasi_config); + wasi_config_inherit_stdin(wasi_config); + wasi_config_inherit_stdout(wasi_config); + wasi_config_inherit_stderr(wasi_config); + error = wasmtime_context_set_wasi(context, wasi_config); + if (error) + exit_with_error("failed to initialise WASI", error, NULL); + + printf("Instantiating module...\n"); + error = wasmtime_linker_module(linker, context, "", 0, module); + if (error != NULL) + exit_with_error("failed to instantiate module", error, NULL); + + printf("Getting function exports...\n"); + ok = wasmtime_linker_get(linker, context, "", 0, "HTTP#handle", 11, + &item); + if (!ok) { + printf("> Error getting function export [HTTP#handle]\n"); + exit(EXIT_FAILURE); + } + printf(" [HTTP#handle]\n"); + + ok = wasmtime_linker_get(linker, context, "", 0, "cabi_realloc", 12, + &item); + if (!ok) { + printf("> Error getting function export [cabi_realloc]\n"); + exit(EXIT_FAILURE); + } + printf(" [cabi_realloc]\n"); + + printf("Shutting down...\n"); + wasmtime_module_delete(module); + wasmtime_store_delete(store); + wasm_engine_delete(engine); + + printf("Done.\n"); + + exit(EXIT_SUCCESS);; +} -- cgit