js_mu.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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. /* Expandos live on the backing object; everything else comes from the
  353. * wrapper's own prototype chain with the wrapper as receiver, so a getter
  354. * or setter defined on a prototype sees the element as `this`, and a
  355. * changed prototype (a Custom Element upgrade) takes effect. */
  356. static JSValue mu_ud_inherited_get(JSContext *ctx, struct mu_ud *u,
  357. JSValueConst obj, JSAtom atom,
  358. JSValueConst receiver)
  359. {
  360. JSValue proto, v;
  361. int own = JS_GetOwnProperty(ctx, 0, u->backing, atom);
  362. if (own < 0)
  363. return JS_EXCEPTION;
  364. if (own)
  365. return JS_GetProperty(ctx, u->backing, atom);
  366. proto = JS_GetPrototype(ctx, obj);
  367. if (JS_IsException(proto))
  368. return proto;
  369. if (!JS_IsObject(proto)) {
  370. JS_FreeValue(ctx, proto);
  371. return JS_UNDEFINED;
  372. }
  373. v = JS_GetPropertyInternal(ctx, proto, atom,
  374. JS_IsObject(receiver) ? receiver : obj, 0);
  375. JS_FreeValue(ctx, proto);
  376. return v;
  377. }
  378. static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
  379. JSValueConst receiver)
  380. {
  381. struct mu_ud *u = mu_ud_of(obj);
  382. JSValue v;
  383. int r;
  384. if (!u)
  385. return JS_UNDEFINED;
  386. r = mu_ud_lookup(ctx, u, atom, &v);
  387. if (r < 0)
  388. return JS_EXCEPTION;
  389. if (r > 0)
  390. return v;
  391. return mu_ud_inherited_get(ctx, u, obj, atom, receiver);
  392. }
  393. static int mu_ud_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
  394. {
  395. struct mu_ud *u = mu_ud_of(obj);
  396. JSValue v;
  397. int r;
  398. if (!u)
  399. return 0;
  400. r = mu_ud_lookup(ctx, u, atom, &v);
  401. if (r < 0)
  402. return -1;
  403. if (r > 0) {
  404. JS_FreeValue(ctx, v);
  405. return 1;
  406. }
  407. r = JS_GetOwnProperty(ctx, 0, u->backing, atom);
  408. if (r != 0)
  409. return r;
  410. {
  411. JSValue proto = JS_GetPrototype(ctx, obj);
  412. if (JS_IsException(proto))
  413. return -1;
  414. r = JS_IsObject(proto) ? JS_HasProperty(ctx, proto, atom) : 0;
  415. JS_FreeValue(ctx, proto);
  416. }
  417. return r;
  418. }
  419. static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
  420. JSValueConst value, JSValueConst receiver, int flags)
  421. {
  422. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  423. struct mu_ud *u = mu_ud_of(obj);
  424. int savetop = J->top, r;
  425. (void)receiver;
  426. if (!u)
  427. return 0;
  428. if (u->put) {
  429. mu_push(J, JS_DupValue(ctx, value));
  430. r = mu_hook(J, u->put, u->data, atom, savetop);
  431. mu_popto(J, savetop);
  432. if (r < 0)
  433. return -1;
  434. if (r > 0)
  435. return 1;
  436. }
  437. r = JS_GetOwnProperty(ctx, 0, u->backing, atom);
  438. if (r < 0)
  439. return -1;
  440. if (!r) {
  441. /* A setter on the prototype chain runs with the element as
  442. * `this`; a plain new property lands on the backing object
  443. * through mu_ud_define(). */
  444. JSValue proto = JS_GetPrototype(ctx, obj);
  445. if (JS_IsException(proto))
  446. return -1;
  447. if (JS_IsObject(proto)) {
  448. r = JS_SetPropertyInternal(ctx, proto, atom,
  449. JS_DupValue(ctx, value),
  450. obj, flags);
  451. JS_FreeValue(ctx, proto);
  452. return r;
  453. }
  454. JS_FreeValue(ctx, proto);
  455. }
  456. return JS_SetProperty(ctx, u->backing, atom, JS_DupValue(ctx, value));
  457. }
  458. static int mu_ud_delete(JSContext *ctx, JSValueConst obj, JSAtom atom)
  459. {
  460. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  461. struct mu_ud *u = mu_ud_of(obj);
  462. int savetop = J->top, r;
  463. if (!u)
  464. return 1;
  465. if (u->del) {
  466. r = mu_hook(J, u->del, u->data, atom, savetop);
  467. mu_popto(J, savetop);
  468. if (r < 0)
  469. return -1;
  470. if (r > 0)
  471. return 1;
  472. }
  473. return JS_DeleteProperty(ctx, u->backing, atom, 0);
  474. }
  475. static int mu_ud_own(JSContext *ctx, JSPropertyDescriptor *desc,
  476. JSValueConst obj, JSAtom atom)
  477. {
  478. struct mu_ud *u = mu_ud_of(obj);
  479. JSValue v;
  480. int r;
  481. if (!u)
  482. return 0;
  483. r = mu_ud_lookup(ctx, u, atom, &v);
  484. if (r < 0)
  485. return -1;
  486. if (r > 0) {
  487. if (desc) {
  488. desc->flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |
  489. JS_PROP_CONFIGURABLE;
  490. desc->value = v;
  491. desc->getter = JS_UNDEFINED;
  492. desc->setter = JS_UNDEFINED;
  493. } else {
  494. JS_FreeValue(ctx, v);
  495. }
  496. return 1;
  497. }
  498. return JS_GetOwnProperty(ctx, desc, u->backing, atom);
  499. }
  500. static int mu_ud_names(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen,
  501. JSValueConst obj)
  502. {
  503. struct mu_ud *u = mu_ud_of(obj);
  504. if (!u) {
  505. *ptab = 0;
  506. *plen = 0;
  507. return 0;
  508. }
  509. return JS_GetOwnPropertyNames(ctx, ptab, plen, u->backing,
  510. JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK);
  511. }
  512. static int mu_ud_define(JSContext *ctx, JSValueConst this_obj, JSAtom prop,
  513. JSValueConst val, JSValueConst getter,
  514. JSValueConst setter, int flags)
  515. {
  516. struct mu_ud *u = mu_ud_of(this_obj);
  517. if (!u)
  518. return 0;
  519. return JS_DefineProperty(ctx, u->backing, prop, val, getter, setter,
  520. flags);
  521. }
  522. static void mu_ud_finalizer(JSRuntime *rt, JSValue val)
  523. {
  524. struct mu_ud *u = mu_ud_of(val);
  525. if (u) {
  526. JS_FreeValueRT(rt, u->backing);
  527. free(u);
  528. }
  529. }
  530. static void mu_ud_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark)
  531. {
  532. struct mu_ud *u = mu_ud_of(val);
  533. if (u)
  534. JS_MarkValue(rt, u->backing, mark);
  535. }
  536. static JSClassExoticMethods mu_ud_exotic = {
  537. .get_own_property = mu_ud_own,
  538. .get_own_property_names = mu_ud_names,
  539. .delete_property = mu_ud_delete,
  540. .define_own_property = mu_ud_define,
  541. .has_property = mu_ud_has,
  542. .get_property = mu_ud_get,
  543. .set_property = mu_ud_set,
  544. };
  545. static JSClassDef mu_ud_def = {
  546. .class_name = "HTMLElement",
  547. .finalizer = mu_ud_finalizer,
  548. .gc_mark = mu_ud_mark,
  549. .exotic = &mu_ud_exotic,
  550. };
  551. /* Pops the prototype from the top of the stack, like MuJS. */
  552. void js_newuserdatax(js_State *J, const char *tag, void *data,
  553. js_HasProperty has, js_Put put, js_Delete del,
  554. js_Finalize finalize)
  555. {
  556. JSValue proto = mu_take(J), obj;
  557. struct mu_ud *u;
  558. (void)finalize;
  559. if (!JS_IsObject(proto)) {
  560. JS_FreeValue(J->ctx, proto);
  561. proto = JS_NULL;
  562. }
  563. u = (struct mu_ud *)malloc(sizeof(*u));
  564. obj = JS_NewObjectProtoClass(J->ctx, proto, mu_ud_class);
  565. if (!u || JS_IsException(obj)) {
  566. free(u);
  567. JS_FreeValue(J->ctx, proto);
  568. mu_check(J, JS_IsException(obj) ? obj : JS_ThrowOutOfMemory(J->ctx));
  569. return;
  570. }
  571. u->tag = tag;
  572. u->data = data;
  573. u->has = has;
  574. u->put = put;
  575. u->del = del;
  576. u->backing = JS_NewObjectProto(J->ctx, proto);
  577. JS_FreeValue(J->ctx, proto);
  578. JS_SetOpaque(obj, u);
  579. mu_push(J, obj);
  580. }
  581. int js_isuserdata(js_State *J, int idx, const char *tag)
  582. {
  583. struct mu_ud *u = mu_ud_of(mu_at(J, idx));
  584. return u && !strcmp(u->tag, tag);
  585. }
  586. void *js_touserdata(js_State *J, int idx, const char *tag)
  587. {
  588. struct mu_ud *u = mu_ud_of(mu_at(J, idx));
  589. if (!u || strcmp(u->tag, tag))
  590. js_typeerror(J, "not a %s", tag);
  591. return u->data;
  592. }
  593. /* ---- state ---- */
  594. static int mu_interrupt(JSRuntime *rt, void *opaque)
  595. {
  596. js_State *J = (js_State *)opaque;
  597. static unsigned int calls;
  598. (void)rt;
  599. /* QuickJS asks every ~10000 operations; a 20 s budget needs nothing
  600. * like that precision, and each clock read is a syscall. */
  601. if (!J->limited || (++calls & 15))
  602. return 0;
  603. return (int)(u_ticks_ms() - J->deadline) >= 0;
  604. }
  605. /* An async function or a promise chain that fails with nobody listening
  606. * (Vite apps bootstrap from an async IIFE) would otherwise vanish without a
  607. * trace. The error goes to the report hook, like an uncaught exception.
  608. * A handler attached later in the same job cannot be detected here, so a
  609. * rejection that is handled late is still reported once. */
  610. static void mu_rejection(JSContext *ctx, JSValueConst promise,
  611. JSValueConst reason, int is_handled, void *opaque)
  612. {
  613. js_State *J = (js_State *)opaque;
  614. const char *msg, *stack = 0;
  615. JSValue st = JS_UNDEFINED;
  616. char buf[768];
  617. (void)promise;
  618. if (is_handled || !J->report)
  619. return;
  620. msg = JS_ToCString(ctx, reason);
  621. if (JS_IsObject(reason)) {
  622. st = JS_GetPropertyStr(ctx, reason, "stack");
  623. if (JS_IsString(st))
  624. stack = JS_ToCString(ctx, st);
  625. }
  626. snprintf(buf, sizeof(buf), "Uncaught (in promise) %s%s%s",
  627. msg ? msg : "error", stack ? "\n" : "", stack ? stack : "");
  628. J->report(J, buf);
  629. if (stack)
  630. JS_FreeCString(ctx, stack);
  631. JS_FreeValue(ctx, st);
  632. if (msg)
  633. JS_FreeCString(ctx, msg);
  634. else
  635. JS_FreeValue(ctx, JS_GetException(ctx));
  636. }
  637. js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
  638. {
  639. js_State *J;
  640. (void)alloc;
  641. (void)actx;
  642. (void)flags;
  643. J = (js_State *)calloc(1, sizeof(*J));
  644. if (!J)
  645. return 0;
  646. J->rt = JS_NewRuntime();
  647. if (!J->rt) {
  648. free(J);
  649. return 0;
  650. }
  651. #ifdef MU_OWN_STACK
  652. J->jsstack = malloc(JS_MU_STACK_BYTES);
  653. JS_SetMaxStackSize(J->rt, J->jsstack ?
  654. JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN :
  655. 48u * 1024u);
  656. #else
  657. JS_SetMaxStackSize(J->rt, JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN);
  658. #endif
  659. if (!mu_ud_class)
  660. JS_NewClassID(&mu_ud_class);
  661. JS_NewClass(J->rt, mu_ud_class, &mu_ud_def);
  662. J->ctx = JS_NewContext(J->rt);
  663. if (!J->ctx) {
  664. JS_FreeRuntime(J->rt);
  665. free(J);
  666. return 0;
  667. }
  668. JS_SetContextOpaque(J->ctx, J);
  669. JS_SetInterruptHandler(J->rt, mu_interrupt, J);
  670. JS_SetHostPromiseRejectionTracker(J->rt, mu_rejection, J);
  671. J->registry = JS_NewObject(J->ctx);
  672. return J;
  673. }
  674. void js_freestate(js_State *J)
  675. {
  676. if (!J)
  677. return;
  678. J->bot = 0;
  679. mu_popto(J, 0);
  680. JS_FreeValue(J->ctx, J->registry);
  681. JS_FreeContext(J->ctx);
  682. JS_FreeRuntime(J->rt);
  683. free(J->stk);
  684. free(J->jsstack);
  685. free(J);
  686. }
  687. void js_setreport(js_State *J, js_Report report)
  688. {
  689. J->report = report;
  690. }
  691. js_Panic js_atpanic(js_State *J, js_Panic panic)
  692. {
  693. js_Panic old = J->panic;
  694. J->panic = panic;
  695. return old;
  696. }
  697. void js_setlimit(js_State *J, int limit_ms, int memlimit)
  698. {
  699. (void)memlimit;
  700. J->limited = limit_ms > 0;
  701. J->deadline = u_ticks_ms() + (unsigned int)limit_ms;
  702. }
  703. /* ---- loading and calling ---- */
  704. /* Run an engine entry: on the private stack when this is the outermost
  705. * one, directly when JavaScript is already running (a nested callback). */
  706. struct mu_entry {
  707. js_State *J;
  708. void (*fn)(struct mu_entry *e);
  709. const char *filename, *source;
  710. JSValue fn_obj, thisv, *argv, result;
  711. int argc;
  712. };
  713. static void mu_entry_run(void *arg)
  714. {
  715. struct mu_entry *e = (struct mu_entry *)arg;
  716. JS_UpdateStackTop(e->J->rt);
  717. e->fn(e);
  718. }
  719. static void mu_enter(js_State *J, struct mu_entry *e)
  720. {
  721. e->J = J;
  722. if (J->depth++ == 0) {
  723. #ifdef MU_OWN_STACK
  724. if (J->jsstack) {
  725. mu_stack_call((char *)J->jsstack + JS_MU_STACK_BYTES,
  726. mu_entry_run, e);
  727. J->depth--;
  728. return;
  729. }
  730. #endif
  731. mu_entry_run(e);
  732. } else {
  733. e->fn(e);
  734. }
  735. J->depth--;
  736. }
  737. static void mu_do_compile(struct mu_entry *e)
  738. {
  739. e->result = JS_Eval(e->J->ctx, e->source, strlen(e->source),
  740. e->filename ? e->filename : "[string]",
  741. JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
  742. }
  743. static void mu_do_call(struct mu_entry *e)
  744. {
  745. JSContext *ctx = e->J->ctx;
  746. if (JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_FUNCTION_BYTECODE ||
  747. JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_MODULE) {
  748. e->result = JS_EvalFunction(ctx, e->fn_obj);
  749. e->fn_obj = JS_UNDEFINED;
  750. } else {
  751. e->result = JS_Call(ctx, e->fn_obj, e->thisv, e->argc,
  752. e->argv);
  753. }
  754. }
  755. static void mu_do_jobs(struct mu_entry *e)
  756. {
  757. js_State *J = e->J;
  758. JSContext *c;
  759. int i, r;
  760. for (i = 0; i < 10000; i++) {
  761. r = JS_ExecutePendingJob(J->rt, &c);
  762. if (r == 0)
  763. break;
  764. if (r < 0) {
  765. JSValue exc = JS_GetException(J->ctx);
  766. mu_push(J, exc);
  767. if (J->report)
  768. J->report(J, js_trystring(J, -1,
  769. "uncaught exception in promise job"));
  770. js_pop(J, 1);
  771. }
  772. }
  773. }
  774. void js_runjobs(js_State *J)
  775. {
  776. struct mu_entry e;
  777. /* Promise jobs are microtasks: while a script is still running (an
  778. * event dispatched from inside JavaScript), the outermost entry runs
  779. * them when it finishes. */
  780. if (J->depth > 0)
  781. return;
  782. memset(&e, 0, sizeof(e));
  783. e.fn = mu_do_jobs;
  784. mu_enter(J, &e);
  785. }
  786. static JSValue mu_compile(js_State *J, const char *filename,
  787. const char *source)
  788. {
  789. struct mu_entry e;
  790. memset(&e, 0, sizeof(e));
  791. e.fn = mu_do_compile;
  792. e.filename = filename;
  793. e.source = source;
  794. mu_enter(J, &e);
  795. return e.result;
  796. }
  797. /* ---- ES modules ----
  798. *
  799. * Module specifiers are resolved to absolute URLs by the host, and QuickJS
  800. * caches modules by that name, so every URL is fetched and evaluated once
  801. * per state, as in a browser. The loader runs synchronously inside the
  802. * engine: the host fetches the source while the script waits. */
  803. static void mu_set_import_meta(JSContext *ctx, JSModuleDef *m,
  804. const char *url)
  805. {
  806. JSValue meta = JS_GetImportMeta(ctx, m);
  807. if (JS_IsException(meta))
  808. return;
  809. JS_DefinePropertyValueStr(ctx, meta, "url", JS_NewString(ctx, url),
  810. JS_PROP_C_W_E);
  811. JS_FreeValue(ctx, meta);
  812. }
  813. static char *mu_module_normalize(JSContext *ctx, const char *base,
  814. const char *name, void *opaque)
  815. {
  816. js_State *J = (js_State *)opaque;
  817. char buf[1024];
  818. size_t n;
  819. char *out;
  820. if (!J->mod_resolve || J->mod_resolve(base, name, buf, sizeof(buf)))
  821. snprintf(buf, sizeof(buf), "%s", name);
  822. n = strlen(buf);
  823. out = (char *)js_malloc(ctx, n + 1);
  824. if (out)
  825. memcpy(out, buf, n + 1);
  826. return out;
  827. }
  828. static JSModuleDef *mu_module_loader(JSContext *ctx, const char *name,
  829. void *opaque)
  830. {
  831. js_State *J = (js_State *)opaque;
  832. unsigned int len = 0;
  833. char *src;
  834. JSValue f;
  835. JSModuleDef *m;
  836. src = J->mod_load ? J->mod_load(name, &len) : 0;
  837. if (!src) {
  838. JS_ThrowReferenceError(ctx, "could not load module '%s'", name);
  839. return 0;
  840. }
  841. f = JS_Eval(ctx, src, len, name,
  842. JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  843. free(src);
  844. if (JS_IsException(f))
  845. return 0;
  846. m = (JSModuleDef *)JS_VALUE_GET_PTR(f);
  847. mu_set_import_meta(ctx, m, name);
  848. JS_FreeValue(ctx, f);
  849. return m;
  850. }
  851. void js_setmodulehost(js_State *J, js_ModuleResolve resolve,
  852. js_ModuleLoad load)
  853. {
  854. J->mod_resolve = resolve;
  855. J->mod_load = load;
  856. JS_SetModuleLoaderFunc(J->rt, mu_module_normalize, mu_module_loader, J);
  857. }
  858. static void mu_do_module(struct mu_entry *e)
  859. {
  860. JSContext *ctx = e->J->ctx;
  861. JSValue f;
  862. f = JS_Eval(ctx, e->source, strlen(e->source),
  863. e->filename ? e->filename : "[module]",
  864. JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  865. if (JS_IsException(f)) {
  866. e->result = f;
  867. return;
  868. }
  869. mu_set_import_meta(ctx, (JSModuleDef *)JS_VALUE_GET_PTR(f),
  870. e->filename ? e->filename : "");
  871. /* Links the import graph (the loader fetches dependencies), then runs
  872. * it; the result is the evaluation promise. */
  873. e->result = JS_EvalFunction(ctx, f);
  874. }
  875. int js_ploadmodule(js_State *J, const char *filename, const char *source)
  876. {
  877. struct mu_entry e;
  878. JSValue p;
  879. int st;
  880. memset(&e, 0, sizeof(e));
  881. e.fn = mu_do_module;
  882. e.filename = filename;
  883. e.source = source;
  884. mu_enter(J, &e);
  885. p = e.result;
  886. if (JS_IsException(p)) {
  887. mu_push(J, JS_GetException(J->ctx));
  888. return 1;
  889. }
  890. js_runjobs(J);
  891. st = JS_PromiseState(J->ctx, p);
  892. if (st == JS_PROMISE_REJECTED) {
  893. JSValue r = JS_PromiseResult(J->ctx, p);
  894. JS_FreeValue(J->ctx, p);
  895. mu_push(J, r);
  896. return 1;
  897. }
  898. JS_FreeValue(J->ctx, p);
  899. mu_push(J, JS_UNDEFINED);
  900. return 0;
  901. }
  902. int js_ploadstring(js_State *J, const char *filename, const char *source)
  903. {
  904. JSValue f = mu_compile(J, filename, source);
  905. if (JS_IsException(f)) {
  906. mu_push(J, JS_GetException(J->ctx));
  907. return 1;
  908. }
  909. mu_push(J, f);
  910. return 0;
  911. }
  912. void js_loadstring(js_State *J, const char *filename, const char *source)
  913. {
  914. JSValue f = mu_compile(J, filename, source);
  915. mu_check(J, f);
  916. mu_push(J, f);
  917. }
  918. /* Stack: function, this, n arguments. Replaced by the result (0) or the
  919. * error value (1). */
  920. int js_pcall(js_State *J, int n)
  921. {
  922. int base = J->top - n - 2, i;
  923. JSValue fn, thisv, r, argv_small[8], *argv = argv_small;
  924. if (base < J->bot) {
  925. JS_ThrowInternalError(J->ctx, "pcall: stack underflow");
  926. mu_push(J, JS_GetException(J->ctx));
  927. return 1;
  928. }
  929. if (n > 8) {
  930. argv = (JSValue *)malloc((size_t)n * sizeof(JSValue));
  931. if (!argv) {
  932. mu_popto(J, base);
  933. mu_push(J, JS_ThrowOutOfMemory(J->ctx));
  934. mu_push(J, JS_GetException(J->ctx));
  935. return 1;
  936. }
  937. }
  938. /* Copy out: a nested call may grow (move) the value stack. */
  939. fn = JS_DupValue(J->ctx, J->stk[base].v);
  940. thisv = JS_DupValue(J->ctx, J->stk[base + 1].v);
  941. for (i = 0; i < n; i++)
  942. argv[i] = JS_DupValue(J->ctx, J->stk[base + 2 + i].v);
  943. mu_popto(J, base);
  944. {
  945. struct mu_entry e;
  946. memset(&e, 0, sizeof(e));
  947. e.fn = mu_do_call;
  948. e.fn_obj = fn;
  949. e.thisv = thisv;
  950. e.argv = argv;
  951. e.argc = n;
  952. mu_enter(J, &e);
  953. fn = e.fn_obj;
  954. r = e.result;
  955. }
  956. JS_FreeValue(J->ctx, fn);
  957. JS_FreeValue(J->ctx, thisv);
  958. for (i = 0; i < n; i++)
  959. JS_FreeValue(J->ctx, argv[i]);
  960. if (argv != argv_small)
  961. free(argv);
  962. if (JS_IsException(r)) {
  963. mu_push(J, JS_GetException(J->ctx));
  964. return 1;
  965. }
  966. mu_push(J, r);
  967. return 0;
  968. }
  969. /* ---- globals, registry and properties ---- */
  970. void js_getglobal(js_State *J, const char *name)
  971. {
  972. JSValue g = JS_GetGlobalObject(J->ctx);
  973. JSValue v = JS_GetPropertyStr(J->ctx, g, name);
  974. JS_FreeValue(J->ctx, g);
  975. mu_check(J, v);
  976. mu_push(J, v);
  977. }
  978. void js_pushglobal(js_State *J)
  979. {
  980. mu_push(J, JS_GetGlobalObject(J->ctx));
  981. }
  982. static int mu_flags(int atts)
  983. {
  984. int f = 0;
  985. if (!(atts & JS_READONLY))
  986. f |= JS_PROP_WRITABLE;
  987. if (!(atts & JS_DONTENUM))
  988. f |= JS_PROP_ENUMERABLE;
  989. if (!(atts & JS_DONTCONF))
  990. f |= JS_PROP_CONFIGURABLE;
  991. return f;
  992. }
  993. void js_defglobal(js_State *J, const char *name, int atts)
  994. {
  995. JSValue v = mu_take(J);
  996. JSValue g = JS_GetGlobalObject(J->ctx);
  997. JS_DefinePropertyValueStr(J->ctx, g, name, v, mu_flags(atts));
  998. JS_FreeValue(J->ctx, g);
  999. }
  1000. void js_getregistry(js_State *J, const char *name)
  1001. {
  1002. mu_push(J, JS_GetPropertyStr(J->ctx, J->registry, name));
  1003. }
  1004. void js_setregistry(js_State *J, const char *name)
  1005. {
  1006. JS_SetPropertyStr(J->ctx, J->registry, name, mu_take(J));
  1007. }
  1008. void js_delregistry(js_State *J, const char *name)
  1009. {
  1010. JSAtom a = JS_NewAtom(J->ctx, name);
  1011. JS_DeleteProperty(J->ctx, J->registry, a, 0);
  1012. JS_FreeAtom(J->ctx, a);
  1013. }
  1014. /* The returned key lives in a small ring; callers copy it at once. */
  1015. const char *js_ref(js_State *J)
  1016. {
  1017. static char keys[8][24];
  1018. static int next;
  1019. char *k = keys[next++ & 7];
  1020. snprintf(k, 24, "_ref%d", ++J->nextref);
  1021. js_setregistry(J, k);
  1022. return k;
  1023. }
  1024. void js_unref(js_State *J, const char *ref)
  1025. {
  1026. js_delregistry(J, ref);
  1027. }
  1028. void js_getproperty(js_State *J, int idx, const char *name)
  1029. {
  1030. JSValue v = JS_GetPropertyStr(J->ctx, mu_at(J, idx), name);
  1031. mu_check(J, v);
  1032. mu_push(J, v);
  1033. }
  1034. void js_setproperty(js_State *J, int idx, const char *name)
  1035. {
  1036. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  1037. JSValue v = mu_take(J);
  1038. int r = JS_SetPropertyStr(J->ctx, obj, name, v);
  1039. JS_FreeValue(J->ctx, obj);
  1040. if (r < 0)
  1041. mu_throw_value(J, JS_GetException(J->ctx));
  1042. }
  1043. void js_setindex(js_State *J, int idx, int i)
  1044. {
  1045. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  1046. JSValue v = mu_take(J);
  1047. int r = JS_SetPropertyUint32(J->ctx, obj, (uint32_t)i, v);
  1048. JS_FreeValue(J->ctx, obj);
  1049. if (r < 0)
  1050. mu_throw_value(J, JS_GetException(J->ctx));
  1051. }
  1052. /* Stack: ..., getter, setter (either may be undefined). */
  1053. void js_defaccessor(js_State *J, int idx, const char *name, int atts)
  1054. {
  1055. JSValue obj = mu_at(J, idx);
  1056. JSValue get = JS_DupValue(J->ctx, mu_at(J, -2));
  1057. JSValue set = JS_DupValue(J->ctx, mu_at(J, -1));
  1058. JSAtom a = JS_NewAtom(J->ctx, name);
  1059. if (!JS_IsFunction(J->ctx, get)) {
  1060. JS_FreeValue(J->ctx, get);
  1061. get = JS_UNDEFINED;
  1062. }
  1063. if (!JS_IsFunction(J->ctx, set)) {
  1064. JS_FreeValue(J->ctx, set);
  1065. set = JS_UNDEFINED;
  1066. }
  1067. JS_DefinePropertyGetSet(J->ctx, obj, a, get, set,
  1068. mu_flags(atts) & ~JS_PROP_WRITABLE);
  1069. JS_FreeAtom(J->ctx, a);
  1070. js_pop(J, 2);
  1071. }
  1072. void js_newobject(js_State *J)
  1073. {
  1074. mu_push(J, JS_NewObject(J->ctx));
  1075. }
  1076. void js_newarray(js_State *J)
  1077. {
  1078. mu_push(J, JS_NewArray(J->ctx));
  1079. }
  1080. /* ---- pushing and popping ---- */
  1081. void js_pushundefined(js_State *J) { mu_push(J, JS_UNDEFINED); }
  1082. void js_pushnull(js_State *J) { mu_push(J, JS_NULL); }
  1083. void js_pushboolean(js_State *J, int v) { mu_push(J, JS_NewBool(J->ctx, v)); }
  1084. void js_pushnumber(js_State *J, double v)
  1085. {
  1086. mu_push(J, JS_NewFloat64(J->ctx, v));
  1087. }
  1088. void js_pushstring(js_State *J, const char *v)
  1089. {
  1090. mu_push(J, JS_NewString(J->ctx, v ? v : ""));
  1091. }
  1092. void js_pushlstring(js_State *J, const char *v, int n)
  1093. {
  1094. mu_push(J, JS_NewStringLen(J->ctx, v ? v : "", v && n > 0 ? (size_t)n : 0));
  1095. }
  1096. void js_copy(js_State *J, int idx)
  1097. {
  1098. mu_push(J, JS_DupValue(J->ctx, mu_at(J, idx)));
  1099. }
  1100. void js_pop(js_State *J, int n)
  1101. {
  1102. int target = J->top - n;
  1103. if (target < J->bot)
  1104. target = J->bot;
  1105. mu_popto(J, target);
  1106. }
  1107. int js_gettop(js_State *J)
  1108. {
  1109. return J->top - J->bot;
  1110. }
  1111. /* ---- type tests and conversions ---- */
  1112. int js_isdefined(js_State *J, int idx) { return !JS_IsUndefined(mu_at(J, idx)); }
  1113. int js_isundefined(js_State *J, int idx) { return JS_IsUndefined(mu_at(J, idx)); }
  1114. int js_isnull(js_State *J, int idx) { return JS_IsNull(mu_at(J, idx)); }
  1115. int js_isboolean(js_State *J, int idx) { return JS_IsBool(mu_at(J, idx)); }
  1116. int js_isnumber(js_State *J, int idx) { return JS_IsNumber(mu_at(J, idx)); }
  1117. int js_isstring(js_State *J, int idx) { return JS_IsString(mu_at(J, idx)); }
  1118. int js_isobject(js_State *J, int idx) { return JS_IsObject(mu_at(J, idx)); }
  1119. int js_iscallable(js_State *J, int idx)
  1120. {
  1121. return JS_IsFunction(J->ctx, mu_at(J, idx));
  1122. }
  1123. int js_toboolean(js_State *J, int idx)
  1124. {
  1125. return JS_ToBool(J->ctx, mu_at(J, idx)) > 0;
  1126. }
  1127. double js_tonumber(js_State *J, int idx)
  1128. {
  1129. double d = 0;
  1130. if (JS_ToFloat64(J->ctx, &d, mu_at(J, idx)) < 0)
  1131. mu_throw_value(J, JS_GetException(J->ctx));
  1132. return d;
  1133. }
  1134. int js_tointeger(js_State *J, int idx)
  1135. {
  1136. double d = js_tonumber(J, idx);
  1137. if (d != d)
  1138. return 0;
  1139. if (d >= 2147483647.0)
  1140. return 2147483647;
  1141. if (d <= -2147483648.0)
  1142. return (int)-2147483647 - 1;
  1143. return (int)d;
  1144. }
  1145. static const char *mu_tostring(js_State *J, int idx, const char *error)
  1146. {
  1147. struct mu_slot *s = mu_slot_at(J, idx);
  1148. JSValue str;
  1149. if (!s)
  1150. return "undefined";
  1151. if (s->cs && JS_IsString(s->v))
  1152. return s->cs;
  1153. str = JS_ToString(J->ctx, s->v);
  1154. if (JS_IsException(str)) {
  1155. if (error) {
  1156. JS_FreeValue(J->ctx, JS_GetException(J->ctx));
  1157. return error;
  1158. }
  1159. mu_throw_value(J, JS_GetException(J->ctx));
  1160. }
  1161. /* Convert in place, as MuJS does. */
  1162. mu_slot_free(J, s);
  1163. s->v = str;
  1164. s->cs = JS_ToCString(J->ctx, str);
  1165. return s->cs ? s->cs : "";
  1166. }
  1167. const char *js_tostring(js_State *J, int idx)
  1168. {
  1169. return mu_tostring(J, idx, 0);
  1170. }
  1171. const char *js_trystring(js_State *J, int idx, const char *error)
  1172. {
  1173. return mu_tostring(J, idx, error);
  1174. }
  1175. int js_equal(js_State *J)
  1176. {
  1177. JSValue x = mu_at(J, -2), y = mu_at(J, -1);
  1178. const char *a, *b;
  1179. int eq;
  1180. if (JS_IsObject(x) || JS_IsObject(y))
  1181. return JS_IsObject(x) && JS_IsObject(y) &&
  1182. JS_VALUE_GET_PTR(x) == JS_VALUE_GET_PTR(y);
  1183. a = JS_ToCString(J->ctx, x);
  1184. b = JS_ToCString(J->ctx, y);
  1185. eq = a && b && !strcmp(a, b);
  1186. JS_FreeCString(J->ctx, a);
  1187. JS_FreeCString(J->ctx, b);
  1188. return eq;
  1189. }