/* js_mu: the MuJS stack API used by js_browser.c, implemented on QuickJS. * See js_mu.h for the model. */ #include #include #include #include #include #ifdef JS_MU_HOST #include static unsigned int u_ticks_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (unsigned int)(t.tv_sec * 1000u + t.tv_nsec / 1000000u); } #else #include "ucmd_lib.h" #endif #include "quickjs.h" #include "js_mu.h" #define MU_TRIES 64 #define MU_STACK_INIT 256 /* QuickJS recurses on the C stack for every JavaScript call, and the ring-3 * stack is only 128 KB (USER_STACK_PAGES). Outermost entries into the * engine therefore switch to a private stack from the heap; QuickJS's own * limit leaves a margin below it, so deep recursion becomes a RangeError * instead of a page fault. */ #ifndef JS_MU_STACK_BYTES #define JS_MU_STACK_BYTES (1024u * 1024u) #endif #define JS_MU_STACK_MARGIN (64u * 1024u) #if defined(__i386__) && !defined(JS_MU_HOST) #define MU_OWN_STACK 1 /* mu_stack_call(top, fn, arg): run fn(arg) with ESP at `top`. EBP is * callee-saved, so it restores the caller's stack afterwards (a longjmp * out of fn restores ESP from its jmp_buf instead). */ void mu_stack_call(void *top, void (*fn)(void *), void *arg); __asm__(".text\n" ".globl mu_stack_call\n" "mu_stack_call:\n" " pushl %ebp\n" " movl %esp, %ebp\n" " movl 8(%ebp), %eax\n" " movl 12(%ebp), %ecx\n" " movl 16(%ebp), %edx\n" " movl %eax, %esp\n" " andl $-16, %esp\n" " subl $12, %esp\n" " pushl %edx\n" " call *%ecx\n" " movl %ebp, %esp\n" " popl %ebp\n" " ret\n"); #endif struct mu_slot { JSValue v; const char *cs; /* cached C string for js_tostring() */ }; struct mu_try { jmp_buf buf; int top, bot; void *fdata; }; struct js_State { JSRuntime *rt; JSContext *ctx; struct mu_slot *stk; int top, bot, cap; void *fdata; struct mu_try tries[MU_TRIES]; int ntry; JSValue registry; int nextref; js_Report report; js_Panic panic; unsigned int deadline; int limited; int depth; /* nested entries from C into JavaScript */ void *jsstack; /* private engine stack (MU_OWN_STACK) */ js_ModuleResolve mod_resolve; js_ModuleLoad mod_load; }; struct mu_ud { const char *tag; void *data; js_HasProperty has; js_Put put; js_Delete del; JSValue backing; /* expando properties (jQuery data, ...) */ }; static JSClassID mu_ud_class; /* ---- value stack ---- */ static void mu_push(js_State *J, JSValue v) { if (J->top >= J->cap) { int ncap = J->cap ? J->cap * 2 : MU_STACK_INIT; struct mu_slot *n = (struct mu_slot *)realloc(J->stk, (size_t)ncap * sizeof(*n)); if (!n) { JS_FreeValue(J->ctx, v); if (J->panic) J->panic(J); abort(); } J->stk = n; J->cap = ncap; } J->stk[J->top].v = v; J->stk[J->top].cs = 0; J->top++; } static void mu_slot_free(js_State *J, struct mu_slot *s) { if (s->cs) JS_FreeCString(J->ctx, s->cs); s->cs = 0; JS_FreeValue(J->ctx, s->v); s->v = JS_UNDEFINED; } static void mu_popto(js_State *J, int top) { while (J->top > top && J->top > 0) mu_slot_free(J, &J->stk[--J->top]); } /* Take ownership of the top value. */ static JSValue mu_take(js_State *J) { struct mu_slot *s; JSValue v; if (J->top <= J->bot) return JS_UNDEFINED; s = &J->stk[--J->top]; if (s->cs) JS_FreeCString(J->ctx, s->cs); v = s->v; s->cs = 0; s->v = JS_UNDEFINED; return v; } static int mu_abs(js_State *J, int idx) { return idx < 0 ? J->top + idx : J->bot + idx; } static struct mu_slot *mu_slot_at(js_State *J, int idx) { int i = mu_abs(J, idx); if (i < 0 || i >= J->top) return 0; return &J->stk[i]; } static JSValue mu_at(js_State *J, int idx) { struct mu_slot *s = mu_slot_at(J, idx); return s ? s->v : JS_UNDEFINED; } /* ---- exceptions ---- */ static __attribute__((noreturn)) void mu_throw_value(js_State *J, JSValue exc) { struct mu_try *t; if (J->ntry == 0) { mu_push(J, exc); if (J->panic) J->panic(J); abort(); } t = &J->tries[--J->ntry]; mu_popto(J, t->top); J->bot = t->bot; J->fdata = t->fdata; mu_push(J, exc); longjmp(t->buf, 1); } static void mu_check(js_State *J, JSValue v) { if (JS_IsException(v)) mu_throw_value(J, JS_GetException(J->ctx)); } jmp_buf *js_savetry(js_State *J) { struct mu_try *t; if (J->ntry >= MU_TRIES) { JS_ThrowInternalError(J->ctx, "try stack overflow"); mu_throw_value(J, JS_GetException(J->ctx)); } t = &J->tries[J->ntry++]; t->top = J->top; t->bot = J->bot; t->fdata = J->fdata; return &t->buf; } void js_endtry(js_State *J) { if (J->ntry > 0) J->ntry--; } void js_throw(js_State *J) { mu_throw_value(J, mu_take(J)); } void js_typeerror(js_State *J, const char *fmt, ...) { char buf[256]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); JS_ThrowTypeError(J->ctx, "%s", buf); mu_throw_value(J, JS_GetException(J->ctx)); } /* ---- C functions ---- */ static JSValue mu_ptr_value(void *p) { return JS_NewFloat64(0, (double)(uintptr_t)p); } static void *mu_value_ptr(JSValueConst v) { double d; if (JS_VALUE_GET_TAG(v) == JS_TAG_INT) return (void *)(uintptr_t)(uint32_t)JS_VALUE_GET_INT(v); d = JS_VALUE_GET_FLOAT64(v); return (void *)(uintptr_t)d; } /* Every C callback is a catch boundary: a js_throw() inside it becomes a * QuickJS exception for the calling script. */ static JSValue mu_trampoline(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *data) { js_State *J = (js_State *)JS_GetContextOpaque(ctx); js_CFunction fn = (js_CFunction)mu_value_ptr(data[0]); void *fdata = mu_value_ptr(data[1]); int savetop = J->top, savebot = J->bot, ntry = J->ntry, i; void *savefd = J->fdata; struct mu_try *t; JSValue ret; mu_push(J, JS_DupValue(ctx, this_val)); for (i = 0; i < argc; i++) mu_push(J, JS_DupValue(ctx, argv[i])); for (; i < magic; i++) mu_push(J, JS_UNDEFINED); if (J->ntry >= MU_TRIES) { mu_popto(J, savetop); return JS_ThrowInternalError(ctx, "try stack overflow"); } t = &J->tries[J->ntry++]; t->top = savetop; t->bot = savebot; t->fdata = savefd; J->bot = savetop; J->fdata = fdata; if (setjmp(t->buf)) { JSValue exc = mu_take(J); mu_popto(J, savetop); J->bot = savebot; J->fdata = savefd; J->ntry = ntry; return JS_Throw(ctx, exc); } fn(J); J->ntry = ntry; ret = J->top > savetop ? JS_DupValue(ctx, J->stk[J->top - 1].v) : JS_UNDEFINED; mu_popto(J, savetop); J->bot = savebot; J->fdata = savefd; return ret; } void js_newcfunctionx(js_State *J, js_CFunction fun, const char *name, int length, void *data, js_Finalize finalize) { JSValue d[2]; JSValue f; (void)name; (void)finalize; d[0] = mu_ptr_value((void *)fun); d[1] = mu_ptr_value(data); f = JS_NewCFunctionData(J->ctx, mu_trampoline, length, length, 2, d); /* MuJS lets `new` call any C function (Event, CustomEvent, ... * return their object); QuickJS needs the constructor bit for that. */ JS_SetConstructorBit(J->ctx, f, 1); mu_push(J, f); } void js_newcfunction(js_State *J, js_CFunction fun, const char *name, int length) { js_newcfunctionx(J, fun, name, length, 0, 0); } void *js_currentfunctiondata(js_State *J) { return J->fdata; } /* ---- userdata ---- */ /* Run a has/put/delete hook as a catch boundary. Returns the hook's * result, or -1 with a pending QuickJS exception. */ static int mu_hook(js_State *J, js_HasProperty hook, void *p, JSAtom atom, int savetop) { const char *name = JS_AtomToCString(J->ctx, atom); int savebot = J->bot, ntry = J->ntry, r; void *savefd = J->fdata; struct mu_try *t; if (!name) return -1; if (J->ntry >= MU_TRIES) { JS_FreeCString(J->ctx, name); JS_ThrowInternalError(J->ctx, "try stack overflow"); return -1; } t = &J->tries[J->ntry++]; t->top = savetop; t->bot = savebot; t->fdata = savefd; if (setjmp(t->buf)) { JSValue exc = mu_take(J); JS_FreeCString(J->ctx, name); mu_popto(J, savetop); J->bot = savebot; J->fdata = savefd; J->ntry = ntry; JS_Throw(J->ctx, exc); return -1; } r = hook(J, p, name); J->ntry = ntry; J->bot = savebot; J->fdata = savefd; JS_FreeCString(J->ctx, name); return r; } /* has-hook lookup: 1 with *out set, 0 when the hook does not know the * name, -1 on exception. */ static int mu_ud_lookup(JSContext *ctx, struct mu_ud *u, JSAtom atom, JSValue *out) { js_State *J = (js_State *)JS_GetContextOpaque(ctx); int savetop = J->top, r; if (!u->has) return 0; r = mu_hook(J, u->has, u->data, atom, savetop); if (r > 0) { *out = J->top > savetop ? JS_DupValue(ctx, J->stk[J->top - 1].v) : JS_UNDEFINED; mu_popto(J, savetop); return 1; } mu_popto(J, savetop); return r < 0 ? -1 : 0; } static struct mu_ud *mu_ud_of(JSValueConst obj) { return (struct mu_ud *)JS_GetOpaque(obj, mu_ud_class); } /* Expandos live on the backing object; everything else comes from the * wrapper's own prototype chain with the wrapper as receiver, so a getter * or setter defined on a prototype sees the element as `this`, and a * changed prototype (a Custom Element upgrade) takes effect. */ static JSValue mu_ud_inherited_get(JSContext *ctx, struct mu_ud *u, JSValueConst obj, JSAtom atom, JSValueConst receiver) { JSValue proto, v; int own = JS_GetOwnProperty(ctx, 0, u->backing, atom); if (own < 0) return JS_EXCEPTION; if (own) return JS_GetProperty(ctx, u->backing, atom); proto = JS_GetPrototype(ctx, obj); if (JS_IsException(proto)) return proto; if (!JS_IsObject(proto)) { JS_FreeValue(ctx, proto); return JS_UNDEFINED; } v = JS_GetPropertyInternal(ctx, proto, atom, JS_IsObject(receiver) ? receiver : obj, 0); JS_FreeValue(ctx, proto); return v; } static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom, JSValueConst receiver) { struct mu_ud *u = mu_ud_of(obj); JSValue v; int r; if (!u) return JS_UNDEFINED; r = mu_ud_lookup(ctx, u, atom, &v); if (r < 0) return JS_EXCEPTION; if (r > 0) return v; return mu_ud_inherited_get(ctx, u, obj, atom, receiver); } static int mu_ud_has(JSContext *ctx, JSValueConst obj, JSAtom atom) { struct mu_ud *u = mu_ud_of(obj); JSValue v; int r; if (!u) return 0; r = mu_ud_lookup(ctx, u, atom, &v); if (r < 0) return -1; if (r > 0) { JS_FreeValue(ctx, v); return 1; } r = JS_GetOwnProperty(ctx, 0, u->backing, atom); if (r != 0) return r; { JSValue proto = JS_GetPrototype(ctx, obj); if (JS_IsException(proto)) return -1; r = JS_IsObject(proto) ? JS_HasProperty(ctx, proto, atom) : 0; JS_FreeValue(ctx, proto); } return r; } static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom, JSValueConst value, JSValueConst receiver, int flags) { js_State *J = (js_State *)JS_GetContextOpaque(ctx); struct mu_ud *u = mu_ud_of(obj); int savetop = J->top, r; (void)receiver; if (!u) return 0; if (u->put) { mu_push(J, JS_DupValue(ctx, value)); r = mu_hook(J, u->put, u->data, atom, savetop); mu_popto(J, savetop); if (r < 0) return -1; if (r > 0) return 1; } r = JS_GetOwnProperty(ctx, 0, u->backing, atom); if (r < 0) return -1; if (!r) { /* A setter on the prototype chain runs with the element as * `this`; a plain new property lands on the backing object * through mu_ud_define(). */ JSValue proto = JS_GetPrototype(ctx, obj); if (JS_IsException(proto)) return -1; if (JS_IsObject(proto)) { r = JS_SetPropertyInternal(ctx, proto, atom, JS_DupValue(ctx, value), obj, flags); JS_FreeValue(ctx, proto); return r; } JS_FreeValue(ctx, proto); } return JS_SetProperty(ctx, u->backing, atom, JS_DupValue(ctx, value)); } static int mu_ud_delete(JSContext *ctx, JSValueConst obj, JSAtom atom) { js_State *J = (js_State *)JS_GetContextOpaque(ctx); struct mu_ud *u = mu_ud_of(obj); int savetop = J->top, r; if (!u) return 1; if (u->del) { r = mu_hook(J, u->del, u->data, atom, savetop); mu_popto(J, savetop); if (r < 0) return -1; if (r > 0) return 1; } return JS_DeleteProperty(ctx, u->backing, atom, 0); } static int mu_ud_own(JSContext *ctx, JSPropertyDescriptor *desc, JSValueConst obj, JSAtom atom) { struct mu_ud *u = mu_ud_of(obj); JSValue v; int r; if (!u) return 0; r = mu_ud_lookup(ctx, u, atom, &v); if (r < 0) return -1; if (r > 0) { if (desc) { desc->flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE; desc->value = v; desc->getter = JS_UNDEFINED; desc->setter = JS_UNDEFINED; } else { JS_FreeValue(ctx, v); } return 1; } return JS_GetOwnProperty(ctx, desc, u->backing, atom); } static int mu_ud_names(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst obj) { struct mu_ud *u = mu_ud_of(obj); if (!u) { *ptab = 0; *plen = 0; return 0; } return JS_GetOwnPropertyNames(ctx, ptab, plen, u->backing, JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK); } static int mu_ud_define(JSContext *ctx, JSValueConst this_obj, JSAtom prop, JSValueConst val, JSValueConst getter, JSValueConst setter, int flags) { struct mu_ud *u = mu_ud_of(this_obj); if (!u) return 0; return JS_DefineProperty(ctx, u->backing, prop, val, getter, setter, flags); } static void mu_ud_finalizer(JSRuntime *rt, JSValue val) { struct mu_ud *u = mu_ud_of(val); if (u) { JS_FreeValueRT(rt, u->backing); free(u); } } static void mu_ud_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark) { struct mu_ud *u = mu_ud_of(val); if (u) JS_MarkValue(rt, u->backing, mark); } static JSClassExoticMethods mu_ud_exotic = { .get_own_property = mu_ud_own, .get_own_property_names = mu_ud_names, .delete_property = mu_ud_delete, .define_own_property = mu_ud_define, .has_property = mu_ud_has, .get_property = mu_ud_get, .set_property = mu_ud_set, }; static JSClassDef mu_ud_def = { .class_name = "HTMLElement", .finalizer = mu_ud_finalizer, .gc_mark = mu_ud_mark, .exotic = &mu_ud_exotic, }; /* Pops the prototype from the top of the stack, like MuJS. */ void js_newuserdatax(js_State *J, const char *tag, void *data, js_HasProperty has, js_Put put, js_Delete del, js_Finalize finalize) { JSValue proto = mu_take(J), obj; struct mu_ud *u; (void)finalize; if (!JS_IsObject(proto)) { JS_FreeValue(J->ctx, proto); proto = JS_NULL; } u = (struct mu_ud *)malloc(sizeof(*u)); obj = JS_NewObjectProtoClass(J->ctx, proto, mu_ud_class); if (!u || JS_IsException(obj)) { free(u); JS_FreeValue(J->ctx, proto); mu_check(J, JS_IsException(obj) ? obj : JS_ThrowOutOfMemory(J->ctx)); return; } u->tag = tag; u->data = data; u->has = has; u->put = put; u->del = del; u->backing = JS_NewObjectProto(J->ctx, proto); JS_FreeValue(J->ctx, proto); JS_SetOpaque(obj, u); mu_push(J, obj); } int js_isuserdata(js_State *J, int idx, const char *tag) { struct mu_ud *u = mu_ud_of(mu_at(J, idx)); return u && !strcmp(u->tag, tag); } void *js_touserdata(js_State *J, int idx, const char *tag) { struct mu_ud *u = mu_ud_of(mu_at(J, idx)); if (!u || strcmp(u->tag, tag)) js_typeerror(J, "not a %s", tag); return u->data; } /* ---- state ---- */ static int mu_interrupt(JSRuntime *rt, void *opaque) { js_State *J = (js_State *)opaque; (void)rt; return J->limited && (int)(u_ticks_ms() - J->deadline) >= 0; } /* An async function or a promise chain that fails with nobody listening * (Vite apps bootstrap from an async IIFE) would otherwise vanish without a * trace. The error goes to the report hook, like an uncaught exception. * A handler attached later in the same job cannot be detected here, so a * rejection that is handled late is still reported once. */ static void mu_rejection(JSContext *ctx, JSValueConst promise, JSValueConst reason, int is_handled, void *opaque) { js_State *J = (js_State *)opaque; const char *msg, *stack = 0; JSValue st = JS_UNDEFINED; char buf[768]; (void)promise; if (is_handled || !J->report) return; msg = JS_ToCString(ctx, reason); if (JS_IsObject(reason)) { st = JS_GetPropertyStr(ctx, reason, "stack"); if (JS_IsString(st)) stack = JS_ToCString(ctx, st); } snprintf(buf, sizeof(buf), "Uncaught (in promise) %s%s%s", msg ? msg : "error", stack ? "\n" : "", stack ? stack : ""); J->report(J, buf); if (stack) JS_FreeCString(ctx, stack); JS_FreeValue(ctx, st); if (msg) JS_FreeCString(ctx, msg); else JS_FreeValue(ctx, JS_GetException(ctx)); } js_State *js_newstate(js_Alloc alloc, void *actx, int flags) { js_State *J; (void)alloc; (void)actx; (void)flags; J = (js_State *)calloc(1, sizeof(*J)); if (!J) return 0; J->rt = JS_NewRuntime(); if (!J->rt) { free(J); return 0; } #ifdef MU_OWN_STACK J->jsstack = malloc(JS_MU_STACK_BYTES); JS_SetMaxStackSize(J->rt, J->jsstack ? JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN : 48u * 1024u); #else JS_SetMaxStackSize(J->rt, JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN); #endif if (!mu_ud_class) JS_NewClassID(&mu_ud_class); JS_NewClass(J->rt, mu_ud_class, &mu_ud_def); J->ctx = JS_NewContext(J->rt); if (!J->ctx) { JS_FreeRuntime(J->rt); free(J); return 0; } JS_SetContextOpaque(J->ctx, J); JS_SetInterruptHandler(J->rt, mu_interrupt, J); JS_SetHostPromiseRejectionTracker(J->rt, mu_rejection, J); J->registry = JS_NewObject(J->ctx); return J; } void js_freestate(js_State *J) { if (!J) return; J->bot = 0; mu_popto(J, 0); JS_FreeValue(J->ctx, J->registry); JS_FreeContext(J->ctx); JS_FreeRuntime(J->rt); free(J->stk); free(J->jsstack); free(J); } void js_setreport(js_State *J, js_Report report) { J->report = report; } js_Panic js_atpanic(js_State *J, js_Panic panic) { js_Panic old = J->panic; J->panic = panic; return old; } void js_setlimit(js_State *J, int limit_ms, int memlimit) { (void)memlimit; J->limited = limit_ms > 0; J->deadline = u_ticks_ms() + (unsigned int)limit_ms; } /* ---- loading and calling ---- */ /* Run an engine entry: on the private stack when this is the outermost * one, directly when JavaScript is already running (a nested callback). */ struct mu_entry { js_State *J; void (*fn)(struct mu_entry *e); const char *filename, *source; JSValue fn_obj, thisv, *argv, result; int argc; }; static void mu_entry_run(void *arg) { struct mu_entry *e = (struct mu_entry *)arg; JS_UpdateStackTop(e->J->rt); e->fn(e); } static void mu_enter(js_State *J, struct mu_entry *e) { e->J = J; if (J->depth++ == 0) { #ifdef MU_OWN_STACK if (J->jsstack) { mu_stack_call((char *)J->jsstack + JS_MU_STACK_BYTES, mu_entry_run, e); J->depth--; return; } #endif mu_entry_run(e); } else { e->fn(e); } J->depth--; } static void mu_do_compile(struct mu_entry *e) { e->result = JS_Eval(e->J->ctx, e->source, strlen(e->source), e->filename ? e->filename : "[string]", JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY); } static void mu_do_call(struct mu_entry *e) { JSContext *ctx = e->J->ctx; if (JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_FUNCTION_BYTECODE || JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_MODULE) { e->result = JS_EvalFunction(ctx, e->fn_obj); e->fn_obj = JS_UNDEFINED; } else { e->result = JS_Call(ctx, e->fn_obj, e->thisv, e->argc, e->argv); } } static void mu_do_jobs(struct mu_entry *e) { js_State *J = e->J; JSContext *c; int i, r; for (i = 0; i < 10000; i++) { r = JS_ExecutePendingJob(J->rt, &c); if (r == 0) break; if (r < 0) { JSValue exc = JS_GetException(J->ctx); mu_push(J, exc); if (J->report) J->report(J, js_trystring(J, -1, "uncaught exception in promise job")); js_pop(J, 1); } } } void js_runjobs(js_State *J) { struct mu_entry e; /* Promise jobs are microtasks: while a script is still running (an * event dispatched from inside JavaScript), the outermost entry runs * them when it finishes. */ if (J->depth > 0) return; memset(&e, 0, sizeof(e)); e.fn = mu_do_jobs; mu_enter(J, &e); } static JSValue mu_compile(js_State *J, const char *filename, const char *source) { struct mu_entry e; memset(&e, 0, sizeof(e)); e.fn = mu_do_compile; e.filename = filename; e.source = source; mu_enter(J, &e); return e.result; } /* ---- ES modules ---- * * Module specifiers are resolved to absolute URLs by the host, and QuickJS * caches modules by that name, so every URL is fetched and evaluated once * per state, as in a browser. The loader runs synchronously inside the * engine: the host fetches the source while the script waits. */ static void mu_set_import_meta(JSContext *ctx, JSModuleDef *m, const char *url) { JSValue meta = JS_GetImportMeta(ctx, m); if (JS_IsException(meta)) return; JS_DefinePropertyValueStr(ctx, meta, "url", JS_NewString(ctx, url), JS_PROP_C_W_E); JS_FreeValue(ctx, meta); } static char *mu_module_normalize(JSContext *ctx, const char *base, const char *name, void *opaque) { js_State *J = (js_State *)opaque; char buf[1024]; size_t n; char *out; if (!J->mod_resolve || J->mod_resolve(base, name, buf, sizeof(buf))) snprintf(buf, sizeof(buf), "%s", name); n = strlen(buf); out = (char *)js_malloc(ctx, n + 1); if (out) memcpy(out, buf, n + 1); return out; } static JSModuleDef *mu_module_loader(JSContext *ctx, const char *name, void *opaque) { js_State *J = (js_State *)opaque; unsigned int len = 0; char *src; JSValue f; JSModuleDef *m; src = J->mod_load ? J->mod_load(name, &len) : 0; if (!src) { JS_ThrowReferenceError(ctx, "could not load module '%s'", name); return 0; } f = JS_Eval(ctx, src, len, name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); free(src); if (JS_IsException(f)) return 0; m = (JSModuleDef *)JS_VALUE_GET_PTR(f); mu_set_import_meta(ctx, m, name); JS_FreeValue(ctx, f); return m; } void js_setmodulehost(js_State *J, js_ModuleResolve resolve, js_ModuleLoad load) { J->mod_resolve = resolve; J->mod_load = load; JS_SetModuleLoaderFunc(J->rt, mu_module_normalize, mu_module_loader, J); } static void mu_do_module(struct mu_entry *e) { JSContext *ctx = e->J->ctx; JSValue f; f = JS_Eval(ctx, e->source, strlen(e->source), e->filename ? e->filename : "[module]", JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); if (JS_IsException(f)) { e->result = f; return; } mu_set_import_meta(ctx, (JSModuleDef *)JS_VALUE_GET_PTR(f), e->filename ? e->filename : ""); /* Links the import graph (the loader fetches dependencies), then runs * it; the result is the evaluation promise. */ e->result = JS_EvalFunction(ctx, f); } int js_ploadmodule(js_State *J, const char *filename, const char *source) { struct mu_entry e; JSValue p; int st; memset(&e, 0, sizeof(e)); e.fn = mu_do_module; e.filename = filename; e.source = source; mu_enter(J, &e); p = e.result; if (JS_IsException(p)) { mu_push(J, JS_GetException(J->ctx)); return 1; } js_runjobs(J); st = JS_PromiseState(J->ctx, p); if (st == JS_PROMISE_REJECTED) { JSValue r = JS_PromiseResult(J->ctx, p); JS_FreeValue(J->ctx, p); mu_push(J, r); return 1; } JS_FreeValue(J->ctx, p); mu_push(J, JS_UNDEFINED); return 0; } int js_ploadstring(js_State *J, const char *filename, const char *source) { JSValue f = mu_compile(J, filename, source); if (JS_IsException(f)) { mu_push(J, JS_GetException(J->ctx)); return 1; } mu_push(J, f); return 0; } void js_loadstring(js_State *J, const char *filename, const char *source) { JSValue f = mu_compile(J, filename, source); mu_check(J, f); mu_push(J, f); } /* Stack: function, this, n arguments. Replaced by the result (0) or the * error value (1). */ int js_pcall(js_State *J, int n) { int base = J->top - n - 2, i; JSValue fn, thisv, r, argv_small[8], *argv = argv_small; if (base < J->bot) { JS_ThrowInternalError(J->ctx, "pcall: stack underflow"); mu_push(J, JS_GetException(J->ctx)); return 1; } if (n > 8) { argv = (JSValue *)malloc((size_t)n * sizeof(JSValue)); if (!argv) { mu_popto(J, base); mu_push(J, JS_ThrowOutOfMemory(J->ctx)); mu_push(J, JS_GetException(J->ctx)); return 1; } } /* Copy out: a nested call may grow (move) the value stack. */ fn = JS_DupValue(J->ctx, J->stk[base].v); thisv = JS_DupValue(J->ctx, J->stk[base + 1].v); for (i = 0; i < n; i++) argv[i] = JS_DupValue(J->ctx, J->stk[base + 2 + i].v); mu_popto(J, base); { struct mu_entry e; memset(&e, 0, sizeof(e)); e.fn = mu_do_call; e.fn_obj = fn; e.thisv = thisv; e.argv = argv; e.argc = n; mu_enter(J, &e); fn = e.fn_obj; r = e.result; } JS_FreeValue(J->ctx, fn); JS_FreeValue(J->ctx, thisv); for (i = 0; i < n; i++) JS_FreeValue(J->ctx, argv[i]); if (argv != argv_small) free(argv); if (JS_IsException(r)) { mu_push(J, JS_GetException(J->ctx)); return 1; } mu_push(J, r); return 0; } /* ---- globals, registry and properties ---- */ void js_getglobal(js_State *J, const char *name) { JSValue g = JS_GetGlobalObject(J->ctx); JSValue v = JS_GetPropertyStr(J->ctx, g, name); JS_FreeValue(J->ctx, g); mu_check(J, v); mu_push(J, v); } void js_pushglobal(js_State *J) { mu_push(J, JS_GetGlobalObject(J->ctx)); } static int mu_flags(int atts) { int f = 0; if (!(atts & JS_READONLY)) f |= JS_PROP_WRITABLE; if (!(atts & JS_DONTENUM)) f |= JS_PROP_ENUMERABLE; if (!(atts & JS_DONTCONF)) f |= JS_PROP_CONFIGURABLE; return f; } void js_defglobal(js_State *J, const char *name, int atts) { JSValue v = mu_take(J); JSValue g = JS_GetGlobalObject(J->ctx); JS_DefinePropertyValueStr(J->ctx, g, name, v, mu_flags(atts)); JS_FreeValue(J->ctx, g); } void js_getregistry(js_State *J, const char *name) { mu_push(J, JS_GetPropertyStr(J->ctx, J->registry, name)); } void js_setregistry(js_State *J, const char *name) { JS_SetPropertyStr(J->ctx, J->registry, name, mu_take(J)); } void js_delregistry(js_State *J, const char *name) { JSAtom a = JS_NewAtom(J->ctx, name); JS_DeleteProperty(J->ctx, J->registry, a, 0); JS_FreeAtom(J->ctx, a); } /* The returned key lives in a small ring; callers copy it at once. */ const char *js_ref(js_State *J) { static char keys[8][24]; static int next; char *k = keys[next++ & 7]; snprintf(k, 24, "_ref%d", ++J->nextref); js_setregistry(J, k); return k; } void js_unref(js_State *J, const char *ref) { js_delregistry(J, ref); } void js_getproperty(js_State *J, int idx, const char *name) { JSValue v = JS_GetPropertyStr(J->ctx, mu_at(J, idx), name); mu_check(J, v); mu_push(J, v); } void js_setproperty(js_State *J, int idx, const char *name) { JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx)); JSValue v = mu_take(J); int r = JS_SetPropertyStr(J->ctx, obj, name, v); JS_FreeValue(J->ctx, obj); if (r < 0) mu_throw_value(J, JS_GetException(J->ctx)); } void js_setindex(js_State *J, int idx, int i) { JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx)); JSValue v = mu_take(J); int r = JS_SetPropertyUint32(J->ctx, obj, (uint32_t)i, v); JS_FreeValue(J->ctx, obj); if (r < 0) mu_throw_value(J, JS_GetException(J->ctx)); } /* Stack: ..., getter, setter (either may be undefined). */ void js_defaccessor(js_State *J, int idx, const char *name, int atts) { JSValue obj = mu_at(J, idx); JSValue get = JS_DupValue(J->ctx, mu_at(J, -2)); JSValue set = JS_DupValue(J->ctx, mu_at(J, -1)); JSAtom a = JS_NewAtom(J->ctx, name); if (!JS_IsFunction(J->ctx, get)) { JS_FreeValue(J->ctx, get); get = JS_UNDEFINED; } if (!JS_IsFunction(J->ctx, set)) { JS_FreeValue(J->ctx, set); set = JS_UNDEFINED; } JS_DefinePropertyGetSet(J->ctx, obj, a, get, set, mu_flags(atts) & ~JS_PROP_WRITABLE); JS_FreeAtom(J->ctx, a); js_pop(J, 2); } void js_newobject(js_State *J) { mu_push(J, JS_NewObject(J->ctx)); } void js_newarray(js_State *J) { mu_push(J, JS_NewArray(J->ctx)); } /* ---- pushing and popping ---- */ void js_pushundefined(js_State *J) { mu_push(J, JS_UNDEFINED); } void js_pushnull(js_State *J) { mu_push(J, JS_NULL); } void js_pushboolean(js_State *J, int v) { mu_push(J, JS_NewBool(J->ctx, v)); } void js_pushnumber(js_State *J, double v) { mu_push(J, JS_NewFloat64(J->ctx, v)); } void js_pushstring(js_State *J, const char *v) { mu_push(J, JS_NewString(J->ctx, v ? v : "")); } void js_pushlstring(js_State *J, const char *v, int n) { mu_push(J, JS_NewStringLen(J->ctx, v ? v : "", v && n > 0 ? (size_t)n : 0)); } void js_copy(js_State *J, int idx) { mu_push(J, JS_DupValue(J->ctx, mu_at(J, idx))); } void js_pop(js_State *J, int n) { int target = J->top - n; if (target < J->bot) target = J->bot; mu_popto(J, target); } int js_gettop(js_State *J) { return J->top - J->bot; } /* ---- type tests and conversions ---- */ int js_isdefined(js_State *J, int idx) { return !JS_IsUndefined(mu_at(J, idx)); } int js_isundefined(js_State *J, int idx) { return JS_IsUndefined(mu_at(J, idx)); } int js_isnull(js_State *J, int idx) { return JS_IsNull(mu_at(J, idx)); } int js_isboolean(js_State *J, int idx) { return JS_IsBool(mu_at(J, idx)); } int js_isnumber(js_State *J, int idx) { return JS_IsNumber(mu_at(J, idx)); } int js_isstring(js_State *J, int idx) { return JS_IsString(mu_at(J, idx)); } int js_isobject(js_State *J, int idx) { return JS_IsObject(mu_at(J, idx)); } int js_iscallable(js_State *J, int idx) { return JS_IsFunction(J->ctx, mu_at(J, idx)); } int js_toboolean(js_State *J, int idx) { return JS_ToBool(J->ctx, mu_at(J, idx)) > 0; } double js_tonumber(js_State *J, int idx) { double d = 0; if (JS_ToFloat64(J->ctx, &d, mu_at(J, idx)) < 0) mu_throw_value(J, JS_GetException(J->ctx)); return d; } int js_tointeger(js_State *J, int idx) { double d = js_tonumber(J, idx); if (d != d) return 0; if (d >= 2147483647.0) return 2147483647; if (d <= -2147483648.0) return (int)-2147483647 - 1; return (int)d; } static const char *mu_tostring(js_State *J, int idx, const char *error) { struct mu_slot *s = mu_slot_at(J, idx); JSValue str; if (!s) return "undefined"; if (s->cs && JS_IsString(s->v)) return s->cs; str = JS_ToString(J->ctx, s->v); if (JS_IsException(str)) { if (error) { JS_FreeValue(J->ctx, JS_GetException(J->ctx)); return error; } mu_throw_value(J, JS_GetException(J->ctx)); } /* Convert in place, as MuJS does. */ mu_slot_free(J, s); s->v = str; s->cs = JS_ToCString(J->ctx, str); return s->cs ? s->cs : ""; } const char *js_tostring(js_State *J, int idx) { return mu_tostring(J, idx, 0); } const char *js_trystring(js_State *J, int idx, const char *error) { return mu_tostring(J, idx, error); } int js_equal(js_State *J) { JSValue x = mu_at(J, -2), y = mu_at(J, -1); const char *a, *b; int eq; if (JS_IsObject(x) || JS_IsObject(y)) return JS_IsObject(x) && JS_IsObject(y) && JS_VALUE_GET_PTR(x) == JS_VALUE_GET_PTR(y); a = JS_ToCString(J->ctx, x); b = JS_ToCString(J->ctx, y); eq = a && b && !strcmp(a, b); JS_FreeCString(J->ctx, a); JS_FreeCString(J->ctx, b); return eq; }