| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148 |
- /* js_mu: the MuJS stack API used by js_browser.c, implemented on QuickJS.
- * See js_mu.h for the model. */
- #include <stdarg.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #ifdef JS_MU_HOST
- #include <time.h>
- 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) */
- };
- 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);
- }
- 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;
- (void)receiver;
- 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 JS_GetProperty(ctx, u->backing, atom);
- }
- 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;
- }
- return JS_HasProperty(ctx, u->backing, atom);
- }
- 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;
- (void)flags;
- 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;
- }
- 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;
- }
- 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);
- 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;
- }
- 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;
- }
|