lj_bcwrite.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. ** Bytecode writer.
  3. ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
  4. */
  5. #define lj_bcwrite_c
  6. #define LUA_CORE
  7. #include "lj_obj.h"
  8. #include "lj_gc.h"
  9. #include "lj_buf.h"
  10. #include "lj_bc.h"
  11. #if LJ_HASFFI
  12. #include "lj_ctype.h"
  13. #endif
  14. #if LJ_HASJIT
  15. #include "lj_dispatch.h"
  16. #include "lj_jit.h"
  17. #endif
  18. #include "lj_strfmt.h"
  19. #include "lj_bcdump.h"
  20. #include "lj_vm.h"
  21. /* Context for bytecode writer. */
  22. typedef struct BCWriteCtx {
  23. SBuf sb; /* Output buffer. */
  24. GCproto *pt; /* Root prototype. */
  25. lua_Writer wfunc; /* Writer callback. */
  26. void *wdata; /* Writer callback data. */
  27. TValue **heap; /* Heap used for deterministic sorting. */
  28. uint32_t heapsz; /* Size of heap. */
  29. uint32_t flags; /* BCDUMP_F_* flags. */
  30. int status; /* Status from writer callback. */
  31. #ifdef LUA_USE_ASSERT
  32. global_State *g;
  33. #endif
  34. } BCWriteCtx;
  35. #ifdef LUA_USE_ASSERT
  36. #define lj_assertBCW(c, ...) lj_assertG_(ctx->g, (c), __VA_ARGS__)
  37. #else
  38. #define lj_assertBCW(c, ...) ((void)ctx)
  39. #endif
  40. /* -- Bytecode writer ----------------------------------------------------- */
  41. /* Write a single constant key/value of a template table. */
  42. static void bcwrite_ktabk(BCWriteCtx *ctx, cTValue *o, int narrow)
  43. {
  44. char *p = lj_buf_more(&ctx->sb, 1+10);
  45. if (tvisstr(o)) {
  46. const GCstr *str = strV(o);
  47. MSize len = str->len;
  48. p = lj_buf_more(&ctx->sb, 5+len);
  49. p = lj_strfmt_wuleb128(p, BCDUMP_KTAB_STR+len);
  50. p = lj_buf_wmem(p, strdata(str), len);
  51. } else if (tvisint(o)) {
  52. *p++ = BCDUMP_KTAB_INT;
  53. p = lj_strfmt_wuleb128(p, intV(o));
  54. } else if (tvisnum(o)) {
  55. if (!LJ_DUALNUM && narrow) { /* Narrow number constants to integers. */
  56. lua_Number num = numV(o);
  57. int32_t k = lj_num2int(num);
  58. if (num == (lua_Number)k) { /* -0 is never a constant. */
  59. *p++ = BCDUMP_KTAB_INT;
  60. p = lj_strfmt_wuleb128(p, k);
  61. ctx->sb.w = p;
  62. return;
  63. }
  64. }
  65. *p++ = BCDUMP_KTAB_NUM;
  66. p = lj_strfmt_wuleb128(p, o->u32.lo);
  67. p = lj_strfmt_wuleb128(p, o->u32.hi);
  68. } else {
  69. lj_assertBCW(tvispri(o), "unhandled type %d", itype(o));
  70. *p++ = BCDUMP_KTAB_NIL+~itype(o);
  71. }
  72. ctx->sb.w = p;
  73. }
  74. /* Compare two template table keys. */
  75. static LJ_AINLINE int bcwrite_ktabk_lt(TValue *a, TValue *b)
  76. {
  77. uint32_t at = itype(a), bt = itype(b);
  78. if (at != bt) { /* This also handles false and true keys. */
  79. return at < bt;
  80. } else if (at == LJ_TSTR) {
  81. return lj_str_cmp(strV(a), strV(b)) < 0;
  82. } else {
  83. return a->u64 < b->u64; /* This works for numbers and integers. */
  84. }
  85. }
  86. /* Insert key into a sorted heap. */
  87. static void bcwrite_ktabk_heap_insert(TValue **heap, MSize idx, MSize end,
  88. TValue *key)
  89. {
  90. MSize child;
  91. while ((child = idx * 2 + 1) < end) {
  92. /* Find lower of the two children. */
  93. TValue *c0 = heap[child];
  94. if (child + 1 < end) {
  95. TValue *c1 = heap[child + 1];
  96. if (bcwrite_ktabk_lt(c1, c0)) {
  97. c0 = c1;
  98. child++;
  99. }
  100. }
  101. if (bcwrite_ktabk_lt(key, c0)) break; /* Key lower? Found our position. */
  102. heap[idx] = c0; /* Move lower child up. */
  103. idx = child; /* Descend. */
  104. }
  105. heap[idx] = key; /* Insert key here. */
  106. }
  107. /* Resize heap, dropping content. */
  108. static void bcwrite_heap_resize(BCWriteCtx *ctx, uint32_t nsz)
  109. {
  110. lua_State *L = sbufL(&ctx->sb);
  111. if (ctx->heapsz) {
  112. lj_mem_freevec(G(L), ctx->heap, ctx->heapsz, TValue *);
  113. ctx->heapsz = 0;
  114. }
  115. if (nsz) {
  116. ctx->heap = lj_mem_newvec(L, nsz, TValue *);
  117. ctx->heapsz = nsz;
  118. }
  119. }
  120. /* Write hash part of template table in sorted order. */
  121. static void bcwrite_ktab_sorted_hash(BCWriteCtx *ctx, Node *node, MSize nhash)
  122. {
  123. TValue **heap = ctx->heap;
  124. MSize i = nhash;
  125. for (;; node--) { /* Build heap. */
  126. if (!tvisnil(&node->val)) {
  127. bcwrite_ktabk_heap_insert(heap, --i, nhash, &node->key);
  128. if (i == 0) break;
  129. }
  130. }
  131. do { /* Drain heap. */
  132. TValue *key = heap[0]; /* Output lowest key from top. */
  133. bcwrite_ktabk(ctx, key, 0);
  134. bcwrite_ktabk(ctx, (TValue *)((char *)key - offsetof(Node, key)), 1);
  135. key = heap[--nhash]; /* Remove last key. */
  136. bcwrite_ktabk_heap_insert(heap, 0, nhash, key); /* Re-insert. */
  137. } while (nhash);
  138. }
  139. /* Write a template table. */
  140. static void bcwrite_ktab(BCWriteCtx *ctx, char *p, const GCtab *t)
  141. {
  142. MSize narray = 0, nhash = 0;
  143. if (t->asize > 0) { /* Determine max. length of array part. */
  144. ptrdiff_t i;
  145. TValue *array = tvref(t->array);
  146. for (i = (ptrdiff_t)t->asize-1; i >= 0; i--)
  147. if (!tvisnil(&array[i]))
  148. break;
  149. narray = (MSize)(i+1);
  150. }
  151. if (t->hmask > 0) { /* Count number of used hash slots. */
  152. MSize i, hmask = t->hmask;
  153. Node *node = noderef(t->node);
  154. for (i = 0; i <= hmask; i++)
  155. nhash += !tvisnil(&node[i].val);
  156. }
  157. /* Write number of array slots and hash slots. */
  158. p = lj_strfmt_wuleb128(p, narray);
  159. p = lj_strfmt_wuleb128(p, nhash);
  160. ctx->sb.w = p;
  161. if (narray) { /* Write array entries (may contain nil). */
  162. MSize i;
  163. TValue *o = tvref(t->array);
  164. for (i = 0; i < narray; i++, o++)
  165. bcwrite_ktabk(ctx, o, 1);
  166. }
  167. if (nhash) { /* Write hash entries. */
  168. Node *node = noderef(t->node) + t->hmask;
  169. if ((ctx->flags & BCDUMP_F_DETERMINISTIC) && nhash > 1) {
  170. if (ctx->heapsz < nhash)
  171. bcwrite_heap_resize(ctx, t->hmask + 1);
  172. bcwrite_ktab_sorted_hash(ctx, node, nhash);
  173. } else {
  174. MSize i = nhash;
  175. for (;; node--)
  176. if (!tvisnil(&node->val)) {
  177. bcwrite_ktabk(ctx, &node->key, 0);
  178. bcwrite_ktabk(ctx, &node->val, 1);
  179. if (--i == 0) break;
  180. }
  181. }
  182. }
  183. }
  184. /* Write GC constants of a prototype. */
  185. static void bcwrite_kgc(BCWriteCtx *ctx, GCproto *pt)
  186. {
  187. MSize i, sizekgc = pt->sizekgc;
  188. GCRef *kr = mref(pt->k, GCRef) - (ptrdiff_t)sizekgc;
  189. for (i = 0; i < sizekgc; i++, kr++) {
  190. GCobj *o = gcref(*kr);
  191. MSize tp, need = 1;
  192. char *p;
  193. /* Determine constant type and needed size. */
  194. if (o->gch.gct == ~LJ_TSTR) {
  195. tp = BCDUMP_KGC_STR + gco2str(o)->len;
  196. need = 5+gco2str(o)->len;
  197. } else if (o->gch.gct == ~LJ_TPROTO) {
  198. lj_assertBCW((pt->flags & PROTO_CHILD), "prototype has unexpected child");
  199. tp = BCDUMP_KGC_CHILD;
  200. #if LJ_HASFFI
  201. } else if (o->gch.gct == ~LJ_TCDATA) {
  202. CTypeID id = gco2cd(o)->ctypeid;
  203. need = 1+4*5;
  204. if (id == CTID_INT64) {
  205. tp = BCDUMP_KGC_I64;
  206. } else if (id == CTID_UINT64) {
  207. tp = BCDUMP_KGC_U64;
  208. } else {
  209. lj_assertBCW(id == CTID_COMPLEX_DOUBLE,
  210. "bad cdata constant CTID %d", id);
  211. tp = BCDUMP_KGC_COMPLEX;
  212. }
  213. #endif
  214. } else {
  215. lj_assertBCW(o->gch.gct == ~LJ_TTAB,
  216. "bad constant GC type %d", o->gch.gct);
  217. tp = BCDUMP_KGC_TAB;
  218. need = 1+2*5;
  219. }
  220. /* Write constant type. */
  221. p = lj_buf_more(&ctx->sb, need);
  222. p = lj_strfmt_wuleb128(p, tp);
  223. /* Write constant data (if any). */
  224. if (tp >= BCDUMP_KGC_STR) {
  225. p = lj_buf_wmem(p, strdata(gco2str(o)), gco2str(o)->len);
  226. } else if (tp == BCDUMP_KGC_TAB) {
  227. bcwrite_ktab(ctx, p, gco2tab(o));
  228. continue;
  229. #if LJ_HASFFI
  230. } else if (tp != BCDUMP_KGC_CHILD) {
  231. cTValue *q = (TValue *)cdataptr(gco2cd(o));
  232. p = lj_strfmt_wuleb128(p, q[0].u32.lo);
  233. p = lj_strfmt_wuleb128(p, q[0].u32.hi);
  234. if (tp == BCDUMP_KGC_COMPLEX) {
  235. p = lj_strfmt_wuleb128(p, q[1].u32.lo);
  236. p = lj_strfmt_wuleb128(p, q[1].u32.hi);
  237. }
  238. #endif
  239. }
  240. ctx->sb.w = p;
  241. }
  242. }
  243. /* Write number constants of a prototype. */
  244. static void bcwrite_knum(BCWriteCtx *ctx, GCproto *pt)
  245. {
  246. MSize i, sizekn = pt->sizekn;
  247. cTValue *o = mref(pt->k, TValue);
  248. char *p = lj_buf_more(&ctx->sb, 10*sizekn);
  249. for (i = 0; i < sizekn; i++, o++) {
  250. int32_t k;
  251. if (tvisint(o)) {
  252. k = intV(o);
  253. goto save_int;
  254. } else {
  255. /* Write a 33 bit ULEB128 for the int (lsb=0) or loword (lsb=1). */
  256. if (!LJ_DUALNUM && o->u32.hi != LJ_KEYINDEX) {
  257. /* Narrow number constants to integers. */
  258. lua_Number num = numV(o);
  259. k = lj_num2int(num);
  260. if (num == (lua_Number)k) { /* -0 is never a constant. */
  261. save_int:
  262. p = lj_strfmt_wuleb128(p, 2*(uint32_t)k | ((uint32_t)k&0x80000000u));
  263. if (k < 0)
  264. p[-1] = (p[-1] & 7) | ((k>>27) & 0x18);
  265. continue;
  266. }
  267. }
  268. p = lj_strfmt_wuleb128(p, 1+(2*o->u32.lo | (o->u32.lo & 0x80000000u)));
  269. if (o->u32.lo >= 0x80000000u)
  270. p[-1] = (p[-1] & 7) | ((o->u32.lo>>27) & 0x18);
  271. p = lj_strfmt_wuleb128(p, o->u32.hi);
  272. }
  273. }
  274. ctx->sb.w = p;
  275. }
  276. /* Write bytecode instructions. */
  277. static char *bcwrite_bytecode(BCWriteCtx *ctx, char *p, GCproto *pt)
  278. {
  279. MSize nbc = pt->sizebc-1; /* Omit the [JI]FUNC* header. */
  280. #if LJ_HASJIT
  281. uint8_t *q = (uint8_t *)p;
  282. #endif
  283. p = lj_buf_wmem(p, proto_bc(pt)+1, nbc*(MSize)sizeof(BCIns));
  284. UNUSED(ctx);
  285. #if LJ_HASJIT
  286. /* Unpatch modified bytecode containing ILOOP/JLOOP etc. */
  287. if ((pt->flags & PROTO_ILOOP) || pt->trace) {
  288. jit_State *J = L2J(sbufL(&ctx->sb));
  289. MSize i;
  290. for (i = 0; i < nbc; i++, q += sizeof(BCIns)) {
  291. BCOp op = (BCOp)q[LJ_ENDIAN_SELECT(0, 3)];
  292. if (op == BC_IFORL || op == BC_IITERL || op == BC_ILOOP ||
  293. op == BC_JFORI) {
  294. q[LJ_ENDIAN_SELECT(0, 3)] = (uint8_t)(op-BC_IFORL+BC_FORL);
  295. } else if (op == BC_JFORL || op == BC_JITERL || op == BC_JLOOP) {
  296. BCReg rd = q[LJ_ENDIAN_SELECT(2, 1)] + (q[LJ_ENDIAN_SELECT(3, 0)] << 8);
  297. memcpy(q, &traceref(J, rd)->startins, 4);
  298. }
  299. }
  300. }
  301. #endif
  302. return p;
  303. }
  304. /* Write prototype. */
  305. static void bcwrite_proto(BCWriteCtx *ctx, GCproto *pt)
  306. {
  307. MSize sizedbg = 0;
  308. char *p;
  309. /* Recursively write children of prototype. */
  310. if ((pt->flags & PROTO_CHILD)) {
  311. ptrdiff_t i, n = pt->sizekgc;
  312. GCRef *kr = mref(pt->k, GCRef) - 1;
  313. for (i = 0; i < n; i++, kr--) {
  314. GCobj *o = gcref(*kr);
  315. if (o->gch.gct == ~LJ_TPROTO)
  316. bcwrite_proto(ctx, gco2pt(o));
  317. }
  318. }
  319. /* Start writing the prototype info to a buffer. */
  320. p = lj_buf_need(&ctx->sb,
  321. 5+4+6*5+(pt->sizebc-1)*(MSize)sizeof(BCIns)+pt->sizeuv*2);
  322. p += 5; /* Leave room for final size. */
  323. /* Write prototype header. */
  324. *p++ = (pt->flags & (PROTO_CHILD|PROTO_VARARG|PROTO_FFI));
  325. *p++ = pt->numparams;
  326. *p++ = pt->framesize;
  327. *p++ = pt->sizeuv;
  328. p = lj_strfmt_wuleb128(p, pt->sizekgc);
  329. p = lj_strfmt_wuleb128(p, pt->sizekn);
  330. p = lj_strfmt_wuleb128(p, pt->sizebc-1);
  331. if (!(ctx->flags & BCDUMP_F_STRIP)) {
  332. if (proto_lineinfo(pt))
  333. sizedbg = pt->sizept - (MSize)((char *)proto_lineinfo(pt) - (char *)pt);
  334. p = lj_strfmt_wuleb128(p, sizedbg);
  335. if (sizedbg) {
  336. p = lj_strfmt_wuleb128(p, pt->firstline);
  337. p = lj_strfmt_wuleb128(p, pt->numline);
  338. }
  339. }
  340. /* Write bytecode instructions and upvalue refs. */
  341. p = bcwrite_bytecode(ctx, p, pt);
  342. p = lj_buf_wmem(p, proto_uv(pt), pt->sizeuv*2);
  343. ctx->sb.w = p;
  344. /* Write constants. */
  345. bcwrite_kgc(ctx, pt);
  346. bcwrite_knum(ctx, pt);
  347. /* Write debug info, if not stripped. */
  348. if (sizedbg) {
  349. p = lj_buf_more(&ctx->sb, sizedbg);
  350. p = lj_buf_wmem(p, proto_lineinfo(pt), sizedbg);
  351. ctx->sb.w = p;
  352. }
  353. /* Pass buffer to writer function. */
  354. if (ctx->status == 0) {
  355. MSize n = sbuflen(&ctx->sb) - 5;
  356. MSize nn = (lj_fls(n)+8)*9 >> 6;
  357. char *q = ctx->sb.b + (5 - nn);
  358. p = lj_strfmt_wuleb128(q, n); /* Fill in final size. */
  359. lj_assertBCW(p == ctx->sb.b + 5, "bad ULEB128 write");
  360. ctx->status = ctx->wfunc(sbufL(&ctx->sb), q, nn+n, ctx->wdata);
  361. }
  362. }
  363. /* Write header of bytecode dump. */
  364. static void bcwrite_header(BCWriteCtx *ctx)
  365. {
  366. GCstr *chunkname = proto_chunkname(ctx->pt);
  367. const char *name = strdata(chunkname);
  368. MSize len = chunkname->len;
  369. char *p = lj_buf_need(&ctx->sb, 5+5+len);
  370. *p++ = BCDUMP_HEAD1;
  371. *p++ = BCDUMP_HEAD2;
  372. *p++ = BCDUMP_HEAD3;
  373. *p++ = BCDUMP_VERSION;
  374. *p++ = (ctx->flags & (BCDUMP_F_STRIP | BCDUMP_F_FR2)) +
  375. LJ_BE*BCDUMP_F_BE +
  376. ((ctx->pt->flags & PROTO_FFI) ? BCDUMP_F_FFI : 0);
  377. if (!(ctx->flags & BCDUMP_F_STRIP)) {
  378. p = lj_strfmt_wuleb128(p, len);
  379. p = lj_buf_wmem(p, name, len);
  380. }
  381. ctx->status = ctx->wfunc(sbufL(&ctx->sb), ctx->sb.b,
  382. (MSize)(p - ctx->sb.b), ctx->wdata);
  383. }
  384. /* Write footer of bytecode dump. */
  385. static void bcwrite_footer(BCWriteCtx *ctx)
  386. {
  387. if (ctx->status == 0) {
  388. uint8_t zero = 0;
  389. ctx->status = ctx->wfunc(sbufL(&ctx->sb), &zero, 1, ctx->wdata);
  390. }
  391. }
  392. /* Protected callback for bytecode writer. */
  393. static TValue *cpwriter(lua_State *L, lua_CFunction dummy, void *ud)
  394. {
  395. BCWriteCtx *ctx = (BCWriteCtx *)ud;
  396. UNUSED(L); UNUSED(dummy);
  397. lj_buf_need(&ctx->sb, 1024); /* Avoids resize for most prototypes. */
  398. bcwrite_header(ctx);
  399. bcwrite_proto(ctx, ctx->pt);
  400. bcwrite_footer(ctx);
  401. return NULL;
  402. }
  403. /* Write bytecode for a prototype. */
  404. int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer, void *data,
  405. uint32_t flags)
  406. {
  407. BCWriteCtx ctx;
  408. int status;
  409. ctx.pt = pt;
  410. ctx.wfunc = writer;
  411. ctx.wdata = data;
  412. ctx.heapsz = 0;
  413. if ((bc_op(proto_bc(pt)[0]) != BC_NOT) == LJ_FR2) flags |= BCDUMP_F_FR2;
  414. ctx.flags = flags;
  415. ctx.status = 0;
  416. #ifdef LUA_USE_ASSERT
  417. ctx.g = G(L);
  418. #endif
  419. lj_buf_init(L, &ctx.sb);
  420. status = lj_vm_cpcall(L, NULL, &ctx, cpwriter);
  421. if (status == 0) status = ctx.status;
  422. lj_buf_free(G(sbufL(&ctx.sb)), &ctx.sb);
  423. bcwrite_heap_resize(&ctx, 0);
  424. return status;
  425. }