From 99882ef128b923262748ef80784fc1c22c3b7519 Mon Sep 17 00:00:00 2001 From: Renata Hodovan Date: Tue, 23 Jul 2024 19:32:34 +0200 Subject: [PATCH] Ensure that workers in fuzzers can create their own context Inspired by qjs, a new helper method was added to create the JS context, that can be reused to create context in workers, too. --- fuzz/fuzz_common.c | 23 +++++++++++++++++------ fuzz/fuzz_common.h | 1 + fuzz/fuzz_compile.c | 2 +- fuzz/fuzz_eval.c | 2 +- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/fuzz/fuzz_common.c b/fuzz/fuzz_common.c index 9f1662d..cb17ffd 100644 --- a/fuzz/fuzz_common.c +++ b/fuzz/fuzz_common.c @@ -28,24 +28,35 @@ void reset_nbinterrupts() { nbinterrupts = 0; } +JSContext *JS_NewCustomContext(JSRuntime *rt) +{ + JSContext *ctx = JS_NewContext(rt); + if (!ctx) + return NULL; + + JS_AddIntrinsicBigFloat(ctx); + JS_AddIntrinsicBigDecimal(ctx); + JS_AddIntrinsicOperators(ctx); + JS_EnableBignumExt(ctx, 1); + + js_init_module_std(ctx, "std"); + js_init_module_os(ctx, "os"); + return ctx; +} + void test_one_input_init(JSRuntime *rt, JSContext *ctx) { // 64 Mo JS_SetMemoryLimit(rt, 0x4000000); // 64 Kb JS_SetMaxStackSize(rt, 0x10000); - JS_AddIntrinsicBigFloat(ctx); - JS_AddIntrinsicBigDecimal(ctx); - JS_AddIntrinsicOperators(ctx); - JS_EnableBignumExt(ctx, 1); JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL); JS_SetInterruptHandler(JS_GetRuntime(ctx), interrupt_handler, NULL); + js_std_set_worker_new_context_func(JS_NewCustomContext); js_std_add_helpers(ctx, 0, NULL); // Load os and std js_std_init_handlers(rt); - js_init_module_std(ctx, "std"); - js_init_module_os(ctx, "os"); const char *str = "import * as std from 'std';\n" "import * as os from 'os';\n" "globalThis.std = std;\n" diff --git a/fuzz/fuzz_common.h b/fuzz/fuzz_common.h index 10cb497..3987a01 100644 --- a/fuzz/fuzz_common.h +++ b/fuzz/fuzz_common.h @@ -18,5 +18,6 @@ static int nbinterrupts = 0; +JSContext *JS_NewCustomContext(JSRuntime *rt); void reset_nbinterrupts(); void test_one_input_init(JSRuntime *rt, JSContext *ctx); diff --git a/fuzz/fuzz_compile.c b/fuzz/fuzz_compile.c index 0ab1b03..5e83267 100644 --- a/fuzz/fuzz_compile.c +++ b/fuzz/fuzz_compile.c @@ -27,7 +27,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { return 0; JSRuntime *rt = JS_NewRuntime(); - JSContext *ctx = JS_NewContext(rt); + JSContext *ctx = JS_NewCustomContext(rt); test_one_input_init(rt, ctx); uint8_t *null_terminated_data = malloc(size + 1); diff --git a/fuzz/fuzz_eval.c b/fuzz/fuzz_eval.c index aa26f1e..5851875 100644 --- a/fuzz/fuzz_eval.c +++ b/fuzz/fuzz_eval.c @@ -26,7 +26,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { return 0; JSRuntime *rt = JS_NewRuntime(); - JSContext *ctx = JS_NewContext(rt); + JSContext *ctx = JS_NewCustomContext(rt); test_one_input_init(rt, ctx); uint8_t *null_terminated_data = malloc(size + 1);