js_mu.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. /* js_mu: the MuJS stack API used by js_browser.c, implemented on QuickJS.
  2. * See js_mu.h for the model. */
  3. #include <stdarg.h>
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #ifdef JS_MU_HOST
  9. #include <time.h>
  10. static unsigned int u_ticks_ms(void)
  11. {
  12. struct timespec t;
  13. clock_gettime(CLOCK_MONOTONIC, &t);
  14. return (unsigned int)(t.tv_sec * 1000u + t.tv_nsec / 1000000u);
  15. }
  16. #else
  17. #include "ucmd_lib.h"
  18. #endif
  19. #include "quickjs.h"
  20. #include "js_mu.h"
  21. #define MU_TRIES 64
  22. #define MU_STACK_INIT 256
  23. /* QuickJS recurses on the C stack for every JavaScript call, and the ring-3
  24. * stack is only 128 KB (USER_STACK_PAGES). Outermost entries into the
  25. * engine therefore switch to a private stack from the heap; QuickJS's own
  26. * limit leaves a margin below it, so deep recursion becomes a RangeError
  27. * instead of a page fault. */
  28. #ifndef JS_MU_STACK_BYTES
  29. #define JS_MU_STACK_BYTES (1024u * 1024u)
  30. #endif
  31. #define JS_MU_STACK_MARGIN (64u * 1024u)
  32. #if defined(__i386__) && !defined(JS_MU_HOST)
  33. #define MU_OWN_STACK 1
  34. /* mu_stack_call(top, fn, arg): run fn(arg) with ESP at `top`. EBP is
  35. * callee-saved, so it restores the caller's stack afterwards (a longjmp
  36. * out of fn restores ESP from its jmp_buf instead). */
  37. void mu_stack_call(void *top, void (*fn)(void *), void *arg);
  38. __asm__(".text\n"
  39. ".globl mu_stack_call\n"
  40. "mu_stack_call:\n"
  41. " pushl %ebp\n"
  42. " movl %esp, %ebp\n"
  43. " movl 8(%ebp), %eax\n"
  44. " movl 12(%ebp), %ecx\n"
  45. " movl 16(%ebp), %edx\n"
  46. " movl %eax, %esp\n"
  47. " andl $-16, %esp\n"
  48. " subl $12, %esp\n"
  49. " pushl %edx\n"
  50. " call *%ecx\n"
  51. " movl %ebp, %esp\n"
  52. " popl %ebp\n"
  53. " ret\n");
  54. #endif
  55. struct mu_slot {
  56. JSValue v;
  57. const char *cs; /* cached C string for js_tostring() */
  58. };
  59. struct mu_try {
  60. jmp_buf buf;
  61. int top, bot;
  62. void *fdata;
  63. };
  64. struct js_State {
  65. JSRuntime *rt;
  66. JSContext *ctx;
  67. struct mu_slot *stk;
  68. int top, bot, cap;
  69. void *fdata;
  70. struct mu_try tries[MU_TRIES];
  71. int ntry;
  72. JSValue registry;
  73. int nextref;
  74. js_Report report;
  75. js_Panic panic;
  76. unsigned int deadline;
  77. int limited;
  78. int depth; /* nested entries from C into JavaScript */
  79. void *jsstack; /* private engine stack (MU_OWN_STACK) */
  80. js_ModuleResolve mod_resolve;
  81. js_ModuleLoad mod_load;
  82. };
  83. struct mu_ud {
  84. const char *tag;
  85. void *data;
  86. js_HasProperty has;
  87. js_Put put;
  88. js_Delete del;
  89. JSValue backing; /* expando properties (jQuery data, ...) */
  90. };
  91. static JSClassID mu_ud_class;
  92. /* ---- value stack ---- */
  93. static void mu_push(js_State *J, JSValue v)
  94. {
  95. if (J->top >= J->cap) {
  96. int ncap = J->cap ? J->cap * 2 : MU_STACK_INIT;
  97. struct mu_slot *n = (struct mu_slot *)realloc(J->stk,
  98. (size_t)ncap * sizeof(*n));
  99. if (!n) {
  100. JS_FreeValue(J->ctx, v);
  101. if (J->panic)
  102. J->panic(J);
  103. abort();
  104. }
  105. J->stk = n;
  106. J->cap = ncap;
  107. }
  108. J->stk[J->top].v = v;
  109. J->stk[J->top].cs = 0;
  110. J->top++;
  111. }
  112. static void mu_slot_free(js_State *J, struct mu_slot *s)
  113. {
  114. if (s->cs)
  115. JS_FreeCString(J->ctx, s->cs);
  116. s->cs = 0;
  117. JS_FreeValue(J->ctx, s->v);
  118. s->v = JS_UNDEFINED;
  119. }
  120. static void mu_popto(js_State *J, int top)
  121. {
  122. while (J->top > top && J->top > 0)
  123. mu_slot_free(J, &J->stk[--J->top]);
  124. }
  125. /* Take ownership of the top value. */
  126. static JSValue mu_take(js_State *J)
  127. {
  128. struct mu_slot *s;
  129. JSValue v;
  130. if (J->top <= J->bot)
  131. return JS_UNDEFINED;
  132. s = &J->stk[--J->top];
  133. if (s->cs)
  134. JS_FreeCString(J->ctx, s->cs);
  135. v = s->v;
  136. s->cs = 0;
  137. s->v = JS_UNDEFINED;
  138. return v;
  139. }
  140. static int mu_abs(js_State *J, int idx)
  141. {
  142. return idx < 0 ? J->top + idx : J->bot + idx;
  143. }
  144. static struct mu_slot *mu_slot_at(js_State *J, int idx)
  145. {
  146. int i = mu_abs(J, idx);
  147. if (i < 0 || i >= J->top)
  148. return 0;
  149. return &J->stk[i];
  150. }
  151. static JSValue mu_at(js_State *J, int idx)
  152. {
  153. struct mu_slot *s = mu_slot_at(J, idx);
  154. return s ? s->v : JS_UNDEFINED;
  155. }
  156. /* ---- exceptions ---- */
  157. static __attribute__((noreturn)) void mu_throw_value(js_State *J, JSValue exc)
  158. {
  159. struct mu_try *t;
  160. if (J->ntry == 0) {
  161. mu_push(J, exc);
  162. if (J->panic)
  163. J->panic(J);
  164. abort();
  165. }
  166. t = &J->tries[--J->ntry];
  167. mu_popto(J, t->top);
  168. J->bot = t->bot;
  169. J->fdata = t->fdata;
  170. mu_push(J, exc);
  171. longjmp(t->buf, 1);
  172. }
  173. static void mu_check(js_State *J, JSValue v)
  174. {
  175. if (JS_IsException(v))
  176. mu_throw_value(J, JS_GetException(J->ctx));
  177. }
  178. jmp_buf *js_savetry(js_State *J)
  179. {
  180. struct mu_try *t;
  181. if (J->ntry >= MU_TRIES) {
  182. JS_ThrowInternalError(J->ctx, "try stack overflow");
  183. mu_throw_value(J, JS_GetException(J->ctx));
  184. }
  185. t = &J->tries[J->ntry++];
  186. t->top = J->top;
  187. t->bot = J->bot;
  188. t->fdata = J->fdata;
  189. return &t->buf;
  190. }
  191. void js_endtry(js_State *J)
  192. {
  193. if (J->ntry > 0)
  194. J->ntry--;
  195. }
  196. void js_throw(js_State *J)
  197. {
  198. mu_throw_value(J, mu_take(J));
  199. }
  200. void js_typeerror(js_State *J, const char *fmt, ...)
  201. {
  202. char buf[256];
  203. va_list ap;
  204. va_start(ap, fmt);
  205. vsnprintf(buf, sizeof(buf), fmt, ap);
  206. va_end(ap);
  207. JS_ThrowTypeError(J->ctx, "%s", buf);
  208. mu_throw_value(J, JS_GetException(J->ctx));
  209. }
  210. /* ---- C functions ---- */
  211. static JSValue mu_ptr_value(void *p)
  212. {
  213. return JS_NewFloat64(0, (double)(uintptr_t)p);
  214. }
  215. static void *mu_value_ptr(JSValueConst v)
  216. {
  217. double d;
  218. if (JS_VALUE_GET_TAG(v) == JS_TAG_INT)
  219. return (void *)(uintptr_t)(uint32_t)JS_VALUE_GET_INT(v);
  220. d = JS_VALUE_GET_FLOAT64(v);
  221. return (void *)(uintptr_t)d;
  222. }
  223. /* Every C callback is a catch boundary: a js_throw() inside it becomes a
  224. * QuickJS exception for the calling script. */
  225. static JSValue mu_trampoline(JSContext *ctx, JSValueConst this_val, int argc,
  226. JSValueConst *argv, int magic, JSValue *data)
  227. {
  228. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  229. js_CFunction fn = (js_CFunction)mu_value_ptr(data[0]);
  230. void *fdata = mu_value_ptr(data[1]);
  231. int savetop = J->top, savebot = J->bot, ntry = J->ntry, i;
  232. void *savefd = J->fdata;
  233. struct mu_try *t;
  234. JSValue ret;
  235. mu_push(J, JS_DupValue(ctx, this_val));
  236. for (i = 0; i < argc; i++)
  237. mu_push(J, JS_DupValue(ctx, argv[i]));
  238. for (; i < magic; i++)
  239. mu_push(J, JS_UNDEFINED);
  240. if (J->ntry >= MU_TRIES) {
  241. mu_popto(J, savetop);
  242. return JS_ThrowInternalError(ctx, "try stack overflow");
  243. }
  244. t = &J->tries[J->ntry++];
  245. t->top = savetop;
  246. t->bot = savebot;
  247. t->fdata = savefd;
  248. J->bot = savetop;
  249. J->fdata = fdata;
  250. if (setjmp(t->buf)) {
  251. JSValue exc = mu_take(J);
  252. mu_popto(J, savetop);
  253. J->bot = savebot;
  254. J->fdata = savefd;
  255. J->ntry = ntry;
  256. return JS_Throw(ctx, exc);
  257. }
  258. fn(J);
  259. J->ntry = ntry;
  260. ret = J->top > savetop ? JS_DupValue(ctx, J->stk[J->top - 1].v) :
  261. JS_UNDEFINED;
  262. mu_popto(J, savetop);
  263. J->bot = savebot;
  264. J->fdata = savefd;
  265. return ret;
  266. }
  267. void js_newcfunctionx(js_State *J, js_CFunction fun, const char *name,
  268. int length, void *data, js_Finalize finalize)
  269. {
  270. JSValue d[2];
  271. JSValue f;
  272. (void)name;
  273. (void)finalize;
  274. d[0] = mu_ptr_value((void *)fun);
  275. d[1] = mu_ptr_value(data);
  276. f = JS_NewCFunctionData(J->ctx, mu_trampoline, length, length, 2, d);
  277. /* MuJS lets `new` call any C function (Event, CustomEvent, ...
  278. * return their object); QuickJS needs the constructor bit for that. */
  279. JS_SetConstructorBit(J->ctx, f, 1);
  280. mu_push(J, f);
  281. }
  282. void js_newcfunction(js_State *J, js_CFunction fun, const char *name,
  283. int length)
  284. {
  285. js_newcfunctionx(J, fun, name, length, 0, 0);
  286. }
  287. void *js_currentfunctiondata(js_State *J)
  288. {
  289. return J->fdata;
  290. }
  291. /* ---- userdata ---- */
  292. /* Run a has/put/delete hook as a catch boundary. Returns the hook's
  293. * result, or -1 with a pending QuickJS exception. */
  294. static int mu_hook(js_State *J, js_HasProperty hook, void *p, JSAtom atom,
  295. int savetop)
  296. {
  297. const char *name = JS_AtomToCString(J->ctx, atom);
  298. int savebot = J->bot, ntry = J->ntry, r;
  299. void *savefd = J->fdata;
  300. struct mu_try *t;
  301. if (!name)
  302. return -1;
  303. if (J->ntry >= MU_TRIES) {
  304. JS_FreeCString(J->ctx, name);
  305. JS_ThrowInternalError(J->ctx, "try stack overflow");
  306. return -1;
  307. }
  308. t = &J->tries[J->ntry++];
  309. t->top = savetop;
  310. t->bot = savebot;
  311. t->fdata = savefd;
  312. if (setjmp(t->buf)) {
  313. JSValue exc = mu_take(J);
  314. JS_FreeCString(J->ctx, name);
  315. mu_popto(J, savetop);
  316. J->bot = savebot;
  317. J->fdata = savefd;
  318. J->ntry = ntry;
  319. JS_Throw(J->ctx, exc);
  320. return -1;
  321. }
  322. r = hook(J, p, name);
  323. J->ntry = ntry;
  324. J->bot = savebot;
  325. J->fdata = savefd;
  326. JS_FreeCString(J->ctx, name);
  327. return r;
  328. }
  329. /* has-hook lookup: 1 with *out set, 0 when the hook does not know the
  330. * name, -1 on exception. */
  331. static int mu_ud_lookup(JSContext *ctx, struct mu_ud *u, JSAtom atom,
  332. JSValue *out)
  333. {
  334. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  335. int savetop = J->top, r;
  336. if (!u->has)
  337. return 0;
  338. r = mu_hook(J, u->has, u->data, atom, savetop);
  339. if (r > 0) {
  340. *out = J->top > savetop ?
  341. JS_DupValue(ctx, J->stk[J->top - 1].v) : JS_UNDEFINED;
  342. mu_popto(J, savetop);
  343. return 1;
  344. }
  345. mu_popto(J, savetop);
  346. return r < 0 ? -1 : 0;
  347. }
  348. static struct mu_ud *mu_ud_of(JSValueConst obj)
  349. {
  350. return (struct mu_ud *)JS_GetOpaque(obj, mu_ud_class);
  351. }
  352. static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
  353. JSValueConst receiver)
  354. {
  355. struct mu_ud *u = mu_ud_of(obj);
  356. JSValue v;
  357. int r;
  358. (void)receiver;
  359. if (!u)
  360. return JS_UNDEFINED;
  361. r = mu_ud_lookup(ctx, u, atom, &v);
  362. if (r < 0)
  363. return JS_EXCEPTION;
  364. if (r > 0)
  365. return v;
  366. return JS_GetProperty(ctx, u->backing, atom);
  367. }
  368. static int mu_ud_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
  369. {
  370. struct mu_ud *u = mu_ud_of(obj);
  371. JSValue v;
  372. int r;
  373. if (!u)
  374. return 0;
  375. r = mu_ud_lookup(ctx, u, atom, &v);
  376. if (r < 0)
  377. return -1;
  378. if (r > 0) {
  379. JS_FreeValue(ctx, v);
  380. return 1;
  381. }
  382. return JS_HasProperty(ctx, u->backing, atom);
  383. }
  384. static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
  385. JSValueConst value, JSValueConst receiver, int flags)
  386. {
  387. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  388. struct mu_ud *u = mu_ud_of(obj);
  389. int savetop = J->top, r;
  390. (void)receiver;
  391. (void)flags;
  392. if (!u)
  393. return 0;
  394. if (u->put) {
  395. mu_push(J, JS_DupValue(ctx, value));
  396. r = mu_hook(J, u->put, u->data, atom, savetop);
  397. mu_popto(J, savetop);
  398. if (r < 0)
  399. return -1;
  400. if (r > 0)
  401. return 1;
  402. }
  403. return JS_SetProperty(ctx, u->backing, atom, JS_DupValue(ctx, value));
  404. }
  405. static int mu_ud_delete(JSContext *ctx, JSValueConst obj, JSAtom atom)
  406. {
  407. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  408. struct mu_ud *u = mu_ud_of(obj);
  409. int savetop = J->top, r;
  410. if (!u)
  411. return 1;
  412. if (u->del) {
  413. r = mu_hook(J, u->del, u->data, atom, savetop);
  414. mu_popto(J, savetop);
  415. if (r < 0)
  416. return -1;
  417. if (r > 0)
  418. return 1;
  419. }
  420. return JS_DeleteProperty(ctx, u->backing, atom, 0);
  421. }
  422. static int mu_ud_own(JSContext *ctx, JSPropertyDescriptor *desc,
  423. JSValueConst obj, JSAtom atom)
  424. {
  425. struct mu_ud *u = mu_ud_of(obj);
  426. JSValue v;
  427. int r;
  428. if (!u)
  429. return 0;
  430. r = mu_ud_lookup(ctx, u, atom, &v);
  431. if (r < 0)
  432. return -1;
  433. if (r > 0) {
  434. if (desc) {
  435. desc->flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |
  436. JS_PROP_CONFIGURABLE;
  437. desc->value = v;
  438. desc->getter = JS_UNDEFINED;
  439. desc->setter = JS_UNDEFINED;
  440. } else {
  441. JS_FreeValue(ctx, v);
  442. }
  443. return 1;
  444. }
  445. return JS_GetOwnProperty(ctx, desc, u->backing, atom);
  446. }
  447. static int mu_ud_names(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen,
  448. JSValueConst obj)
  449. {
  450. struct mu_ud *u = mu_ud_of(obj);
  451. if (!u) {
  452. *ptab = 0;
  453. *plen = 0;
  454. return 0;
  455. }
  456. return JS_GetOwnPropertyNames(ctx, ptab, plen, u->backing,
  457. JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK);
  458. }
  459. static int mu_ud_define(JSContext *ctx, JSValueConst this_obj, JSAtom prop,
  460. JSValueConst val, JSValueConst getter,
  461. JSValueConst setter, int flags)
  462. {
  463. struct mu_ud *u = mu_ud_of(this_obj);
  464. if (!u)
  465. return 0;
  466. return JS_DefineProperty(ctx, u->backing, prop, val, getter, setter,
  467. flags);
  468. }
  469. static void mu_ud_finalizer(JSRuntime *rt, JSValue val)
  470. {
  471. struct mu_ud *u = mu_ud_of(val);
  472. if (u) {
  473. JS_FreeValueRT(rt, u->backing);
  474. free(u);
  475. }
  476. }
  477. static void mu_ud_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark)
  478. {
  479. struct mu_ud *u = mu_ud_of(val);
  480. if (u)
  481. JS_MarkValue(rt, u->backing, mark);
  482. }
  483. static JSClassExoticMethods mu_ud_exotic = {
  484. .get_own_property = mu_ud_own,
  485. .get_own_property_names = mu_ud_names,
  486. .delete_property = mu_ud_delete,
  487. .define_own_property = mu_ud_define,
  488. .has_property = mu_ud_has,
  489. .get_property = mu_ud_get,
  490. .set_property = mu_ud_set,
  491. };
  492. static JSClassDef mu_ud_def = {
  493. .class_name = "HTMLElement",
  494. .finalizer = mu_ud_finalizer,
  495. .gc_mark = mu_ud_mark,
  496. .exotic = &mu_ud_exotic,
  497. };
  498. /* Pops the prototype from the top of the stack, like MuJS. */
  499. void js_newuserdatax(js_State *J, const char *tag, void *data,
  500. js_HasProperty has, js_Put put, js_Delete del,
  501. js_Finalize finalize)
  502. {
  503. JSValue proto = mu_take(J), obj;
  504. struct mu_ud *u;
  505. (void)finalize;
  506. if (!JS_IsObject(proto)) {
  507. JS_FreeValue(J->ctx, proto);
  508. proto = JS_NULL;
  509. }
  510. u = (struct mu_ud *)malloc(sizeof(*u));
  511. obj = JS_NewObjectProtoClass(J->ctx, proto, mu_ud_class);
  512. if (!u || JS_IsException(obj)) {
  513. free(u);
  514. JS_FreeValue(J->ctx, proto);
  515. mu_check(J, JS_IsException(obj) ? obj : JS_ThrowOutOfMemory(J->ctx));
  516. return;
  517. }
  518. u->tag = tag;
  519. u->data = data;
  520. u->has = has;
  521. u->put = put;
  522. u->del = del;
  523. u->backing = JS_NewObjectProto(J->ctx, proto);
  524. JS_FreeValue(J->ctx, proto);
  525. JS_SetOpaque(obj, u);
  526. mu_push(J, obj);
  527. }
  528. int js_isuserdata(js_State *J, int idx, const char *tag)
  529. {
  530. struct mu_ud *u = mu_ud_of(mu_at(J, idx));
  531. return u && !strcmp(u->tag, tag);
  532. }
  533. void *js_touserdata(js_State *J, int idx, const char *tag)
  534. {
  535. struct mu_ud *u = mu_ud_of(mu_at(J, idx));
  536. if (!u || strcmp(u->tag, tag))
  537. js_typeerror(J, "not a %s", tag);
  538. return u->data;
  539. }
  540. /* ---- state ---- */
  541. static int mu_interrupt(JSRuntime *rt, void *opaque)
  542. {
  543. js_State *J = (js_State *)opaque;
  544. (void)rt;
  545. return J->limited && (int)(u_ticks_ms() - J->deadline) >= 0;
  546. }
  547. /* An async function or a promise chain that fails with nobody listening
  548. * (Vite apps bootstrap from an async IIFE) would otherwise vanish without a
  549. * trace. The error goes to the report hook, like an uncaught exception.
  550. * A handler attached later in the same job cannot be detected here, so a
  551. * rejection that is handled late is still reported once. */
  552. static void mu_rejection(JSContext *ctx, JSValueConst promise,
  553. JSValueConst reason, int is_handled, void *opaque)
  554. {
  555. js_State *J = (js_State *)opaque;
  556. const char *msg, *stack = 0;
  557. JSValue st = JS_UNDEFINED;
  558. char buf[768];
  559. (void)promise;
  560. if (is_handled || !J->report)
  561. return;
  562. msg = JS_ToCString(ctx, reason);
  563. if (JS_IsObject(reason)) {
  564. st = JS_GetPropertyStr(ctx, reason, "stack");
  565. if (JS_IsString(st))
  566. stack = JS_ToCString(ctx, st);
  567. }
  568. snprintf(buf, sizeof(buf), "Uncaught (in promise) %s%s%s",
  569. msg ? msg : "error", stack ? "\n" : "", stack ? stack : "");
  570. J->report(J, buf);
  571. if (stack)
  572. JS_FreeCString(ctx, stack);
  573. JS_FreeValue(ctx, st);
  574. if (msg)
  575. JS_FreeCString(ctx, msg);
  576. else
  577. JS_FreeValue(ctx, JS_GetException(ctx));
  578. }
  579. js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
  580. {
  581. js_State *J;
  582. (void)alloc;
  583. (void)actx;
  584. (void)flags;
  585. J = (js_State *)calloc(1, sizeof(*J));
  586. if (!J)
  587. return 0;
  588. J->rt = JS_NewRuntime();
  589. if (!J->rt) {
  590. free(J);
  591. return 0;
  592. }
  593. #ifdef MU_OWN_STACK
  594. J->jsstack = malloc(JS_MU_STACK_BYTES);
  595. JS_SetMaxStackSize(J->rt, J->jsstack ?
  596. JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN :
  597. 48u * 1024u);
  598. #else
  599. JS_SetMaxStackSize(J->rt, JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN);
  600. #endif
  601. if (!mu_ud_class)
  602. JS_NewClassID(&mu_ud_class);
  603. JS_NewClass(J->rt, mu_ud_class, &mu_ud_def);
  604. J->ctx = JS_NewContext(J->rt);
  605. if (!J->ctx) {
  606. JS_FreeRuntime(J->rt);
  607. free(J);
  608. return 0;
  609. }
  610. JS_SetContextOpaque(J->ctx, J);
  611. JS_SetInterruptHandler(J->rt, mu_interrupt, J);
  612. JS_SetHostPromiseRejectionTracker(J->rt, mu_rejection, J);
  613. J->registry = JS_NewObject(J->ctx);
  614. return J;
  615. }
  616. void js_freestate(js_State *J)
  617. {
  618. if (!J)
  619. return;
  620. J->bot = 0;
  621. mu_popto(J, 0);
  622. JS_FreeValue(J->ctx, J->registry);
  623. JS_FreeContext(J->ctx);
  624. JS_FreeRuntime(J->rt);
  625. free(J->stk);
  626. free(J->jsstack);
  627. free(J);
  628. }
  629. void js_setreport(js_State *J, js_Report report)
  630. {
  631. J->report = report;
  632. }
  633. js_Panic js_atpanic(js_State *J, js_Panic panic)
  634. {
  635. js_Panic old = J->panic;
  636. J->panic = panic;
  637. return old;
  638. }
  639. void js_setlimit(js_State *J, int limit_ms, int memlimit)
  640. {
  641. (void)memlimit;
  642. J->limited = limit_ms > 0;
  643. J->deadline = u_ticks_ms() + (unsigned int)limit_ms;
  644. }
  645. /* ---- loading and calling ---- */
  646. /* Run an engine entry: on the private stack when this is the outermost
  647. * one, directly when JavaScript is already running (a nested callback). */
  648. struct mu_entry {
  649. js_State *J;
  650. void (*fn)(struct mu_entry *e);
  651. const char *filename, *source;
  652. JSValue fn_obj, thisv, *argv, result;
  653. int argc;
  654. };
  655. static void mu_entry_run(void *arg)
  656. {
  657. struct mu_entry *e = (struct mu_entry *)arg;
  658. JS_UpdateStackTop(e->J->rt);
  659. e->fn(e);
  660. }
  661. static void mu_enter(js_State *J, struct mu_entry *e)
  662. {
  663. e->J = J;
  664. if (J->depth++ == 0) {
  665. #ifdef MU_OWN_STACK
  666. if (J->jsstack) {
  667. mu_stack_call((char *)J->jsstack + JS_MU_STACK_BYTES,
  668. mu_entry_run, e);
  669. J->depth--;
  670. return;
  671. }
  672. #endif
  673. mu_entry_run(e);
  674. } else {
  675. e->fn(e);
  676. }
  677. J->depth--;
  678. }
  679. static void mu_do_compile(struct mu_entry *e)
  680. {
  681. e->result = JS_Eval(e->J->ctx, e->source, strlen(e->source),
  682. e->filename ? e->filename : "[string]",
  683. JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
  684. }
  685. static void mu_do_call(struct mu_entry *e)
  686. {
  687. JSContext *ctx = e->J->ctx;
  688. if (JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_FUNCTION_BYTECODE ||
  689. JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_MODULE) {
  690. e->result = JS_EvalFunction(ctx, e->fn_obj);
  691. e->fn_obj = JS_UNDEFINED;
  692. } else {
  693. e->result = JS_Call(ctx, e->fn_obj, e->thisv, e->argc,
  694. e->argv);
  695. }
  696. }
  697. static void mu_do_jobs(struct mu_entry *e)
  698. {
  699. js_State *J = e->J;
  700. JSContext *c;
  701. int i, r;
  702. for (i = 0; i < 10000; i++) {
  703. r = JS_ExecutePendingJob(J->rt, &c);
  704. if (r == 0)
  705. break;
  706. if (r < 0) {
  707. JSValue exc = JS_GetException(J->ctx);
  708. mu_push(J, exc);
  709. if (J->report)
  710. J->report(J, js_trystring(J, -1,
  711. "uncaught exception in promise job"));
  712. js_pop(J, 1);
  713. }
  714. }
  715. }
  716. void js_runjobs(js_State *J)
  717. {
  718. struct mu_entry e;
  719. /* Promise jobs are microtasks: while a script is still running (an
  720. * event dispatched from inside JavaScript), the outermost entry runs
  721. * them when it finishes. */
  722. if (J->depth > 0)
  723. return;
  724. memset(&e, 0, sizeof(e));
  725. e.fn = mu_do_jobs;
  726. mu_enter(J, &e);
  727. }
  728. static JSValue mu_compile(js_State *J, const char *filename,
  729. const char *source)
  730. {
  731. struct mu_entry e;
  732. memset(&e, 0, sizeof(e));
  733. e.fn = mu_do_compile;
  734. e.filename = filename;
  735. e.source = source;
  736. mu_enter(J, &e);
  737. return e.result;
  738. }
  739. /* ---- ES modules ----
  740. *
  741. * Module specifiers are resolved to absolute URLs by the host, and QuickJS
  742. * caches modules by that name, so every URL is fetched and evaluated once
  743. * per state, as in a browser. The loader runs synchronously inside the
  744. * engine: the host fetches the source while the script waits. */
  745. static void mu_set_import_meta(JSContext *ctx, JSModuleDef *m,
  746. const char *url)
  747. {
  748. JSValue meta = JS_GetImportMeta(ctx, m);
  749. if (JS_IsException(meta))
  750. return;
  751. JS_DefinePropertyValueStr(ctx, meta, "url", JS_NewString(ctx, url),
  752. JS_PROP_C_W_E);
  753. JS_FreeValue(ctx, meta);
  754. }
  755. static char *mu_module_normalize(JSContext *ctx, const char *base,
  756. const char *name, void *opaque)
  757. {
  758. js_State *J = (js_State *)opaque;
  759. char buf[1024];
  760. size_t n;
  761. char *out;
  762. if (!J->mod_resolve || J->mod_resolve(base, name, buf, sizeof(buf)))
  763. snprintf(buf, sizeof(buf), "%s", name);
  764. n = strlen(buf);
  765. out = (char *)js_malloc(ctx, n + 1);
  766. if (out)
  767. memcpy(out, buf, n + 1);
  768. return out;
  769. }
  770. static JSModuleDef *mu_module_loader(JSContext *ctx, const char *name,
  771. void *opaque)
  772. {
  773. js_State *J = (js_State *)opaque;
  774. unsigned int len = 0;
  775. char *src;
  776. JSValue f;
  777. JSModuleDef *m;
  778. src = J->mod_load ? J->mod_load(name, &len) : 0;
  779. if (!src) {
  780. JS_ThrowReferenceError(ctx, "could not load module '%s'", name);
  781. return 0;
  782. }
  783. f = JS_Eval(ctx, src, len, name,
  784. JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  785. free(src);
  786. if (JS_IsException(f))
  787. return 0;
  788. m = (JSModuleDef *)JS_VALUE_GET_PTR(f);
  789. mu_set_import_meta(ctx, m, name);
  790. JS_FreeValue(ctx, f);
  791. return m;
  792. }
  793. void js_setmodulehost(js_State *J, js_ModuleResolve resolve,
  794. js_ModuleLoad load)
  795. {
  796. J->mod_resolve = resolve;
  797. J->mod_load = load;
  798. JS_SetModuleLoaderFunc(J->rt, mu_module_normalize, mu_module_loader, J);
  799. }
  800. static void mu_do_module(struct mu_entry *e)
  801. {
  802. JSContext *ctx = e->J->ctx;
  803. JSValue f;
  804. f = JS_Eval(ctx, e->source, strlen(e->source),
  805. e->filename ? e->filename : "[module]",
  806. JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  807. if (JS_IsException(f)) {
  808. e->result = f;
  809. return;
  810. }
  811. mu_set_import_meta(ctx, (JSModuleDef *)JS_VALUE_GET_PTR(f),
  812. e->filename ? e->filename : "");
  813. /* Links the import graph (the loader fetches dependencies), then runs
  814. * it; the result is the evaluation promise. */
  815. e->result = JS_EvalFunction(ctx, f);
  816. }
  817. int js_ploadmodule(js_State *J, const char *filename, const char *source)
  818. {
  819. struct mu_entry e;
  820. JSValue p;
  821. int st;
  822. memset(&e, 0, sizeof(e));
  823. e.fn = mu_do_module;
  824. e.filename = filename;
  825. e.source = source;
  826. mu_enter(J, &e);
  827. p = e.result;
  828. if (JS_IsException(p)) {
  829. mu_push(J, JS_GetException(J->ctx));
  830. return 1;
  831. }
  832. js_runjobs(J);
  833. st = JS_PromiseState(J->ctx, p);
  834. if (st == JS_PROMISE_REJECTED) {
  835. JSValue r = JS_PromiseResult(J->ctx, p);
  836. JS_FreeValue(J->ctx, p);
  837. mu_push(J, r);
  838. return 1;
  839. }
  840. JS_FreeValue(J->ctx, p);
  841. mu_push(J, JS_UNDEFINED);
  842. return 0;
  843. }
  844. int js_ploadstring(js_State *J, const char *filename, const char *source)
  845. {
  846. JSValue f = mu_compile(J, filename, source);
  847. if (JS_IsException(f)) {
  848. mu_push(J, JS_GetException(J->ctx));
  849. return 1;
  850. }
  851. mu_push(J, f);
  852. return 0;
  853. }
  854. void js_loadstring(js_State *J, const char *filename, const char *source)
  855. {
  856. JSValue f = mu_compile(J, filename, source);
  857. mu_check(J, f);
  858. mu_push(J, f);
  859. }
  860. /* Stack: function, this, n arguments. Replaced by the result (0) or the
  861. * error value (1). */
  862. int js_pcall(js_State *J, int n)
  863. {
  864. int base = J->top - n - 2, i;
  865. JSValue fn, thisv, r, argv_small[8], *argv = argv_small;
  866. if (base < J->bot) {
  867. JS_ThrowInternalError(J->ctx, "pcall: stack underflow");
  868. mu_push(J, JS_GetException(J->ctx));
  869. return 1;
  870. }
  871. if (n > 8) {
  872. argv = (JSValue *)malloc((size_t)n * sizeof(JSValue));
  873. if (!argv) {
  874. mu_popto(J, base);
  875. mu_push(J, JS_ThrowOutOfMemory(J->ctx));
  876. mu_push(J, JS_GetException(J->ctx));
  877. return 1;
  878. }
  879. }
  880. /* Copy out: a nested call may grow (move) the value stack. */
  881. fn = JS_DupValue(J->ctx, J->stk[base].v);
  882. thisv = JS_DupValue(J->ctx, J->stk[base + 1].v);
  883. for (i = 0; i < n; i++)
  884. argv[i] = JS_DupValue(J->ctx, J->stk[base + 2 + i].v);
  885. mu_popto(J, base);
  886. {
  887. struct mu_entry e;
  888. memset(&e, 0, sizeof(e));
  889. e.fn = mu_do_call;
  890. e.fn_obj = fn;
  891. e.thisv = thisv;
  892. e.argv = argv;
  893. e.argc = n;
  894. mu_enter(J, &e);
  895. fn = e.fn_obj;
  896. r = e.result;
  897. }
  898. JS_FreeValue(J->ctx, fn);
  899. JS_FreeValue(J->ctx, thisv);
  900. for (i = 0; i < n; i++)
  901. JS_FreeValue(J->ctx, argv[i]);
  902. if (argv != argv_small)
  903. free(argv);
  904. if (JS_IsException(r)) {
  905. mu_push(J, JS_GetException(J->ctx));
  906. return 1;
  907. }
  908. mu_push(J, r);
  909. return 0;
  910. }
  911. /* ---- globals, registry and properties ---- */
  912. void js_getglobal(js_State *J, const char *name)
  913. {
  914. JSValue g = JS_GetGlobalObject(J->ctx);
  915. JSValue v = JS_GetPropertyStr(J->ctx, g, name);
  916. JS_FreeValue(J->ctx, g);
  917. mu_check(J, v);
  918. mu_push(J, v);
  919. }
  920. void js_pushglobal(js_State *J)
  921. {
  922. mu_push(J, JS_GetGlobalObject(J->ctx));
  923. }
  924. static int mu_flags(int atts)
  925. {
  926. int f = 0;
  927. if (!(atts & JS_READONLY))
  928. f |= JS_PROP_WRITABLE;
  929. if (!(atts & JS_DONTENUM))
  930. f |= JS_PROP_ENUMERABLE;
  931. if (!(atts & JS_DONTCONF))
  932. f |= JS_PROP_CONFIGURABLE;
  933. return f;
  934. }
  935. void js_defglobal(js_State *J, const char *name, int atts)
  936. {
  937. JSValue v = mu_take(J);
  938. JSValue g = JS_GetGlobalObject(J->ctx);
  939. JS_DefinePropertyValueStr(J->ctx, g, name, v, mu_flags(atts));
  940. JS_FreeValue(J->ctx, g);
  941. }
  942. void js_getregistry(js_State *J, const char *name)
  943. {
  944. mu_push(J, JS_GetPropertyStr(J->ctx, J->registry, name));
  945. }
  946. void js_setregistry(js_State *J, const char *name)
  947. {
  948. JS_SetPropertyStr(J->ctx, J->registry, name, mu_take(J));
  949. }
  950. void js_delregistry(js_State *J, const char *name)
  951. {
  952. JSAtom a = JS_NewAtom(J->ctx, name);
  953. JS_DeleteProperty(J->ctx, J->registry, a, 0);
  954. JS_FreeAtom(J->ctx, a);
  955. }
  956. /* The returned key lives in a small ring; callers copy it at once. */
  957. const char *js_ref(js_State *J)
  958. {
  959. static char keys[8][24];
  960. static int next;
  961. char *k = keys[next++ & 7];
  962. snprintf(k, 24, "_ref%d", ++J->nextref);
  963. js_setregistry(J, k);
  964. return k;
  965. }
  966. void js_unref(js_State *J, const char *ref)
  967. {
  968. js_delregistry(J, ref);
  969. }
  970. void js_getproperty(js_State *J, int idx, const char *name)
  971. {
  972. JSValue v = JS_GetPropertyStr(J->ctx, mu_at(J, idx), name);
  973. mu_check(J, v);
  974. mu_push(J, v);
  975. }
  976. void js_setproperty(js_State *J, int idx, const char *name)
  977. {
  978. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  979. JSValue v = mu_take(J);
  980. int r = JS_SetPropertyStr(J->ctx, obj, name, v);
  981. JS_FreeValue(J->ctx, obj);
  982. if (r < 0)
  983. mu_throw_value(J, JS_GetException(J->ctx));
  984. }
  985. void js_setindex(js_State *J, int idx, int i)
  986. {
  987. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  988. JSValue v = mu_take(J);
  989. int r = JS_SetPropertyUint32(J->ctx, obj, (uint32_t)i, v);
  990. JS_FreeValue(J->ctx, obj);
  991. if (r < 0)
  992. mu_throw_value(J, JS_GetException(J->ctx));
  993. }
  994. /* Stack: ..., getter, setter (either may be undefined). */
  995. void js_defaccessor(js_State *J, int idx, const char *name, int atts)
  996. {
  997. JSValue obj = mu_at(J, idx);
  998. JSValue get = JS_DupValue(J->ctx, mu_at(J, -2));
  999. JSValue set = JS_DupValue(J->ctx, mu_at(J, -1));
  1000. JSAtom a = JS_NewAtom(J->ctx, name);
  1001. if (!JS_IsFunction(J->ctx, get)) {
  1002. JS_FreeValue(J->ctx, get);
  1003. get = JS_UNDEFINED;
  1004. }
  1005. if (!JS_IsFunction(J->ctx, set)) {
  1006. JS_FreeValue(J->ctx, set);
  1007. set = JS_UNDEFINED;
  1008. }
  1009. JS_DefinePropertyGetSet(J->ctx, obj, a, get, set,
  1010. mu_flags(atts) & ~JS_PROP_WRITABLE);
  1011. JS_FreeAtom(J->ctx, a);
  1012. js_pop(J, 2);
  1013. }
  1014. void js_newobject(js_State *J)
  1015. {
  1016. mu_push(J, JS_NewObject(J->ctx));
  1017. }
  1018. void js_newarray(js_State *J)
  1019. {
  1020. mu_push(J, JS_NewArray(J->ctx));
  1021. }
  1022. /* ---- pushing and popping ---- */
  1023. void js_pushundefined(js_State *J) { mu_push(J, JS_UNDEFINED); }
  1024. void js_pushnull(js_State *J) { mu_push(J, JS_NULL); }
  1025. void js_pushboolean(js_State *J, int v) { mu_push(J, JS_NewBool(J->ctx, v)); }
  1026. void js_pushnumber(js_State *J, double v)
  1027. {
  1028. mu_push(J, JS_NewFloat64(J->ctx, v));
  1029. }
  1030. void js_pushstring(js_State *J, const char *v)
  1031. {
  1032. mu_push(J, JS_NewString(J->ctx, v ? v : ""));
  1033. }
  1034. void js_pushlstring(js_State *J, const char *v, int n)
  1035. {
  1036. mu_push(J, JS_NewStringLen(J->ctx, v ? v : "", v && n > 0 ? (size_t)n : 0));
  1037. }
  1038. void js_copy(js_State *J, int idx)
  1039. {
  1040. mu_push(J, JS_DupValue(J->ctx, mu_at(J, idx)));
  1041. }
  1042. void js_pop(js_State *J, int n)
  1043. {
  1044. int target = J->top - n;
  1045. if (target < J->bot)
  1046. target = J->bot;
  1047. mu_popto(J, target);
  1048. }
  1049. int js_gettop(js_State *J)
  1050. {
  1051. return J->top - J->bot;
  1052. }
  1053. /* ---- type tests and conversions ---- */
  1054. int js_isdefined(js_State *J, int idx) { return !JS_IsUndefined(mu_at(J, idx)); }
  1055. int js_isundefined(js_State *J, int idx) { return JS_IsUndefined(mu_at(J, idx)); }
  1056. int js_isnull(js_State *J, int idx) { return JS_IsNull(mu_at(J, idx)); }
  1057. int js_isboolean(js_State *J, int idx) { return JS_IsBool(mu_at(J, idx)); }
  1058. int js_isnumber(js_State *J, int idx) { return JS_IsNumber(mu_at(J, idx)); }
  1059. int js_isstring(js_State *J, int idx) { return JS_IsString(mu_at(J, idx)); }
  1060. int js_isobject(js_State *J, int idx) { return JS_IsObject(mu_at(J, idx)); }
  1061. int js_iscallable(js_State *J, int idx)
  1062. {
  1063. return JS_IsFunction(J->ctx, mu_at(J, idx));
  1064. }
  1065. int js_toboolean(js_State *J, int idx)
  1066. {
  1067. return JS_ToBool(J->ctx, mu_at(J, idx)) > 0;
  1068. }
  1069. double js_tonumber(js_State *J, int idx)
  1070. {
  1071. double d = 0;
  1072. if (JS_ToFloat64(J->ctx, &d, mu_at(J, idx)) < 0)
  1073. mu_throw_value(J, JS_GetException(J->ctx));
  1074. return d;
  1075. }
  1076. int js_tointeger(js_State *J, int idx)
  1077. {
  1078. double d = js_tonumber(J, idx);
  1079. if (d != d)
  1080. return 0;
  1081. if (d >= 2147483647.0)
  1082. return 2147483647;
  1083. if (d <= -2147483648.0)
  1084. return (int)-2147483647 - 1;
  1085. return (int)d;
  1086. }
  1087. static const char *mu_tostring(js_State *J, int idx, const char *error)
  1088. {
  1089. struct mu_slot *s = mu_slot_at(J, idx);
  1090. JSValue str;
  1091. if (!s)
  1092. return "undefined";
  1093. if (s->cs && JS_IsString(s->v))
  1094. return s->cs;
  1095. str = JS_ToString(J->ctx, s->v);
  1096. if (JS_IsException(str)) {
  1097. if (error) {
  1098. JS_FreeValue(J->ctx, JS_GetException(J->ctx));
  1099. return error;
  1100. }
  1101. mu_throw_value(J, JS_GetException(J->ctx));
  1102. }
  1103. /* Convert in place, as MuJS does. */
  1104. mu_slot_free(J, s);
  1105. s->v = str;
  1106. s->cs = JS_ToCString(J->ctx, str);
  1107. return s->cs ? s->cs : "";
  1108. }
  1109. const char *js_tostring(js_State *J, int idx)
  1110. {
  1111. return mu_tostring(J, idx, 0);
  1112. }
  1113. const char *js_trystring(js_State *J, int idx, const char *error)
  1114. {
  1115. return mu_tostring(J, idx, error);
  1116. }
  1117. int js_equal(js_State *J)
  1118. {
  1119. JSValue x = mu_at(J, -2), y = mu_at(J, -1);
  1120. const char *a, *b;
  1121. int eq;
  1122. if (JS_IsObject(x) || JS_IsObject(y))
  1123. return JS_IsObject(x) && JS_IsObject(y) &&
  1124. JS_VALUE_GET_PTR(x) == JS_VALUE_GET_PTR(y);
  1125. a = JS_ToCString(J->ctx, x);
  1126. b = JS_ToCString(J->ctx, y);
  1127. eq = a && b && !strcmp(a, b);
  1128. JS_FreeCString(J->ctx, a);
  1129. JS_FreeCString(J->ctx, b);
  1130. return eq;
  1131. }