js_mu.c 32 KB

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