js_mu.c 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. };
  81. struct mu_ud {
  82. const char *tag;
  83. void *data;
  84. js_HasProperty has;
  85. js_Put put;
  86. js_Delete del;
  87. JSValue backing; /* expando properties (jQuery data, ...) */
  88. };
  89. static JSClassID mu_ud_class;
  90. /* ---- value stack ---- */
  91. static void mu_push(js_State *J, JSValue v)
  92. {
  93. if (J->top >= J->cap) {
  94. int ncap = J->cap ? J->cap * 2 : MU_STACK_INIT;
  95. struct mu_slot *n = (struct mu_slot *)realloc(J->stk,
  96. (size_t)ncap * sizeof(*n));
  97. if (!n) {
  98. JS_FreeValue(J->ctx, v);
  99. if (J->panic)
  100. J->panic(J);
  101. abort();
  102. }
  103. J->stk = n;
  104. J->cap = ncap;
  105. }
  106. J->stk[J->top].v = v;
  107. J->stk[J->top].cs = 0;
  108. J->top++;
  109. }
  110. static void mu_slot_free(js_State *J, struct mu_slot *s)
  111. {
  112. if (s->cs)
  113. JS_FreeCString(J->ctx, s->cs);
  114. s->cs = 0;
  115. JS_FreeValue(J->ctx, s->v);
  116. s->v = JS_UNDEFINED;
  117. }
  118. static void mu_popto(js_State *J, int top)
  119. {
  120. while (J->top > top && J->top > 0)
  121. mu_slot_free(J, &J->stk[--J->top]);
  122. }
  123. /* Take ownership of the top value. */
  124. static JSValue mu_take(js_State *J)
  125. {
  126. struct mu_slot *s;
  127. JSValue v;
  128. if (J->top <= J->bot)
  129. return JS_UNDEFINED;
  130. s = &J->stk[--J->top];
  131. if (s->cs)
  132. JS_FreeCString(J->ctx, s->cs);
  133. v = s->v;
  134. s->cs = 0;
  135. s->v = JS_UNDEFINED;
  136. return v;
  137. }
  138. static int mu_abs(js_State *J, int idx)
  139. {
  140. return idx < 0 ? J->top + idx : J->bot + idx;
  141. }
  142. static struct mu_slot *mu_slot_at(js_State *J, int idx)
  143. {
  144. int i = mu_abs(J, idx);
  145. if (i < 0 || i >= J->top)
  146. return 0;
  147. return &J->stk[i];
  148. }
  149. static JSValue mu_at(js_State *J, int idx)
  150. {
  151. struct mu_slot *s = mu_slot_at(J, idx);
  152. return s ? s->v : JS_UNDEFINED;
  153. }
  154. /* ---- exceptions ---- */
  155. static __attribute__((noreturn)) void mu_throw_value(js_State *J, JSValue exc)
  156. {
  157. struct mu_try *t;
  158. if (J->ntry == 0) {
  159. mu_push(J, exc);
  160. if (J->panic)
  161. J->panic(J);
  162. abort();
  163. }
  164. t = &J->tries[--J->ntry];
  165. mu_popto(J, t->top);
  166. J->bot = t->bot;
  167. J->fdata = t->fdata;
  168. mu_push(J, exc);
  169. longjmp(t->buf, 1);
  170. }
  171. static void mu_check(js_State *J, JSValue v)
  172. {
  173. if (JS_IsException(v))
  174. mu_throw_value(J, JS_GetException(J->ctx));
  175. }
  176. jmp_buf *js_savetry(js_State *J)
  177. {
  178. struct mu_try *t;
  179. if (J->ntry >= MU_TRIES) {
  180. JS_ThrowInternalError(J->ctx, "try stack overflow");
  181. mu_throw_value(J, JS_GetException(J->ctx));
  182. }
  183. t = &J->tries[J->ntry++];
  184. t->top = J->top;
  185. t->bot = J->bot;
  186. t->fdata = J->fdata;
  187. return &t->buf;
  188. }
  189. void js_endtry(js_State *J)
  190. {
  191. if (J->ntry > 0)
  192. J->ntry--;
  193. }
  194. void js_throw(js_State *J)
  195. {
  196. mu_throw_value(J, mu_take(J));
  197. }
  198. void js_typeerror(js_State *J, const char *fmt, ...)
  199. {
  200. char buf[256];
  201. va_list ap;
  202. va_start(ap, fmt);
  203. vsnprintf(buf, sizeof(buf), fmt, ap);
  204. va_end(ap);
  205. JS_ThrowTypeError(J->ctx, "%s", buf);
  206. mu_throw_value(J, JS_GetException(J->ctx));
  207. }
  208. /* ---- C functions ---- */
  209. static JSValue mu_ptr_value(void *p)
  210. {
  211. return JS_NewFloat64(0, (double)(uintptr_t)p);
  212. }
  213. static void *mu_value_ptr(JSValueConst v)
  214. {
  215. double d;
  216. if (JS_VALUE_GET_TAG(v) == JS_TAG_INT)
  217. return (void *)(uintptr_t)(uint32_t)JS_VALUE_GET_INT(v);
  218. d = JS_VALUE_GET_FLOAT64(v);
  219. return (void *)(uintptr_t)d;
  220. }
  221. /* Every C callback is a catch boundary: a js_throw() inside it becomes a
  222. * QuickJS exception for the calling script. */
  223. static JSValue mu_trampoline(JSContext *ctx, JSValueConst this_val, int argc,
  224. JSValueConst *argv, int magic, JSValue *data)
  225. {
  226. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  227. js_CFunction fn = (js_CFunction)mu_value_ptr(data[0]);
  228. void *fdata = mu_value_ptr(data[1]);
  229. int savetop = J->top, savebot = J->bot, ntry = J->ntry, i;
  230. void *savefd = J->fdata;
  231. struct mu_try *t;
  232. JSValue ret;
  233. mu_push(J, JS_DupValue(ctx, this_val));
  234. for (i = 0; i < argc; i++)
  235. mu_push(J, JS_DupValue(ctx, argv[i]));
  236. for (; i < magic; i++)
  237. mu_push(J, JS_UNDEFINED);
  238. if (J->ntry >= MU_TRIES) {
  239. mu_popto(J, savetop);
  240. return JS_ThrowInternalError(ctx, "try stack overflow");
  241. }
  242. t = &J->tries[J->ntry++];
  243. t->top = savetop;
  244. t->bot = savebot;
  245. t->fdata = savefd;
  246. J->bot = savetop;
  247. J->fdata = fdata;
  248. if (setjmp(t->buf)) {
  249. JSValue exc = mu_take(J);
  250. mu_popto(J, savetop);
  251. J->bot = savebot;
  252. J->fdata = savefd;
  253. J->ntry = ntry;
  254. return JS_Throw(ctx, exc);
  255. }
  256. fn(J);
  257. J->ntry = ntry;
  258. ret = J->top > savetop ? JS_DupValue(ctx, J->stk[J->top - 1].v) :
  259. JS_UNDEFINED;
  260. mu_popto(J, savetop);
  261. J->bot = savebot;
  262. J->fdata = savefd;
  263. return ret;
  264. }
  265. void js_newcfunctionx(js_State *J, js_CFunction fun, const char *name,
  266. int length, void *data, js_Finalize finalize)
  267. {
  268. JSValue d[2];
  269. JSValue f;
  270. (void)name;
  271. (void)finalize;
  272. d[0] = mu_ptr_value((void *)fun);
  273. d[1] = mu_ptr_value(data);
  274. f = JS_NewCFunctionData(J->ctx, mu_trampoline, length, length, 2, d);
  275. /* MuJS lets `new` call any C function (Event, CustomEvent, ...
  276. * return their object); QuickJS needs the constructor bit for that. */
  277. JS_SetConstructorBit(J->ctx, f, 1);
  278. mu_push(J, f);
  279. }
  280. void js_newcfunction(js_State *J, js_CFunction fun, const char *name,
  281. int length)
  282. {
  283. js_newcfunctionx(J, fun, name, length, 0, 0);
  284. }
  285. void *js_currentfunctiondata(js_State *J)
  286. {
  287. return J->fdata;
  288. }
  289. /* ---- userdata ---- */
  290. /* Run a has/put/delete hook as a catch boundary. Returns the hook's
  291. * result, or -1 with a pending QuickJS exception. */
  292. static int mu_hook(js_State *J, js_HasProperty hook, void *p, JSAtom atom,
  293. int savetop)
  294. {
  295. const char *name = JS_AtomToCString(J->ctx, atom);
  296. int savebot = J->bot, ntry = J->ntry, r;
  297. void *savefd = J->fdata;
  298. struct mu_try *t;
  299. if (!name)
  300. return -1;
  301. if (J->ntry >= MU_TRIES) {
  302. JS_FreeCString(J->ctx, name);
  303. JS_ThrowInternalError(J->ctx, "try stack overflow");
  304. return -1;
  305. }
  306. t = &J->tries[J->ntry++];
  307. t->top = savetop;
  308. t->bot = savebot;
  309. t->fdata = savefd;
  310. if (setjmp(t->buf)) {
  311. JSValue exc = mu_take(J);
  312. JS_FreeCString(J->ctx, name);
  313. mu_popto(J, savetop);
  314. J->bot = savebot;
  315. J->fdata = savefd;
  316. J->ntry = ntry;
  317. JS_Throw(J->ctx, exc);
  318. return -1;
  319. }
  320. r = hook(J, p, name);
  321. J->ntry = ntry;
  322. J->bot = savebot;
  323. J->fdata = savefd;
  324. JS_FreeCString(J->ctx, name);
  325. return r;
  326. }
  327. /* has-hook lookup: 1 with *out set, 0 when the hook does not know the
  328. * name, -1 on exception. */
  329. static int mu_ud_lookup(JSContext *ctx, struct mu_ud *u, JSAtom atom,
  330. JSValue *out)
  331. {
  332. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  333. int savetop = J->top, r;
  334. if (!u->has)
  335. return 0;
  336. r = mu_hook(J, u->has, u->data, atom, savetop);
  337. if (r > 0) {
  338. *out = J->top > savetop ?
  339. JS_DupValue(ctx, J->stk[J->top - 1].v) : JS_UNDEFINED;
  340. mu_popto(J, savetop);
  341. return 1;
  342. }
  343. mu_popto(J, savetop);
  344. return r < 0 ? -1 : 0;
  345. }
  346. static struct mu_ud *mu_ud_of(JSValueConst obj)
  347. {
  348. return (struct mu_ud *)JS_GetOpaque(obj, mu_ud_class);
  349. }
  350. static JSValue mu_ud_get(JSContext *ctx, JSValueConst obj, JSAtom atom,
  351. JSValueConst receiver)
  352. {
  353. struct mu_ud *u = mu_ud_of(obj);
  354. JSValue v;
  355. int r;
  356. (void)receiver;
  357. if (!u)
  358. return JS_UNDEFINED;
  359. r = mu_ud_lookup(ctx, u, atom, &v);
  360. if (r < 0)
  361. return JS_EXCEPTION;
  362. if (r > 0)
  363. return v;
  364. return JS_GetProperty(ctx, u->backing, atom);
  365. }
  366. static int mu_ud_has(JSContext *ctx, JSValueConst obj, JSAtom atom)
  367. {
  368. struct mu_ud *u = mu_ud_of(obj);
  369. JSValue v;
  370. int r;
  371. if (!u)
  372. return 0;
  373. r = mu_ud_lookup(ctx, u, atom, &v);
  374. if (r < 0)
  375. return -1;
  376. if (r > 0) {
  377. JS_FreeValue(ctx, v);
  378. return 1;
  379. }
  380. return JS_HasProperty(ctx, u->backing, atom);
  381. }
  382. static int mu_ud_set(JSContext *ctx, JSValueConst obj, JSAtom atom,
  383. JSValueConst value, JSValueConst receiver, int flags)
  384. {
  385. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  386. struct mu_ud *u = mu_ud_of(obj);
  387. int savetop = J->top, r;
  388. (void)receiver;
  389. (void)flags;
  390. if (!u)
  391. return 0;
  392. if (u->put) {
  393. mu_push(J, JS_DupValue(ctx, value));
  394. r = mu_hook(J, u->put, u->data, atom, savetop);
  395. mu_popto(J, savetop);
  396. if (r < 0)
  397. return -1;
  398. if (r > 0)
  399. return 1;
  400. }
  401. return JS_SetProperty(ctx, u->backing, atom, JS_DupValue(ctx, value));
  402. }
  403. static int mu_ud_delete(JSContext *ctx, JSValueConst obj, JSAtom atom)
  404. {
  405. js_State *J = (js_State *)JS_GetContextOpaque(ctx);
  406. struct mu_ud *u = mu_ud_of(obj);
  407. int savetop = J->top, r;
  408. if (!u)
  409. return 1;
  410. if (u->del) {
  411. r = mu_hook(J, u->del, u->data, atom, savetop);
  412. mu_popto(J, savetop);
  413. if (r < 0)
  414. return -1;
  415. if (r > 0)
  416. return 1;
  417. }
  418. return JS_DeleteProperty(ctx, u->backing, atom, 0);
  419. }
  420. static int mu_ud_own(JSContext *ctx, JSPropertyDescriptor *desc,
  421. JSValueConst obj, JSAtom atom)
  422. {
  423. struct mu_ud *u = mu_ud_of(obj);
  424. JSValue v;
  425. int r;
  426. if (!u)
  427. return 0;
  428. r = mu_ud_lookup(ctx, u, atom, &v);
  429. if (r < 0)
  430. return -1;
  431. if (r > 0) {
  432. if (desc) {
  433. desc->flags = JS_PROP_ENUMERABLE | JS_PROP_WRITABLE |
  434. JS_PROP_CONFIGURABLE;
  435. desc->value = v;
  436. desc->getter = JS_UNDEFINED;
  437. desc->setter = JS_UNDEFINED;
  438. } else {
  439. JS_FreeValue(ctx, v);
  440. }
  441. return 1;
  442. }
  443. return JS_GetOwnProperty(ctx, desc, u->backing, atom);
  444. }
  445. static int mu_ud_names(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen,
  446. JSValueConst obj)
  447. {
  448. struct mu_ud *u = mu_ud_of(obj);
  449. if (!u) {
  450. *ptab = 0;
  451. *plen = 0;
  452. return 0;
  453. }
  454. return JS_GetOwnPropertyNames(ctx, ptab, plen, u->backing,
  455. JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK);
  456. }
  457. static int mu_ud_define(JSContext *ctx, JSValueConst this_obj, JSAtom prop,
  458. JSValueConst val, JSValueConst getter,
  459. JSValueConst setter, int flags)
  460. {
  461. struct mu_ud *u = mu_ud_of(this_obj);
  462. if (!u)
  463. return 0;
  464. return JS_DefineProperty(ctx, u->backing, prop, val, getter, setter,
  465. flags);
  466. }
  467. static void mu_ud_finalizer(JSRuntime *rt, JSValue val)
  468. {
  469. struct mu_ud *u = mu_ud_of(val);
  470. if (u) {
  471. JS_FreeValueRT(rt, u->backing);
  472. free(u);
  473. }
  474. }
  475. static void mu_ud_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark)
  476. {
  477. struct mu_ud *u = mu_ud_of(val);
  478. if (u)
  479. JS_MarkValue(rt, u->backing, mark);
  480. }
  481. static JSClassExoticMethods mu_ud_exotic = {
  482. .get_own_property = mu_ud_own,
  483. .get_own_property_names = mu_ud_names,
  484. .delete_property = mu_ud_delete,
  485. .define_own_property = mu_ud_define,
  486. .has_property = mu_ud_has,
  487. .get_property = mu_ud_get,
  488. .set_property = mu_ud_set,
  489. };
  490. static JSClassDef mu_ud_def = {
  491. .class_name = "HTMLElement",
  492. .finalizer = mu_ud_finalizer,
  493. .gc_mark = mu_ud_mark,
  494. .exotic = &mu_ud_exotic,
  495. };
  496. /* Pops the prototype from the top of the stack, like MuJS. */
  497. void js_newuserdatax(js_State *J, const char *tag, void *data,
  498. js_HasProperty has, js_Put put, js_Delete del,
  499. js_Finalize finalize)
  500. {
  501. JSValue proto = mu_take(J), obj;
  502. struct mu_ud *u;
  503. (void)finalize;
  504. if (!JS_IsObject(proto)) {
  505. JS_FreeValue(J->ctx, proto);
  506. proto = JS_NULL;
  507. }
  508. u = (struct mu_ud *)malloc(sizeof(*u));
  509. obj = JS_NewObjectProtoClass(J->ctx, proto, mu_ud_class);
  510. if (!u || JS_IsException(obj)) {
  511. free(u);
  512. JS_FreeValue(J->ctx, proto);
  513. mu_check(J, JS_IsException(obj) ? obj : JS_ThrowOutOfMemory(J->ctx));
  514. return;
  515. }
  516. u->tag = tag;
  517. u->data = data;
  518. u->has = has;
  519. u->put = put;
  520. u->del = del;
  521. u->backing = JS_NewObjectProto(J->ctx, proto);
  522. JS_FreeValue(J->ctx, proto);
  523. JS_SetOpaque(obj, u);
  524. mu_push(J, obj);
  525. }
  526. int js_isuserdata(js_State *J, int idx, const char *tag)
  527. {
  528. struct mu_ud *u = mu_ud_of(mu_at(J, idx));
  529. return u && !strcmp(u->tag, tag);
  530. }
  531. void *js_touserdata(js_State *J, int idx, const char *tag)
  532. {
  533. struct mu_ud *u = mu_ud_of(mu_at(J, idx));
  534. if (!u || strcmp(u->tag, tag))
  535. js_typeerror(J, "not a %s", tag);
  536. return u->data;
  537. }
  538. /* ---- state ---- */
  539. static int mu_interrupt(JSRuntime *rt, void *opaque)
  540. {
  541. js_State *J = (js_State *)opaque;
  542. (void)rt;
  543. return J->limited && (int)(u_ticks_ms() - J->deadline) >= 0;
  544. }
  545. js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
  546. {
  547. js_State *J;
  548. (void)alloc;
  549. (void)actx;
  550. (void)flags;
  551. J = (js_State *)calloc(1, sizeof(*J));
  552. if (!J)
  553. return 0;
  554. J->rt = JS_NewRuntime();
  555. if (!J->rt) {
  556. free(J);
  557. return 0;
  558. }
  559. #ifdef MU_OWN_STACK
  560. J->jsstack = malloc(JS_MU_STACK_BYTES);
  561. JS_SetMaxStackSize(J->rt, J->jsstack ?
  562. JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN :
  563. 48u * 1024u);
  564. #else
  565. JS_SetMaxStackSize(J->rt, JS_MU_STACK_BYTES - JS_MU_STACK_MARGIN);
  566. #endif
  567. if (!mu_ud_class)
  568. JS_NewClassID(&mu_ud_class);
  569. JS_NewClass(J->rt, mu_ud_class, &mu_ud_def);
  570. J->ctx = JS_NewContext(J->rt);
  571. if (!J->ctx) {
  572. JS_FreeRuntime(J->rt);
  573. free(J);
  574. return 0;
  575. }
  576. JS_SetContextOpaque(J->ctx, J);
  577. JS_SetInterruptHandler(J->rt, mu_interrupt, J);
  578. J->registry = JS_NewObject(J->ctx);
  579. return J;
  580. }
  581. void js_freestate(js_State *J)
  582. {
  583. if (!J)
  584. return;
  585. J->bot = 0;
  586. mu_popto(J, 0);
  587. JS_FreeValue(J->ctx, J->registry);
  588. JS_FreeContext(J->ctx);
  589. JS_FreeRuntime(J->rt);
  590. free(J->stk);
  591. free(J->jsstack);
  592. free(J);
  593. }
  594. void js_setreport(js_State *J, js_Report report)
  595. {
  596. J->report = report;
  597. }
  598. js_Panic js_atpanic(js_State *J, js_Panic panic)
  599. {
  600. js_Panic old = J->panic;
  601. J->panic = panic;
  602. return old;
  603. }
  604. void js_setlimit(js_State *J, int limit_ms, int memlimit)
  605. {
  606. (void)memlimit;
  607. J->limited = limit_ms > 0;
  608. J->deadline = u_ticks_ms() + (unsigned int)limit_ms;
  609. }
  610. /* ---- loading and calling ---- */
  611. /* Run an engine entry: on the private stack when this is the outermost
  612. * one, directly when JavaScript is already running (a nested callback). */
  613. struct mu_entry {
  614. js_State *J;
  615. void (*fn)(struct mu_entry *e);
  616. const char *filename, *source;
  617. JSValue fn_obj, thisv, *argv, result;
  618. int argc;
  619. };
  620. static void mu_entry_run(void *arg)
  621. {
  622. struct mu_entry *e = (struct mu_entry *)arg;
  623. JS_UpdateStackTop(e->J->rt);
  624. e->fn(e);
  625. }
  626. static void mu_enter(js_State *J, struct mu_entry *e)
  627. {
  628. e->J = J;
  629. if (J->depth++ == 0) {
  630. #ifdef MU_OWN_STACK
  631. if (J->jsstack) {
  632. mu_stack_call((char *)J->jsstack + JS_MU_STACK_BYTES,
  633. mu_entry_run, e);
  634. J->depth--;
  635. return;
  636. }
  637. #endif
  638. mu_entry_run(e);
  639. } else {
  640. e->fn(e);
  641. }
  642. J->depth--;
  643. }
  644. static void mu_do_compile(struct mu_entry *e)
  645. {
  646. e->result = JS_Eval(e->J->ctx, e->source, strlen(e->source),
  647. e->filename ? e->filename : "[string]",
  648. JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
  649. }
  650. static void mu_do_call(struct mu_entry *e)
  651. {
  652. JSContext *ctx = e->J->ctx;
  653. if (JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_FUNCTION_BYTECODE ||
  654. JS_VALUE_GET_TAG(e->fn_obj) == JS_TAG_MODULE) {
  655. e->result = JS_EvalFunction(ctx, e->fn_obj);
  656. e->fn_obj = JS_UNDEFINED;
  657. } else {
  658. e->result = JS_Call(ctx, e->fn_obj, e->thisv, e->argc,
  659. e->argv);
  660. }
  661. }
  662. static void mu_do_jobs(struct mu_entry *e)
  663. {
  664. js_State *J = e->J;
  665. JSContext *c;
  666. int i, r;
  667. for (i = 0; i < 10000; i++) {
  668. r = JS_ExecutePendingJob(J->rt, &c);
  669. if (r == 0)
  670. break;
  671. if (r < 0) {
  672. JSValue exc = JS_GetException(J->ctx);
  673. mu_push(J, exc);
  674. if (J->report)
  675. J->report(J, js_trystring(J, -1,
  676. "uncaught exception in promise job"));
  677. js_pop(J, 1);
  678. }
  679. }
  680. }
  681. void js_runjobs(js_State *J)
  682. {
  683. struct mu_entry e;
  684. /* Promise jobs are microtasks: while a script is still running (an
  685. * event dispatched from inside JavaScript), the outermost entry runs
  686. * them when it finishes. */
  687. if (J->depth > 0)
  688. return;
  689. memset(&e, 0, sizeof(e));
  690. e.fn = mu_do_jobs;
  691. mu_enter(J, &e);
  692. }
  693. static JSValue mu_compile(js_State *J, const char *filename,
  694. const char *source)
  695. {
  696. struct mu_entry e;
  697. memset(&e, 0, sizeof(e));
  698. e.fn = mu_do_compile;
  699. e.filename = filename;
  700. e.source = source;
  701. mu_enter(J, &e);
  702. return e.result;
  703. }
  704. int js_ploadstring(js_State *J, const char *filename, const char *source)
  705. {
  706. JSValue f = mu_compile(J, filename, source);
  707. if (JS_IsException(f)) {
  708. mu_push(J, JS_GetException(J->ctx));
  709. return 1;
  710. }
  711. mu_push(J, f);
  712. return 0;
  713. }
  714. void js_loadstring(js_State *J, const char *filename, const char *source)
  715. {
  716. JSValue f = mu_compile(J, filename, source);
  717. mu_check(J, f);
  718. mu_push(J, f);
  719. }
  720. /* Stack: function, this, n arguments. Replaced by the result (0) or the
  721. * error value (1). */
  722. int js_pcall(js_State *J, int n)
  723. {
  724. int base = J->top - n - 2, i;
  725. JSValue fn, thisv, r, argv_small[8], *argv = argv_small;
  726. if (base < J->bot) {
  727. JS_ThrowInternalError(J->ctx, "pcall: stack underflow");
  728. mu_push(J, JS_GetException(J->ctx));
  729. return 1;
  730. }
  731. if (n > 8) {
  732. argv = (JSValue *)malloc((size_t)n * sizeof(JSValue));
  733. if (!argv) {
  734. mu_popto(J, base);
  735. mu_push(J, JS_ThrowOutOfMemory(J->ctx));
  736. mu_push(J, JS_GetException(J->ctx));
  737. return 1;
  738. }
  739. }
  740. /* Copy out: a nested call may grow (move) the value stack. */
  741. fn = JS_DupValue(J->ctx, J->stk[base].v);
  742. thisv = JS_DupValue(J->ctx, J->stk[base + 1].v);
  743. for (i = 0; i < n; i++)
  744. argv[i] = JS_DupValue(J->ctx, J->stk[base + 2 + i].v);
  745. mu_popto(J, base);
  746. {
  747. struct mu_entry e;
  748. memset(&e, 0, sizeof(e));
  749. e.fn = mu_do_call;
  750. e.fn_obj = fn;
  751. e.thisv = thisv;
  752. e.argv = argv;
  753. e.argc = n;
  754. mu_enter(J, &e);
  755. fn = e.fn_obj;
  756. r = e.result;
  757. }
  758. JS_FreeValue(J->ctx, fn);
  759. JS_FreeValue(J->ctx, thisv);
  760. for (i = 0; i < n; i++)
  761. JS_FreeValue(J->ctx, argv[i]);
  762. if (argv != argv_small)
  763. free(argv);
  764. if (JS_IsException(r)) {
  765. mu_push(J, JS_GetException(J->ctx));
  766. return 1;
  767. }
  768. mu_push(J, r);
  769. return 0;
  770. }
  771. /* ---- globals, registry and properties ---- */
  772. void js_getglobal(js_State *J, const char *name)
  773. {
  774. JSValue g = JS_GetGlobalObject(J->ctx);
  775. JSValue v = JS_GetPropertyStr(J->ctx, g, name);
  776. JS_FreeValue(J->ctx, g);
  777. mu_check(J, v);
  778. mu_push(J, v);
  779. }
  780. void js_pushglobal(js_State *J)
  781. {
  782. mu_push(J, JS_GetGlobalObject(J->ctx));
  783. }
  784. static int mu_flags(int atts)
  785. {
  786. int f = 0;
  787. if (!(atts & JS_READONLY))
  788. f |= JS_PROP_WRITABLE;
  789. if (!(atts & JS_DONTENUM))
  790. f |= JS_PROP_ENUMERABLE;
  791. if (!(atts & JS_DONTCONF))
  792. f |= JS_PROP_CONFIGURABLE;
  793. return f;
  794. }
  795. void js_defglobal(js_State *J, const char *name, int atts)
  796. {
  797. JSValue v = mu_take(J);
  798. JSValue g = JS_GetGlobalObject(J->ctx);
  799. JS_DefinePropertyValueStr(J->ctx, g, name, v, mu_flags(atts));
  800. JS_FreeValue(J->ctx, g);
  801. }
  802. void js_getregistry(js_State *J, const char *name)
  803. {
  804. mu_push(J, JS_GetPropertyStr(J->ctx, J->registry, name));
  805. }
  806. void js_setregistry(js_State *J, const char *name)
  807. {
  808. JS_SetPropertyStr(J->ctx, J->registry, name, mu_take(J));
  809. }
  810. void js_delregistry(js_State *J, const char *name)
  811. {
  812. JSAtom a = JS_NewAtom(J->ctx, name);
  813. JS_DeleteProperty(J->ctx, J->registry, a, 0);
  814. JS_FreeAtom(J->ctx, a);
  815. }
  816. /* The returned key lives in a small ring; callers copy it at once. */
  817. const char *js_ref(js_State *J)
  818. {
  819. static char keys[8][24];
  820. static int next;
  821. char *k = keys[next++ & 7];
  822. snprintf(k, 24, "_ref%d", ++J->nextref);
  823. js_setregistry(J, k);
  824. return k;
  825. }
  826. void js_unref(js_State *J, const char *ref)
  827. {
  828. js_delregistry(J, ref);
  829. }
  830. void js_getproperty(js_State *J, int idx, const char *name)
  831. {
  832. JSValue v = JS_GetPropertyStr(J->ctx, mu_at(J, idx), name);
  833. mu_check(J, v);
  834. mu_push(J, v);
  835. }
  836. void js_setproperty(js_State *J, int idx, const char *name)
  837. {
  838. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  839. JSValue v = mu_take(J);
  840. int r = JS_SetPropertyStr(J->ctx, obj, name, v);
  841. JS_FreeValue(J->ctx, obj);
  842. if (r < 0)
  843. mu_throw_value(J, JS_GetException(J->ctx));
  844. }
  845. void js_setindex(js_State *J, int idx, int i)
  846. {
  847. JSValue obj = JS_DupValue(J->ctx, mu_at(J, idx));
  848. JSValue v = mu_take(J);
  849. int r = JS_SetPropertyUint32(J->ctx, obj, (uint32_t)i, v);
  850. JS_FreeValue(J->ctx, obj);
  851. if (r < 0)
  852. mu_throw_value(J, JS_GetException(J->ctx));
  853. }
  854. /* Stack: ..., getter, setter (either may be undefined). */
  855. void js_defaccessor(js_State *J, int idx, const char *name, int atts)
  856. {
  857. JSValue obj = mu_at(J, idx);
  858. JSValue get = JS_DupValue(J->ctx, mu_at(J, -2));
  859. JSValue set = JS_DupValue(J->ctx, mu_at(J, -1));
  860. JSAtom a = JS_NewAtom(J->ctx, name);
  861. if (!JS_IsFunction(J->ctx, get)) {
  862. JS_FreeValue(J->ctx, get);
  863. get = JS_UNDEFINED;
  864. }
  865. if (!JS_IsFunction(J->ctx, set)) {
  866. JS_FreeValue(J->ctx, set);
  867. set = JS_UNDEFINED;
  868. }
  869. JS_DefinePropertyGetSet(J->ctx, obj, a, get, set,
  870. mu_flags(atts) & ~JS_PROP_WRITABLE);
  871. JS_FreeAtom(J->ctx, a);
  872. js_pop(J, 2);
  873. }
  874. void js_newobject(js_State *J)
  875. {
  876. mu_push(J, JS_NewObject(J->ctx));
  877. }
  878. void js_newarray(js_State *J)
  879. {
  880. mu_push(J, JS_NewArray(J->ctx));
  881. }
  882. /* ---- pushing and popping ---- */
  883. void js_pushundefined(js_State *J) { mu_push(J, JS_UNDEFINED); }
  884. void js_pushnull(js_State *J) { mu_push(J, JS_NULL); }
  885. void js_pushboolean(js_State *J, int v) { mu_push(J, JS_NewBool(J->ctx, v)); }
  886. void js_pushnumber(js_State *J, double v)
  887. {
  888. mu_push(J, JS_NewFloat64(J->ctx, v));
  889. }
  890. void js_pushstring(js_State *J, const char *v)
  891. {
  892. mu_push(J, JS_NewString(J->ctx, v ? v : ""));
  893. }
  894. void js_pushlstring(js_State *J, const char *v, int n)
  895. {
  896. mu_push(J, JS_NewStringLen(J->ctx, v ? v : "", v && n > 0 ? (size_t)n : 0));
  897. }
  898. void js_copy(js_State *J, int idx)
  899. {
  900. mu_push(J, JS_DupValue(J->ctx, mu_at(J, idx)));
  901. }
  902. void js_pop(js_State *J, int n)
  903. {
  904. int target = J->top - n;
  905. if (target < J->bot)
  906. target = J->bot;
  907. mu_popto(J, target);
  908. }
  909. int js_gettop(js_State *J)
  910. {
  911. return J->top - J->bot;
  912. }
  913. /* ---- type tests and conversions ---- */
  914. int js_isdefined(js_State *J, int idx) { return !JS_IsUndefined(mu_at(J, idx)); }
  915. int js_isundefined(js_State *J, int idx) { return JS_IsUndefined(mu_at(J, idx)); }
  916. int js_isnull(js_State *J, int idx) { return JS_IsNull(mu_at(J, idx)); }
  917. int js_isboolean(js_State *J, int idx) { return JS_IsBool(mu_at(J, idx)); }
  918. int js_isnumber(js_State *J, int idx) { return JS_IsNumber(mu_at(J, idx)); }
  919. int js_isstring(js_State *J, int idx) { return JS_IsString(mu_at(J, idx)); }
  920. int js_isobject(js_State *J, int idx) { return JS_IsObject(mu_at(J, idx)); }
  921. int js_iscallable(js_State *J, int idx)
  922. {
  923. return JS_IsFunction(J->ctx, mu_at(J, idx));
  924. }
  925. int js_toboolean(js_State *J, int idx)
  926. {
  927. return JS_ToBool(J->ctx, mu_at(J, idx)) > 0;
  928. }
  929. double js_tonumber(js_State *J, int idx)
  930. {
  931. double d = 0;
  932. if (JS_ToFloat64(J->ctx, &d, mu_at(J, idx)) < 0)
  933. mu_throw_value(J, JS_GetException(J->ctx));
  934. return d;
  935. }
  936. int js_tointeger(js_State *J, int idx)
  937. {
  938. double d = js_tonumber(J, idx);
  939. if (d != d)
  940. return 0;
  941. if (d >= 2147483647.0)
  942. return 2147483647;
  943. if (d <= -2147483648.0)
  944. return (int)-2147483647 - 1;
  945. return (int)d;
  946. }
  947. static const char *mu_tostring(js_State *J, int idx, const char *error)
  948. {
  949. struct mu_slot *s = mu_slot_at(J, idx);
  950. JSValue str;
  951. if (!s)
  952. return "undefined";
  953. if (s->cs && JS_IsString(s->v))
  954. return s->cs;
  955. str = JS_ToString(J->ctx, s->v);
  956. if (JS_IsException(str)) {
  957. if (error) {
  958. JS_FreeValue(J->ctx, JS_GetException(J->ctx));
  959. return error;
  960. }
  961. mu_throw_value(J, JS_GetException(J->ctx));
  962. }
  963. /* Convert in place, as MuJS does. */
  964. mu_slot_free(J, s);
  965. s->v = str;
  966. s->cs = JS_ToCString(J->ctx, str);
  967. return s->cs ? s->cs : "";
  968. }
  969. const char *js_tostring(js_State *J, int idx)
  970. {
  971. return mu_tostring(J, idx, 0);
  972. }
  973. const char *js_trystring(js_State *J, int idx, const char *error)
  974. {
  975. return mu_tostring(J, idx, error);
  976. }
  977. int js_equal(js_State *J)
  978. {
  979. JSValue x = mu_at(J, -2), y = mu_at(J, -1);
  980. const char *a, *b;
  981. int eq;
  982. if (JS_IsObject(x) || JS_IsObject(y))
  983. return JS_IsObject(x) && JS_IsObject(y) &&
  984. JS_VALUE_GET_PTR(x) == JS_VALUE_GET_PTR(y);
  985. a = JS_ToCString(J->ctx, x);
  986. b = JS_ToCString(J->ctx, y);
  987. eq = a && b && !strcmp(a, b);
  988. JS_FreeCString(J->ctx, a);
  989. JS_FreeCString(J->ctx, b);
  990. return eq;
  991. }