js_mu.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  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. (void)rt;
  598. return J->limited && (int)(u_ticks_ms() - J->deadline) >= 0;
  599. }
  600. /* An async function or a promise chain that fails with nobody listening
  601. * (Vite apps bootstrap from an async IIFE) would otherwise vanish without a
  602. * trace. The error goes to the report hook, like an uncaught exception.
  603. * A handler attached later in the same job cannot be detected here, so a
  604. * rejection that is handled late is still reported once. */
  605. static void mu_rejection(JSContext *ctx, JSValueConst promise,
  606. JSValueConst reason, int is_handled, void *opaque)
  607. {
  608. js_State *J = (js_State *)opaque;
  609. const char *msg, *stack = 0;
  610. JSValue st = JS_UNDEFINED;
  611. char buf[768];
  612. (void)promise;
  613. if (is_handled || !J->report)
  614. return;
  615. msg = JS_ToCString(ctx, reason);
  616. if (JS_IsObject(reason)) {
  617. st = JS_GetPropertyStr(ctx, reason, "stack");
  618. if (JS_IsString(st))
  619. stack = JS_ToCString(ctx, st);
  620. }
  621. snprintf(buf, sizeof(buf), "Uncaught (in promise) %s%s%s",
  622. msg ? msg : "error", stack ? "\n" : "", stack ? stack : "");
  623. J->report(J, buf);
  624. if (stack)
  625. JS_FreeCString(ctx, stack);
  626. JS_FreeValue(ctx, st);
  627. if (msg)
  628. JS_FreeCString(ctx, msg);
  629. else
  630. JS_FreeValue(ctx, JS_GetException(ctx));
  631. }
  632. js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
  633. {
  634. js_State *J;
  635. (void)alloc;
  636. (void)actx;
  637. (void)flags;
  638. J = (js_State *)calloc(1, sizeof(*J));
  639. if (!J)
  640. return 0;
  641. J->rt = JS_NewRuntime();
  642. if (!J->rt) {
  643. free(J);
  644. return 0;
  645. }
  646. #ifdef MU_OWN_STACK
  647. J->jsstack = malloc(JS_MU_STACK_BYTES);
  648. JS_SetMaxStackSize(J->rt, J->jsstack ?
  649. JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN :
  650. 48u * 1024u);
  651. #else
  652. JS_SetMaxStackSize(J->rt, JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN);
  653. #endif
  654. if (!mu_ud_class)
  655. JS_NewClassID(&mu_ud_class);
  656. JS_NewClass(J->rt, mu_ud_class, &mu_ud_def);
  657. J->ctx = JS_NewContext(J->rt);
  658. if (!J->ctx) {
  659. JS_FreeRuntime(J->rt);
  660. free(J);
  661. return 0;
  662. }
  663. JS_SetContextOpaque(J->ctx, J);
  664. JS_SetInterruptHandler(J->rt, mu_interrupt, J);
  665. JS_SetHostPromiseRejectionTracker(J->rt, mu_rejection, J);
  666. J->registry = JS_NewObject(J->ctx);
  667. return J;
  668. }
  669. void js_freestate(js_State *J)
  670. {
  671. if (!J)
  672. return;
  673. J->bot = 0;
  674. mu_popto(J, 0);
  675. JS_FreeValue(J->ctx, J->registry);
  676. JS_FreeContext(J->ctx);
  677. JS_FreeRuntime(J->rt);
  678. free(J->stk);
  679. free(J->jsstack);
  680. free(J);
  681. }
  682. void js_setreport(js_State *J, js_Report report)
  683. {
  684. J->report = report;
  685. }
  686. js_Panic js_atpanic(js_State *J, js_Panic panic)
  687. {
  688. js_Panic old = J->panic;
  689. J->panic = panic;
  690. return old;
  691. }
  692. void js_setlimit(js_State *J, int limit_ms, int memlimit)
  693. {
  694. (void)memlimit;
  695. J->limited = limit_ms > 0;
  696. J->deadline = u_ticks_ms() + (unsigned int)limit_ms;
  697. }
  698. /* ---- loading and calling ---- */
  699. /* Run an engine entry: on the private stack when this is the outermost
  700. * one, directly when JavaScript is already running (a nested callback). */
  701. struct mu_entry {
  702. js_State *J;
  703. void (*fn)(struct mu_entry *e);
  704. const char *filename, *source;
  705. JSValue fn_obj, thisv, *argv, result;
  706. int argc;
  707. };
  708. static void mu_entry_run(void *arg)
  709. {
  710. struct mu_entry *e = (struct mu_entry *)arg;
  711. JS_UpdateStackTop(e->J->rt);
  712. e->fn(e);
  713. }
  714. static void mu_enter(js_State *J, struct mu_entry *e)
  715. {
  716. e->J = J;
  717. if (J->depth++ == 0) {
  718. #ifdef MU_OWN_STACK
  719. if (J->jsstack) {
  720. mu_stack_call((char *)J->jsstack + JS_MU_STACK_BYTES,
  721. mu_entry_run, e);
  722. J->depth--;
  723. return;
  724. }
  725. #endif
  726. mu_entry_run(e);
  727. } else {
  728. e->fn(e);
  729. }
  730. J->depth--;
  731. }
  732. static void mu_do_compile(struct mu_entry *e)
  733. {
  734. e->result = JS_Eval(e->J->ctx, e->source, strlen(e->source),
  735. e->filename ? e->filename : "[string]",
  736. JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
  737. }
  738. static void mu_do_call(struct mu_entry *e)
  739. {
  740. JSContext *ctx = e->J->ctx;
  741. if (JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_FUNCTION_BYTECODE ||
  742. JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_MODULE) {
  743. e->result = JS_EvalFunction(ctx, e->fn_obj);
  744. e->fn_obj = JS_UNDEFINED;
  745. } else {
  746. e->result = JS_Call(ctx, e->fn_obj, e->thisv, e->argc,
  747. e->argv);
  748. }
  749. }
  750. static void mu_do_jobs(struct mu_entry *e)
  751. {
  752. js_State *J = e->J;
  753. JSContext *c;
  754. int i, r;
  755. for (i = 0; i < 10000; i++) {
  756. r = JS_ExecutePendingJob(J->rt, &c);
  757. if (r == 0)
  758. break;
  759. if (r < 0) {
  760. JSValue exc = JS_GetException(J->ctx);
  761. mu_push(J, exc);
  762. if (J->report)
  763. J->report(J, js_trystring(J, -1,
  764. "uncaught exception in promise job"));
  765. js_pop(J, 1);
  766. }
  767. }
  768. }
  769. void js_runjobs(js_State *J)
  770. {
  771. struct mu_entry e;
  772. /* Promise jobs are microtasks: while a script is still running (an
  773. * event dispatched from inside JavaScript), the outermost entry runs
  774. * them when it finishes. */
  775. if (J->depth > 0)
  776. return;
  777. memset(&e, 0, sizeof(e));
  778. e.fn = mu_do_jobs;
  779. mu_enter(J, &e);
  780. }
  781. static JSValue mu_compile(js_State *J, const char *filename,
  782. const char *source)
  783. {
  784. struct mu_entry e;
  785. memset(&e, 0, sizeof(e));
  786. e.fn = mu_do_compile;
  787. e.filename = filename;
  788. e.source = source;
  789. mu_enter(J, &e);
  790. return e.result;
  791. }
  792. /* ---- ES modules ----
  793. *
  794. * Module specifiers are resolved to absolute URLs by the host, and QuickJS
  795. * caches modules by that name, so every URL is fetched and evaluated once
  796. * per state, as in a browser. The loader runs synchronously inside the
  797. * engine: the host fetches the source while the script waits. */
  798. static void mu_set_import_meta(JSContext *ctx, JSModuleDef *m,
  799. const char *url)
  800. {
  801. JSValue meta = JS_GetImportMeta(ctx, m);
  802. if (JS_IsException(meta))
  803. return;
  804. JS_DefinePropertyValueStr(ctx, meta, "url", JS_NewString(ctx, url),
  805. JS_PROP_C_W_E);
  806. JS_FreeValue(ctx, meta);
  807. }
  808. static char *mu_module_normalize(JSContext *ctx, const char *base,
  809. const char *name, void *opaque)
  810. {
  811. js_State *J = (js_State *)opaque;
  812. char buf[1024];
  813. size_t n;
  814. char *out;
  815. if (!J->mod_resolve || J->mod_resolve(base, name, buf, sizeof(buf)))
  816. snprintf(buf, sizeof(buf), "%s", name);
  817. n = strlen(buf);
  818. out = (char *)js_malloc(ctx, n + 1);
  819. if (out)
  820. memcpy(out, buf, n + 1);
  821. return out;
  822. }
  823. static JSModuleDef *mu_module_loader(JSContext *ctx, const char *name,
  824. void *opaque)
  825. {
  826. js_State *J = (js_State *)opaque;
  827. unsigned int len = 0;
  828. char *src;
  829. JSValue f;
  830. JSModuleDef *m;
  831. src = J->mod_load ? J->mod_load(name, &len) : 0;
  832. if (!src) {
  833. JS_ThrowReferenceError(ctx, "could not load module '%s'", name);
  834. return 0;
  835. }
  836. f = JS_Eval(ctx, src, len, name,
  837. JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  838. free(src);
  839. if (JS_IsException(f))
  840. return 0;
  841. m = (JSModuleDef *)JS_VALUE_GET_PTR(f);
  842. mu_set_import_meta(ctx, m, name);
  843. JS_FreeValue(ctx, f);
  844. return m;
  845. }
  846. void js_setmodulehost(js_State *J, js_ModuleResolve resolve,
  847. js_ModuleLoad load)
  848. {
  849. J->mod_resolve = resolve;
  850. J->mod_load = load;
  851. JS_SetModuleLoaderFunc(J->rt, mu_module_normalize, mu_module_loader, J);
  852. }
  853. static void mu_do_module(struct mu_entry *e)
  854. {
  855. JSContext *ctx = e->J->ctx;
  856. JSValue f;
  857. f = JS_Eval(ctx, e->source, strlen(e->source),
  858. e->filename ? e->filename : "[module]",
  859. JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
  860. if (JS_IsException(f)) {
  861. e->result = f;
  862. return;
  863. }
  864. mu_set_import_meta(ctx, (JSModuleDef *)JS_VALUE_GET_PTR(f),
  865. e->filename ? e->filename : "");
  866. /* Links the import graph (the loader fetches dependencies), then runs
  867. * it; the result is the evaluation promise. */
  868. e->result = JS_EvalFunction(ctx, f);
  869. }
  870. int js_ploadmodule(js_State *J, const char *filename, const char *source)
  871. {
  872. struct mu_entry e;
  873. JSValue p;
  874. int st;
  875. memset(&e, 0, sizeof(e));
  876. e.fn = mu_do_module;
  877. e.filename = filename;
  878. e.source = source;
  879. mu_enter(J, &e);
  880. p = e.result;
  881. if (JS_IsException(p)) {
  882. mu_push(J, JS_GetException(J->ctx));
  883. return 1;
  884. }
  885. js_runjobs(J);
  886. st = JS_PromiseState(J->ctx, p);
  887. if (st == JS_PROMISE_REJECTED) {
  888. JSValue r = JS_PromiseResult(J->ctx, p);
  889. JS_FreeValue(J->ctx, p);
  890. mu_push(J, r);
  891. return 1;
  892. }
  893. JS_FreeValue(J->ctx, p);
  894. mu_push(J, JS_UNDEFINED);
  895. return 0;
  896. }
  897. int js_ploadstring(js_State *J, const char *filename, const char *source)
  898. {
  899. JSValue f = mu_compile(J, filename, source);
  900. if (JS_IsException(f)) {
  901. mu_push(J, JS_GetException(J->ctx));
  902. return 1;
  903. }
  904. mu_push(J, f);
  905. return 0;
  906. }
  907. void js_loadstring(js_State *J, const char *filename, const char *source)
  908. {
  909. JSValue f = mu_compile(J, filename, source);
  910. mu_check(J, f);
  911. mu_push(J, f);
  912. }
  913. /* Stack: function, this, n arguments. Replaced by the result (0) or the
  914. * error value (1). */
  915. int js_pcall(js_State *J, int n)
  916. {
  917. int base = J->top - n - 2, i;
  918. JSValue fn, thisv, r, argv_small[8], *argv = argv_small;
  919. if (base < J->bot) {
  920. JS_ThrowInternalError(J->ctx, "pcall: stack underflow");
  921. mu_push(J, JS_GetException(J->ctx));
  922. return 1;
  923. }
  924. if (n > 8) {
  925. argv = (JSValue *)malloc((size_t)n * sizeof(JSValue));
  926. if (!argv) {
  927. mu_popto(J, base);
  928. mu_push(J, JS_ThrowOutOfMemory(J->ctx));
  929. mu_push(J, JS_GetException(J->ctx));
  930. return 1;
  931. }
  932. }
  933. /* Copy out: a nested call may grow (move) the value stack. */
  934. fn = JS_DupValue(J->ctx, J->stk[base].v);
  935. thisv = JS_DupValue(J->ctx, J->stk[base + 1].v);
  936. for (i = 0; i < n; i++)
  937. argv[i] = JS_DupValue(J->ctx, J->stk[base + 2 + i].v);
  938. mu_popto(J, base);
  939. {
  940. struct mu_entry e;
  941. memset(&e, 0, sizeof(e));
  942. e.fn = mu_do_call;
  943. e.fn_obj = fn;
  944. e.thisv = thisv;
  945. e.argv = argv;
  946. e.argc = n;
  947. mu_enter(J, &e);
  948. fn = e.fn_obj;
  949. r = e.result;
  950. }
  951. JS_FreeValue(J->ctx, fn);
  952. JS_FreeValue(J->ctx, thisv);
  953. for (i = 0; i < n; i++)
  954. JS_FreeValue(J->ctx, argv[i]);
  955. if (argv != argv_small)
  956. free(argv);
  957. if (JS_IsException(r)) {
  958. mu_push(J, JS_GetException(J->ctx));
  959. return 1;
  960. }
  961. mu_push(J, r);
  962. return 0;
  963. }
  964. /* ---- globals, registry and properties ---- */
  965. void js_getglobal(js_State *J, const char *name)
  966. {
  967. JSValue g = JS_GetGlobalObject(J->ctx);
  968. JSValue v = JS_GetPropertyStr(J->ctx, g, name);
  969. JS_FreeValue(J->ctx, g);
  970. mu_check(J, v);
  971. mu_push(J, v);
  972. }
  973. void js_pushglobal(js_State *J)
  974. {
  975. mu_push(J, JS_GetGlobalObject(J->ctx));
  976. }
  977. static int mu_flags(int atts)
  978. {
  979. int f = 0;
  980. if (!(atts & JS_READONLY))
  981. f |= JS_PROP_WRITABLE;
  982. if (!(atts & JS_DONTENUM))
  983. f |= JS_PROP_ENUMERABLE;
  984. if (!(atts & JS_DONTCONF))
  985. f |= JS_PROP_CONFIGURABLE;
  986. return f;
  987. }
  988. void js_defglobal(js_State *J, const char *name, int atts)
  989. {
  990. JSValue v = mu_take(J);
  991. JSValue g = JS_GetGlobalObject(J->ctx);
  992. JS_DefinePropertyValueStr(J->ctx, g, name, v, mu_flags(atts));
  993. JS_FreeValue(J->ctx, g);
  994. }
  995. void js_getregistry(js_State *J, const char *name)
  996. {
  997. mu_push(J, JS_GetPropertyStr(J->ctx, J->registry, name));
  998. }
  999. void js_setregistry(js_State *J, const char *name)
  1000. {
  1001. JS_SetPropertyStr(J->ctx, J->registry, name, mu_take(J));
  1002. }
  1003. void js_delregistry(js_State *J, const char *name)
  1004. {
  1005. JSAtom a = JS_NewAtom(J->ctx, name);
  1006. JS_DeleteProperty(J->ctx, J->registry, a, 0);
  1007. JS_FreeAtom(J->ctx, a);
  1008. }
  1009. /* The returned key lives in a small ring; callers copy it at once. */
  1010. const char *js_ref(js_State *J)
  1011. {
  1012. static char keys[8][24];
  1013. static int next;
  1014. char *k = keys[next++ & 7];
  1015. snprintf(k, 24, "_ref%d", ++J->nextref);
  1016. js_setregistry(J, k);
  1017. return k;
  1018. }
  1019. void js_unref(js_State *J, const char *ref)
  1020. {
  1021. js_delregistry(J, ref);
  1022. }
  1023. void js_getproperty(js_State *J, int idx, const char *name)
  1024. {
  1025. JSValue v = JS_GetPropertyStr(J->ctx, mu_at(J, idx), name);
  1026. mu_check(J, v);
  1027. mu_push(J, v);
  1028. }
  1029. void js_setproperty(js_State *J, int idx, const char *name)
  1030. {
  1031. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  1032. JSValue v = mu_take(J);
  1033. int r = JS_SetPropertyStr(J->ctx, obj, name, v);
  1034. JS_FreeValue(J->ctx, obj);
  1035. if (r < 0)
  1036. mu_throw_value(J, JS_GetException(J->ctx));
  1037. }
  1038. void js_setindex(js_State *J, int idx, int i)
  1039. {
  1040. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  1041. JSValue v = mu_take(J);
  1042. int r = JS_SetPropertyUint32(J->ctx, obj, (uint32_t)i, v);
  1043. JS_FreeValue(J->ctx, obj);
  1044. if (r < 0)
  1045. mu_throw_value(J, JS_GetException(J->ctx));
  1046. }
  1047. /* Stack: ..., getter, setter (either may be undefined). */
  1048. void js_defaccessor(js_State *J, int idx, const char *name, int atts)
  1049. {
  1050. JSValue obj = mu_at(J, idx);
  1051. JSValue get = JS_DupValue(J->ctx, mu_at(J, -2));
  1052. JSValue set = JS_DupValue(J->ctx, mu_at(J, -1));
  1053. JSAtom a = JS_NewAtom(J->ctx, name);
  1054. if (!JS_IsFunction(J->ctx, get)) {
  1055. JS_FreeValue(J->ctx, get);
  1056. get = JS_UNDEFINED;
  1057. }
  1058. if (!JS_IsFunction(J->ctx, set)) {
  1059. JS_FreeValue(J->ctx, set);
  1060. set = JS_UNDEFINED;
  1061. }
  1062. JS_DefinePropertyGetSet(J->ctx, obj, a, get, set,
  1063. mu_flags(atts) & ~JS_PROP_WRITABLE);
  1064. JS_FreeAtom(J->ctx, a);
  1065. js_pop(J, 2);
  1066. }
  1067. void js_newobject(js_State *J)
  1068. {
  1069. mu_push(J, JS_NewObject(J->ctx));
  1070. }
  1071. void js_newarray(js_State *J)
  1072. {
  1073. mu_push(J, JS_NewArray(J->ctx));
  1074. }
  1075. /* ---- pushing and popping ---- */
  1076. void js_pushundefined(js_State *J) { mu_push(J, JS_UNDEFINED); }
  1077. void js_pushnull(js_State *J) { mu_push(J, JS_NULL); }
  1078. void js_pushboolean(js_State *J, int v) { mu_push(J, JS_NewBool(J->ctx, v)); }
  1079. void js_pushnumber(js_State *J, double v)
  1080. {
  1081. mu_push(J, JS_NewFloat64(J->ctx, v));
  1082. }
  1083. void js_pushstring(js_State *J, const char *v)
  1084. {
  1085. mu_push(J, JS_NewString(J->ctx, v ? v : ""));
  1086. }
  1087. void js_pushlstring(js_State *J, const char *v, int n)
  1088. {
  1089. mu_push(J, JS_NewStringLen(J->ctx, v ? v : "", v && n > 0 ? (size_t)n : 0));
  1090. }
  1091. void js_copy(js_State *J, int idx)
  1092. {
  1093. mu_push(J, JS_DupValue(J->ctx, mu_at(J, idx)));
  1094. }
  1095. void js_pop(js_State *J, int n)
  1096. {
  1097. int target = J->top - n;
  1098. if (target < J->bot)
  1099. target = J->bot;
  1100. mu_popto(J, target);
  1101. }
  1102. int js_gettop(js_State *J)
  1103. {
  1104. return J->top - J->bot;
  1105. }
  1106. /* ---- type tests and conversions ---- */
  1107. int js_isdefined(js_State *J, int idx) { return !JS_IsUndefined(mu_at(J, idx)); }
  1108. int js_isundefined(js_State *J, int idx) { return JS_IsUndefined(mu_at(J, idx)); }
  1109. int js_isnull(js_State *J, int idx) { return JS_IsNull(mu_at(J, idx)); }
  1110. int js_isboolean(js_State *J, int idx) { return JS_IsBool(mu_at(J, idx)); }
  1111. int js_isnumber(js_State *J, int idx) { return JS_IsNumber(mu_at(J, idx)); }
  1112. int js_isstring(js_State *J, int idx) { return JS_IsString(mu_at(J, idx)); }
  1113. int js_isobject(js_State *J, int idx) { return JS_IsObject(mu_at(J, idx)); }
  1114. int js_iscallable(js_State *J, int idx)
  1115. {
  1116. return JS_IsFunction(J->ctx, mu_at(J, idx));
  1117. }
  1118. int js_toboolean(js_State *J, int idx)
  1119. {
  1120. return JS_ToBool(J->ctx, mu_at(J, idx)) > 0;
  1121. }
  1122. double js_tonumber(js_State *J, int idx)
  1123. {
  1124. double d = 0;
  1125. if (JS_ToFloat64(J->ctx, &d, mu_at(J, idx)) < 0)
  1126. mu_throw_value(J, JS_GetException(J->ctx));
  1127. return d;
  1128. }
  1129. int js_tointeger(js_State *J, int idx)
  1130. {
  1131. double d = js_tonumber(J, idx);
  1132. if (d != d)
  1133. return 0;
  1134. if (d >= 2147483647.0)
  1135. return 2147483647;
  1136. if (d <= -2147483648.0)
  1137. return (int)-2147483647 - 1;
  1138. return (int)d;
  1139. }
  1140. static const char *mu_tostring(js_State *J, int idx, const char *error)
  1141. {
  1142. struct mu_slot *s = mu_slot_at(J, idx);
  1143. JSValue str;
  1144. if (!s)
  1145. return "undefined";
  1146. if (s->cs && JS_IsString(s->v))
  1147. return s->cs;
  1148. str = JS_ToString(J->ctx, s->v);
  1149. if (JS_IsException(str)) {
  1150. if (error) {
  1151. JS_FreeValue(J->ctx, JS_GetException(J->ctx));
  1152. return error;
  1153. }
  1154. mu_throw_value(J, JS_GetException(J->ctx));
  1155. }
  1156. /* Convert in place, as MuJS does. */
  1157. mu_slot_free(J, s);
  1158. s->v = str;
  1159. s->cs = JS_ToCString(J->ctx, str);
  1160. return s->cs ? s->cs : "";
  1161. }
  1162. const char *js_tostring(js_State *J, int idx)
  1163. {
  1164. return mu_tostring(J, idx, 0);
  1165. }
  1166. const char *js_trystring(js_State *J, int idx, const char *error)
  1167. {
  1168. return mu_tostring(J, idx, error);
  1169. }
  1170. int js_equal(js_State *J)
  1171. {
  1172. JSValue x = mu_at(J, -2), y = mu_at(J, -1);
  1173. const char *a, *b;
  1174. int eq;
  1175. if (JS_IsObject(x) || JS_IsObject(y))
  1176. return JS_IsObject(x) && JS_IsObject(y) &&
  1177. JS_VALUE_GET_PTR(x) == JS_VALUE_GET_PTR(y);
  1178. a = JS_ToCString(J->ctx, x);
  1179. b = JS_ToCString(J->ctx, y);
  1180. eq = a && b && !strcmp(a, b);
  1181. JS_FreeCString(J->ctx, a);
  1182. JS_FreeCString(J->ctx, b);
  1183. return eq;
  1184. }