lj_obj.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /*
  2. ** LuaJIT VM tags, values and objects.
  3. ** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
  4. **
  5. ** Portions taken verbatim or adapted from the Lua interpreter.
  6. ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
  7. */
  8. #ifndef _LJ_OBJ_H
  9. #define _LJ_OBJ_H
  10. #include "lua.h"
  11. #include "lj_def.h"
  12. #include "lj_arch.h"
  13. /* -- Memory references (32 bit address space) ---------------------------- */
  14. /* Memory size. */
  15. typedef uint32_t MSize;
  16. /* Memory reference */
  17. typedef struct MRef {
  18. uint32_t ptr32; /* Pseudo 32 bit pointer. */
  19. } MRef;
  20. #define mref(r, t) ((t *)(void *)(uintptr_t)(r).ptr32)
  21. #define setmref(r, p) ((r).ptr32 = (uint32_t)(uintptr_t)(void *)(p))
  22. #define setmrefr(r, v) ((r).ptr32 = (v).ptr32)
  23. /* -- GC object references (32 bit address space) ------------------------- */
  24. /* GCobj reference */
  25. typedef struct GCRef {
  26. uint32_t gcptr32; /* Pseudo 32 bit pointer. */
  27. } GCRef;
  28. /* Common GC header for all collectable objects. */
  29. #define GCHeader GCRef nextgc; uint8_t marked; uint8_t gct
  30. /* This occupies 6 bytes, so use the next 2 bytes for non-32 bit fields. */
  31. #define gcref(r) ((GCobj *)(uintptr_t)(r).gcptr32)
  32. #define gcrefp(r, t) ((t *)(void *)(uintptr_t)(r).gcptr32)
  33. #define gcrefu(r) ((r).gcptr32)
  34. #define gcrefi(r) ((int32_t)(r).gcptr32)
  35. #define gcrefeq(r1, r2) ((r1).gcptr32 == (r2).gcptr32)
  36. #define gcnext(gc) (gcref((gc)->gch.nextgc))
  37. #define setgcref(r, gc) ((r).gcptr32 = (uint32_t)(uintptr_t)&(gc)->gch)
  38. #define setgcrefi(r, i) ((r).gcptr32 = (uint32_t)(i))
  39. #define setgcrefp(r, p) ((r).gcptr32 = (uint32_t)(uintptr_t)(p))
  40. #define setgcrefnull(r) ((r).gcptr32 = 0)
  41. #define setgcrefr(r, v) ((r).gcptr32 = (v).gcptr32)
  42. /* IMPORTANT NOTE:
  43. **
  44. ** All uses of the setgcref* macros MUST be accompanied with a write barrier.
  45. **
  46. ** This is to ensure the integrity of the incremental GC. The invariant
  47. ** to preserve is that a black object never points to a white object.
  48. ** I.e. never store a white object into a field of a black object.
  49. **
  50. ** It's ok to LEAVE OUT the write barrier ONLY in the following cases:
  51. ** - The source is not a GC object (NULL).
  52. ** - The target is a GC root. I.e. everything in global_State.
  53. ** - The target is a lua_State field (threads are never black).
  54. ** - The target is a stack slot, see setgcV et al.
  55. ** - The target is an open upvalue, i.e. pointing to a stack slot.
  56. ** - The target is a newly created object (i.e. marked white). But make
  57. ** sure nothing invokes the GC inbetween.
  58. ** - The target and the source are the same object (self-reference).
  59. ** - The target already contains the object (e.g. moving elements around).
  60. **
  61. ** The most common case is a store to a stack slot. All other cases where
  62. ** a barrier has been omitted are annotated with a NOBARRIER comment.
  63. **
  64. ** The same logic applies for stores to table slots (array part or hash
  65. ** part). ALL uses of lj_tab_set* require a barrier for the stored value
  66. ** *and* the stored key, based on the above rules. In practice this means
  67. ** a barrier is needed if *either* of the key or value are a GC object.
  68. **
  69. ** It's ok to LEAVE OUT the write barrier in the following special cases:
  70. ** - The stored value is nil. The key doesn't matter because it's either
  71. ** not resurrected or lj_tab_newkey() will take care of the key barrier.
  72. ** - The key doesn't matter if the *previously* stored value is guaranteed
  73. ** to be non-nil (because the key is kept alive in the table).
  74. ** - The key doesn't matter if it's guaranteed not to be part of the table,
  75. ** since lj_tab_newkey() takes care of the key barrier. This applies
  76. ** trivially to new tables, but watch out for resurrected keys. Storing
  77. ** a nil value leaves the key in the table!
  78. **
  79. ** In case of doubt use lj_gc_anybarriert() as it's rather cheap. It's used
  80. ** by the interpreter for all table stores.
  81. **
  82. ** Note: In contrast to Lua's GC, LuaJIT's GC does *not* specially mark
  83. ** dead keys in tables. The reference is left in, but it's guaranteed to
  84. ** be never dereferenced as long as the value is nil. It's ok if the key is
  85. ** freed or if any object subsequently gets the same address.
  86. **
  87. ** Not destroying dead keys helps to keep key hash slots stable. This avoids
  88. ** specialization back-off for HREFK when a value flips between nil and
  89. ** non-nil and the GC gets in the way. It also allows safely hoisting
  90. ** HREF/HREFK across GC steps. Dead keys are only removed if a table is
  91. ** resized (i.e. by NEWREF) and xREF must not be CSEd across a resize.
  92. **
  93. ** The trade-off is that a write barrier for tables must take the key into
  94. ** account, too. Implicitly resurrecting the key by storing a non-nil value
  95. ** may invalidate the incremental GC invariant.
  96. */
  97. /* -- Common type definitions --------------------------------------------- */
  98. /* Types for handling bytecodes. Need this here, details in lj_bc.h. */
  99. typedef uint32_t BCIns; /* Bytecode instruction. */
  100. typedef uint32_t BCPos; /* Bytecode position. */
  101. typedef uint32_t BCReg; /* Bytecode register. */
  102. typedef int32_t BCLine; /* Bytecode line number. */
  103. /* Internal assembler functions. Never call these directly from C. */
  104. typedef void (*ASMFunction)(void);
  105. /* Resizable string buffer. Need this here, details in lj_str.h. */
  106. typedef struct SBuf {
  107. char *buf; /* String buffer base. */
  108. MSize n; /* String buffer length. */
  109. MSize sz; /* String buffer size. */
  110. } SBuf;
  111. /* -- Tags and values ----------------------------------------------------- */
  112. /* Frame link. */
  113. typedef union {
  114. int32_t ftsz; /* Frame type and size of previous frame. */
  115. MRef pcr; /* Overlaps PC for Lua frames. */
  116. } FrameLink;
  117. /* Tagged value. */
  118. typedef LJ_ALIGN(8) union TValue {
  119. uint64_t u64; /* 64 bit pattern overlaps number. */
  120. lua_Number n; /* Number object overlaps split tag/value object. */
  121. struct {
  122. LJ_ENDIAN_LOHI(
  123. union {
  124. GCRef gcr; /* GCobj reference (if any). */
  125. int32_t i; /* Integer value. */
  126. };
  127. , uint32_t it; /* Internal object tag. Must overlap MSW of number. */
  128. )
  129. };
  130. struct {
  131. LJ_ENDIAN_LOHI(
  132. GCRef func; /* Function for next frame (or dummy L). */
  133. , FrameLink tp; /* Link to previous frame. */
  134. )
  135. } fr;
  136. struct {
  137. LJ_ENDIAN_LOHI(
  138. uint32_t lo; /* Lower 32 bits of number. */
  139. , uint32_t hi; /* Upper 32 bits of number. */
  140. )
  141. } u32;
  142. } TValue;
  143. typedef const TValue cTValue;
  144. #define tvref(r) (mref(r, TValue))
  145. /* More external and GCobj tags for internal objects. */
  146. #define LAST_TT LUA_TTHREAD
  147. #define LUA_TPROTO (LAST_TT+1)
  148. #define LUA_TCDATA (LAST_TT+2)
  149. /* Internal object tags.
  150. **
  151. ** Internal tags overlap the MSW of a number object (must be a double).
  152. ** Interpreted as a double these are special NaNs. The FPU only generates
  153. ** one type of NaN (0xfff8_0000_0000_0000). So MSWs > 0xfff80000 are available
  154. ** for use as internal tags. Small negative numbers are used to shorten the
  155. ** encoding of type comparisons (reg/mem against sign-ext. 8 bit immediate).
  156. **
  157. ** ---MSW---.---LSW---
  158. ** primitive types | itype | |
  159. ** lightuserdata | itype | void * | (32 bit platforms)
  160. ** lightuserdata |ffff| void * | (64 bit platforms, 47 bit pointers)
  161. ** GC objects | itype | GCRef |
  162. ** int (LJ_DUALNUM)| itype | int |
  163. ** number -------double------
  164. **
  165. ** ORDER LJ_T
  166. ** Primitive types nil/false/true must be first, lightuserdata next.
  167. ** GC objects are at the end, table/userdata must be lowest.
  168. ** Also check lj_ir.h for similar ordering constraints.
  169. */
  170. #define LJ_TNIL (~0u)
  171. #define LJ_TFALSE (~1u)
  172. #define LJ_TTRUE (~2u)
  173. #define LJ_TLIGHTUD (~3u)
  174. #define LJ_TSTR (~4u)
  175. #define LJ_TUPVAL (~5u)
  176. #define LJ_TTHREAD (~6u)
  177. #define LJ_TPROTO (~7u)
  178. #define LJ_TFUNC (~8u)
  179. #define LJ_TTRACE (~9u)
  180. #define LJ_TCDATA (~10u)
  181. #define LJ_TTAB (~11u)
  182. #define LJ_TUDATA (~12u)
  183. /* This is just the canonical number type used in some places. */
  184. #define LJ_TNUMX (~13u)
  185. /* Integers have itype == LJ_TISNUM doubles have itype < LJ_TISNUM */
  186. #if LJ_64
  187. #define LJ_TISNUM 0xfffeffffu
  188. #else
  189. #define LJ_TISNUM LJ_TNUMX
  190. #endif
  191. #define LJ_TISTRUECOND LJ_TFALSE
  192. #define LJ_TISPRI LJ_TTRUE
  193. #define LJ_TISGCV (LJ_TSTR+1)
  194. #define LJ_TISTABUD LJ_TTAB
  195. /* -- String object ------------------------------------------------------- */
  196. /* String object header. String payload follows. */
  197. typedef struct GCstr {
  198. GCHeader;
  199. uint8_t reserved; /* Used by lexer for fast lookup of reserved words. */
  200. uint8_t unused;
  201. MSize hash; /* Hash of string. */
  202. MSize len; /* Size of string. */
  203. } GCstr;
  204. #define strref(r) (&gcref((r))->str)
  205. #define strdata(s) ((const char *)((s)+1))
  206. #define strdatawr(s) ((char *)((s)+1))
  207. #define strVdata(o) strdata(strV(o))
  208. #define sizestring(s) (sizeof(struct GCstr)+(s)->len+1)
  209. /* -- Userdata object ----------------------------------------------------- */
  210. /* Userdata object. Payload follows. */
  211. typedef struct GCudata {
  212. GCHeader;
  213. uint8_t udtype; /* Userdata type. */
  214. uint8_t unused2;
  215. GCRef env; /* Should be at same offset in GCfunc. */
  216. MSize len; /* Size of payload. */
  217. GCRef metatable; /* Must be at same offset in GCtab. */
  218. uint32_t align1; /* To force 8 byte alignment of the payload. */
  219. } GCudata;
  220. /* Userdata types. */
  221. enum {
  222. UDTYPE_USERDATA, /* Regular userdata. */
  223. UDTYPE_IO_FILE, /* I/O library FILE. */
  224. UDTYPE_FFI_CLIB, /* FFI C library namespace. */
  225. UDTYPE__MAX
  226. };
  227. #define uddata(u) ((void *)((u)+1))
  228. #define sizeudata(u) (sizeof(struct GCudata)+(u)->len)
  229. /* -- C data object ------------------------------------------------------- */
  230. /* C data object. Payload follows. */
  231. typedef struct GCcdata {
  232. GCHeader;
  233. uint16_t ctypeid; /* C type ID. */
  234. } GCcdata;
  235. /* Prepended to variable-sized or realigned C data objects. */
  236. typedef struct GCcdataVar {
  237. uint16_t offset; /* Offset to allocated memory (relative to GCcdata). */
  238. uint16_t extra; /* Extra space allocated (incl. GCcdata + GCcdatav). */
  239. MSize len; /* Size of payload. */
  240. } GCcdataVar;
  241. #define cdataptr(cd) ((void *)((cd)+1))
  242. #define cdataisv(cd) ((cd)->marked & 0x80)
  243. #define cdatav(cd) ((GCcdataVar *)((char *)(cd) - sizeof(GCcdataVar)))
  244. #define cdatavlen(cd) check_exp(cdataisv(cd), cdatav(cd)->len)
  245. #define sizecdatav(cd) (cdatavlen(cd) + cdatav(cd)->extra)
  246. #define memcdatav(cd) ((void *)((char *)(cd) - cdatav(cd)->offset))
  247. /* -- Prototype object ---------------------------------------------------- */
  248. #define SCALE_NUM_GCO ((int32_t)sizeof(lua_Number)/sizeof(GCRef))
  249. #define round_nkgc(n) (((n) + SCALE_NUM_GCO-1) & ~(SCALE_NUM_GCO-1))
  250. typedef struct GCproto {
  251. GCHeader;
  252. uint8_t numparams; /* Number of parameters. */
  253. uint8_t framesize; /* Fixed frame size. */
  254. MSize sizebc; /* Number of bytecode instructions. */
  255. GCRef gclist;
  256. MRef k; /* Split constant array (points to the middle). */
  257. MRef uv; /* Upvalue list. local slot|0x8000 or parent uv idx. */
  258. MSize sizekgc; /* Number of collectable constants. */
  259. MSize sizekn; /* Number of lua_Number constants. */
  260. MSize sizept; /* Total size including colocated arrays. */
  261. uint8_t sizeuv; /* Number of upvalues. */
  262. uint8_t flags; /* Miscellaneous flags (see below). */
  263. uint16_t trace; /* Anchor for chain of root traces. */
  264. /* ------ The following fields are for debugging/tracebacks only ------ */
  265. GCRef chunkname; /* Name of the chunk this function was defined in. */
  266. BCLine firstline; /* First line of the function definition. */
  267. BCLine numline; /* Number of lines for the function definition. */
  268. MRef lineinfo; /* Compressed map from bytecode ins. to source line. */
  269. MRef uvinfo; /* Upvalue names. */
  270. MRef varinfo; /* Names and compressed extents of local variables. */
  271. } GCproto;
  272. /* Flags for prototype. */
  273. #define PROTO_CHILD 0x01 /* Has child prototypes. */
  274. #define PROTO_VARARG 0x02 /* Vararg function. */
  275. #define PROTO_FFI 0x04 /* Uses BC_KCDATA for FFI datatypes. */
  276. #define PROTO_NOJIT 0x08 /* JIT disabled for this function. */
  277. #define PROTO_ILOOP 0x10 /* Patched bytecode with ILOOP etc. */
  278. /* Only used during parsing. */
  279. #define PROTO_HAS_RETURN 0x20 /* Already emitted a return. */
  280. #define PROTO_FIXUP_RETURN 0x40 /* Need to fixup emitted returns. */
  281. /* Top bits used for counting created closures. */
  282. #define PROTO_CLCOUNT 0x20 /* Base of saturating 3 bit counter. */
  283. #define PROTO_CLC_BITS 3
  284. #define PROTO_CLC_POLY (3*PROTO_CLCOUNT) /* Polymorphic threshold. */
  285. #define PROTO_UV_LOCAL 0x8000 /* Upvalue for local slot. */
  286. #define PROTO_UV_IMMUTABLE 0x4000 /* Immutable upvalue. */
  287. #define proto_kgc(pt, idx) \
  288. check_exp((uintptr_t)(intptr_t)(idx) >= (uintptr_t)-(intptr_t)(pt)->sizekgc, \
  289. gcref(mref((pt)->k, GCRef)[(idx)]))
  290. #define proto_knumtv(pt, idx) \
  291. check_exp((uintptr_t)(idx) < (pt)->sizekn, &mref((pt)->k, TValue)[(idx)])
  292. #define proto_bc(pt) ((BCIns *)((char *)(pt) + sizeof(GCproto)))
  293. #define proto_bcpos(pt, pc) ((BCPos)((pc) - proto_bc(pt)))
  294. #define proto_uv(pt) (mref((pt)->uv, uint16_t))
  295. #define proto_chunkname(pt) (strref((pt)->chunkname))
  296. #define proto_chunknamestr(pt) (strdata(proto_chunkname((pt))))
  297. #define proto_lineinfo(pt) (mref((pt)->lineinfo, const void))
  298. #define proto_uvinfo(pt) (mref((pt)->uvinfo, const uint8_t))
  299. #define proto_varinfo(pt) (mref((pt)->varinfo, const uint8_t))
  300. /* -- Upvalue object ------------------------------------------------------ */
  301. typedef struct GCupval {
  302. GCHeader;
  303. uint8_t closed; /* Set if closed (i.e. uv->v == &uv->u.value). */
  304. uint8_t immutable; /* Immutable value. */
  305. union {
  306. TValue tv; /* If closed: the value itself. */
  307. struct { /* If open: double linked list, anchored at thread. */
  308. GCRef prev;
  309. GCRef next;
  310. };
  311. };
  312. MRef v; /* Points to stack slot (open) or above (closed). */
  313. uint32_t dhash; /* Disambiguation hash: dh1 != dh2 => cannot alias. */
  314. } GCupval;
  315. #define uvprev(uv_) (&gcref((uv_)->prev)->uv)
  316. #define uvnext(uv_) (&gcref((uv_)->next)->uv)
  317. #define uvval(uv_) (mref((uv_)->v, TValue))
  318. /* -- Function object (closures) ------------------------------------------ */
  319. /* Common header for functions. env should be at same offset in GCudata. */
  320. #define GCfuncHeader \
  321. GCHeader; uint8_t ffid; uint8_t nupvalues; \
  322. GCRef env; GCRef gclist; MRef pc
  323. typedef struct GCfuncC {
  324. GCfuncHeader;
  325. lua_CFunction f; /* C function to be called. */
  326. TValue upvalue[1]; /* Array of upvalues (TValue). */
  327. } GCfuncC;
  328. typedef struct GCfuncL {
  329. GCfuncHeader;
  330. GCRef uvptr[1]; /* Array of _pointers_ to upvalue objects (GCupval). */
  331. } GCfuncL;
  332. typedef union GCfunc {
  333. GCfuncC c;
  334. GCfuncL l;
  335. } GCfunc;
  336. #define FF_LUA 0
  337. #define FF_C 1
  338. #define isluafunc(fn) ((fn)->c.ffid == FF_LUA)
  339. #define iscfunc(fn) ((fn)->c.ffid == FF_C)
  340. #define isffunc(fn) ((fn)->c.ffid > FF_C)
  341. #define funcproto(fn) \
  342. check_exp(isluafunc(fn), (GCproto *)(mref((fn)->l.pc, char)-sizeof(GCproto)))
  343. #define sizeCfunc(n) (sizeof(GCfuncC)-sizeof(TValue)+sizeof(TValue)*(n))
  344. #define sizeLfunc(n) (sizeof(GCfuncL)-sizeof(GCRef)+sizeof(GCRef)*(n))
  345. /* -- Table object -------------------------------------------------------- */
  346. /* Hash node. */
  347. typedef struct Node {
  348. TValue val; /* Value object. Must be first field. */
  349. TValue key; /* Key object. */
  350. MRef next; /* Hash chain. */
  351. MRef freetop; /* Top of free elements (stored in t->node[0]). */
  352. } Node;
  353. LJ_STATIC_ASSERT(offsetof(Node, val) == 0);
  354. typedef struct GCtab {
  355. GCHeader;
  356. uint8_t nomm; /* Negative cache for fast metamethods. */
  357. int8_t colo; /* Array colocation. */
  358. MRef array; /* Array part. */
  359. GCRef gclist;
  360. GCRef metatable; /* Must be at same offset in GCudata. */
  361. MRef node; /* Hash part. */
  362. uint32_t asize; /* Size of array part (keys [0, asize-1]). */
  363. uint32_t hmask; /* Hash part mask (size of hash part - 1). */
  364. } GCtab;
  365. #define sizetabcolo(n) ((n)*sizeof(TValue) + sizeof(GCtab))
  366. #define tabref(r) (&gcref((r))->tab)
  367. #define noderef(r) (mref((r), Node))
  368. #define nextnode(n) (mref((n)->next, Node))
  369. /* -- State objects ------------------------------------------------------- */
  370. /* VM states. */
  371. enum {
  372. LJ_VMST_INTERP, /* Interpreter. */
  373. LJ_VMST_C, /* C function. */
  374. LJ_VMST_GC, /* Garbage collector. */
  375. LJ_VMST_EXIT, /* Trace exit handler. */
  376. LJ_VMST_RECORD, /* Trace recorder. */
  377. LJ_VMST_OPT, /* Optimizer. */
  378. LJ_VMST_ASM, /* Assembler. */
  379. LJ_VMST__MAX
  380. };
  381. #define setvmstate(g, st) ((g)->vmstate = ~LJ_VMST_##st)
  382. /* Metamethods. ORDER MM */
  383. #ifdef LJ_HASFFI
  384. #define MMDEF_FFI(_) _(new)
  385. #else
  386. #define MMDEF_FFI(_)
  387. #endif
  388. #if LJ_52 || LJ_HASFFI
  389. #define MMDEF_PAIRS(_) _(pairs) _(ipairs)
  390. #else
  391. #define MMDEF_PAIRS(_)
  392. #define MM_pairs 255
  393. #define MM_ipairs 255
  394. #endif
  395. #define MMDEF(_) \
  396. _(index) _(newindex) _(gc) _(mode) _(eq) _(len) \
  397. /* Only the above (fast) metamethods are negative cached (max. 8). */ \
  398. _(lt) _(le) _(concat) _(call) \
  399. /* The following must be in ORDER ARITH. */ \
  400. _(add) _(sub) _(mul) _(div) _(mod) _(pow) _(unm) \
  401. /* The following are used in the standard libraries. */ \
  402. _(metatable) _(tostring) MMDEF_FFI(_) MMDEF_PAIRS(_)
  403. typedef enum {
  404. #define MMENUM(name) MM_##name,
  405. MMDEF(MMENUM)
  406. #undef MMENUM
  407. MM__MAX,
  408. MM____ = MM__MAX,
  409. MM_FAST = MM_len
  410. } MMS;
  411. /* GC root IDs. */
  412. typedef enum {
  413. GCROOT_MMNAME, /* Metamethod names. */
  414. GCROOT_MMNAME_LAST = GCROOT_MMNAME + MM__MAX-1,
  415. GCROOT_BASEMT, /* Metatables for base types. */
  416. GCROOT_BASEMT_NUM = GCROOT_BASEMT + ~LJ_TNUMX,
  417. GCROOT_IO_INPUT, /* Userdata for default I/O input file. */
  418. GCROOT_IO_OUTPUT, /* Userdata for default I/O output file. */
  419. GCROOT_MAX
  420. } GCRootID;
  421. #define basemt_it(g, it) ((g)->gcroot[GCROOT_BASEMT+~(it)])
  422. #define basemt_obj(g, o) ((g)->gcroot[GCROOT_BASEMT+itypemap(o)])
  423. #define mmname_str(g, mm) (strref((g)->gcroot[GCROOT_MMNAME+(mm)]))
  424. typedef struct GCState {
  425. MSize total; /* Memory currently allocated. */
  426. MSize threshold; /* Memory threshold. */
  427. uint8_t currentwhite; /* Current white color. */
  428. uint8_t state; /* GC state. */
  429. uint8_t nocdatafin; /* No cdata finalizer called. */
  430. uint8_t unused2;
  431. MSize sweepstr; /* Sweep position in string table. */
  432. GCRef root; /* List of all collectable objects. */
  433. MRef sweep; /* Sweep position in root list. */
  434. GCRef gray; /* List of gray objects. */
  435. GCRef grayagain; /* List of objects for atomic traversal. */
  436. GCRef weak; /* List of weak tables (to be cleared). */
  437. GCRef mmudata; /* List of userdata (to be finalized). */
  438. MSize stepmul; /* Incremental GC step granularity. */
  439. MSize debt; /* Debt (how much GC is behind schedule). */
  440. MSize estimate; /* Estimate of memory actually in use. */
  441. MSize pause; /* Pause between successive GC cycles. */
  442. } GCState;
  443. /* Global state, shared by all threads of a Lua universe. */
  444. typedef struct global_State {
  445. GCRef *strhash; /* String hash table (hash chain anchors). */
  446. MSize strmask; /* String hash mask (size of hash table - 1). */
  447. MSize strnum; /* Number of strings in hash table. */
  448. lua_Alloc allocf; /* Memory allocator. */
  449. void *allocd; /* Memory allocator data. */
  450. GCState gc; /* Garbage collector. */
  451. SBuf tmpbuf; /* Temporary buffer for string concatenation. */
  452. Node nilnode; /* Fallback 1-element hash part (nil key and value). */
  453. GCstr strempty; /* Empty string. */
  454. uint8_t stremptyz; /* Zero terminator of empty string. */
  455. uint8_t hookmask; /* Hook mask. */
  456. uint8_t dispatchmode; /* Dispatch mode. */
  457. uint8_t vmevmask; /* VM event mask. */
  458. GCRef mainthref; /* Link to main thread. */
  459. TValue registrytv; /* Anchor for registry. */
  460. TValue tmptv, tmptv2; /* Temporary TValues. */
  461. GCupval uvhead; /* Head of double-linked list of all open upvalues. */
  462. int32_t hookcount; /* Instruction hook countdown. */
  463. int32_t hookcstart; /* Start count for instruction hook counter. */
  464. lua_Hook hookf; /* Hook function. */
  465. lua_CFunction wrapf; /* Wrapper for C function calls. */
  466. lua_CFunction panic; /* Called as a last resort for errors. */
  467. volatile int32_t vmstate; /* VM state or current JIT code trace number. */
  468. BCIns bc_cfunc_int; /* Bytecode for internal C function calls. */
  469. BCIns bc_cfunc_ext; /* Bytecode for external C function calls. */
  470. GCRef jit_L; /* Current JIT code lua_State or NULL. */
  471. MRef jit_base; /* Current JIT code L->base. */
  472. MRef ctype_state; /* Pointer to C type state. */
  473. GCRef gcroot[GCROOT_MAX]; /* GC roots. */
  474. } global_State;
  475. #define mainthread(g) (&gcref(g->mainthref)->th)
  476. #define niltv(L) \
  477. check_exp(tvisnil(&G(L)->nilnode.val), &G(L)->nilnode.val)
  478. #define niltvg(g) \
  479. check_exp(tvisnil(&(g)->nilnode.val), &(g)->nilnode.val)
  480. /* Hook management. Hook event masks are defined in lua.h. */
  481. #define HOOK_EVENTMASK 0x0f
  482. #define HOOK_ACTIVE 0x10
  483. #define HOOK_ACTIVE_SHIFT 4
  484. #define HOOK_VMEVENT 0x20
  485. #define HOOK_GC 0x40
  486. #define hook_active(g) ((g)->hookmask & HOOK_ACTIVE)
  487. #define hook_enter(g) ((g)->hookmask |= HOOK_ACTIVE)
  488. #define hook_entergc(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_GC))
  489. #define hook_vmevent(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_VMEVENT))
  490. #define hook_leave(g) ((g)->hookmask &= ~HOOK_ACTIVE)
  491. #define hook_save(g) ((g)->hookmask & ~HOOK_EVENTMASK)
  492. #define hook_restore(g, h) \
  493. ((g)->hookmask = ((g)->hookmask & HOOK_EVENTMASK) | (h))
  494. /* Per-thread state object. */
  495. struct lua_State {
  496. GCHeader;
  497. uint8_t dummy_ffid; /* Fake FF_C for curr_funcisL() on dummy frames. */
  498. uint8_t status; /* Thread status. */
  499. MRef glref; /* Link to global state. */
  500. GCRef gclist; /* GC chain. */
  501. TValue *base; /* Base of currently executing function. */
  502. TValue *top; /* First free slot in the stack. */
  503. MRef maxstack; /* Last free slot in the stack. */
  504. MRef stack; /* Stack base. */
  505. GCRef openupval; /* List of open upvalues in the stack. */
  506. GCRef env; /* Thread environment (table of globals). */
  507. void *cframe; /* End of C stack frame chain. */
  508. MSize stacksize; /* True stack size (incl. LJ_STACK_EXTRA). */
  509. };
  510. #define G(L) (mref(L->glref, global_State))
  511. #define registry(L) (&G(L)->registrytv)
  512. /* Macros to access the currently executing (Lua) function. */
  513. #define curr_func(L) (&gcref((L->base-1)->fr.func)->fn)
  514. #define curr_funcisL(L) (isluafunc(curr_func(L)))
  515. #define curr_proto(L) (funcproto(curr_func(L)))
  516. #define curr_topL(L) (L->base + curr_proto(L)->framesize)
  517. #define curr_top(L) (curr_funcisL(L) ? curr_topL(L) : L->top)
  518. /* -- GC object definition and conversions -------------------------------- */
  519. /* GC header for generic access to common fields of GC objects. */
  520. typedef struct GChead {
  521. GCHeader;
  522. uint8_t unused1;
  523. uint8_t unused2;
  524. GCRef env;
  525. GCRef gclist;
  526. GCRef metatable;
  527. } GChead;
  528. /* The env field SHOULD be at the same offset for all GC objects. */
  529. LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCfuncL, env));
  530. LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCudata, env));
  531. /* The metatable field MUST be at the same offset for all GC objects. */
  532. LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCtab, metatable));
  533. LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCudata, metatable));
  534. /* The gclist field MUST be at the same offset for all GC objects. */
  535. LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(lua_State, gclist));
  536. LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCproto, gclist));
  537. LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCfuncL, gclist));
  538. LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCtab, gclist));
  539. typedef union GCobj {
  540. GChead gch;
  541. GCstr str;
  542. GCupval uv;
  543. lua_State th;
  544. GCproto pt;
  545. GCfunc fn;
  546. GCcdata cd;
  547. GCtab tab;
  548. GCudata ud;
  549. } GCobj;
  550. /* Macros to convert a GCobj pointer into a specific value. */
  551. #define gco2str(o) check_exp((o)->gch.gct == ~LJ_TSTR, &(o)->str)
  552. #define gco2uv(o) check_exp((o)->gch.gct == ~LJ_TUPVAL, &(o)->uv)
  553. #define gco2th(o) check_exp((o)->gch.gct == ~LJ_TTHREAD, &(o)->th)
  554. #define gco2pt(o) check_exp((o)->gch.gct == ~LJ_TPROTO, &(o)->pt)
  555. #define gco2func(o) check_exp((o)->gch.gct == ~LJ_TFUNC, &(o)->fn)
  556. #define gco2cd(o) check_exp((o)->gch.gct == ~LJ_TCDATA, &(o)->cd)
  557. #define gco2tab(o) check_exp((o)->gch.gct == ~LJ_TTAB, &(o)->tab)
  558. #define gco2ud(o) check_exp((o)->gch.gct == ~LJ_TUDATA, &(o)->ud)
  559. /* Macro to convert any collectable object into a GCobj pointer. */
  560. #define obj2gco(v) ((GCobj *)(v))
  561. /* -- TValue getters/setters ---------------------------------------------- */
  562. #ifdef LUA_USE_ASSERT
  563. #include "lj_gc.h"
  564. #endif
  565. /* Macros to test types. */
  566. #define itype(o) ((o)->it)
  567. #define tvisnil(o) (itype(o) == LJ_TNIL)
  568. #define tvisfalse(o) (itype(o) == LJ_TFALSE)
  569. #define tvistrue(o) (itype(o) == LJ_TTRUE)
  570. #define tvisbool(o) (tvisfalse(o) || tvistrue(o))
  571. #if LJ_64
  572. #define tvislightud(o) (((int32_t)itype(o) >> 15) == -2)
  573. #else
  574. #define tvislightud(o) (itype(o) == LJ_TLIGHTUD)
  575. #endif
  576. #define tvisstr(o) (itype(o) == LJ_TSTR)
  577. #define tvisfunc(o) (itype(o) == LJ_TFUNC)
  578. #define tvisthread(o) (itype(o) == LJ_TTHREAD)
  579. #define tvisproto(o) (itype(o) == LJ_TPROTO)
  580. #define tviscdata(o) (itype(o) == LJ_TCDATA)
  581. #define tvistab(o) (itype(o) == LJ_TTAB)
  582. #define tvisudata(o) (itype(o) == LJ_TUDATA)
  583. #define tvisnumber(o) (itype(o) <= LJ_TISNUM)
  584. #define tvisint(o) (LJ_DUALNUM && itype(o) == LJ_TISNUM)
  585. #define tvisnum(o) (itype(o) < LJ_TISNUM)
  586. #define tvistruecond(o) (itype(o) < LJ_TISTRUECOND)
  587. #define tvispri(o) (itype(o) >= LJ_TISPRI)
  588. #define tvistabud(o) (itype(o) <= LJ_TISTABUD) /* && !tvisnum() */
  589. #define tvisgcv(o) ((itype(o) - LJ_TISGCV) > (LJ_TNUMX - LJ_TISGCV))
  590. /* Special macros to test numbers for NaN, +0, -0, +1 and raw equality. */
  591. #define tvisnan(o) ((o)->n != (o)->n)
  592. #if LJ_64
  593. #define tviszero(o) (((o)->u64 << 1) == 0)
  594. #else
  595. #define tviszero(o) (((o)->u32.lo | ((o)->u32.hi << 1)) == 0)
  596. #endif
  597. #define tvispzero(o) ((o)->u64 == 0)
  598. #define tvismzero(o) ((o)->u64 == U64x(80000000,00000000))
  599. #define tvispone(o) ((o)->u64 == U64x(3ff00000,00000000))
  600. #define rawnumequal(o1, o2) ((o1)->u64 == (o2)->u64)
  601. /* Macros to convert type ids. */
  602. #if LJ_64
  603. #define itypemap(o) \
  604. (tvisnumber(o) ? ~LJ_TNUMX : tvislightud(o) ? ~LJ_TLIGHTUD : ~itype(o))
  605. #else
  606. #define itypemap(o) (tvisnumber(o) ? ~LJ_TNUMX : ~itype(o))
  607. #endif
  608. /* Macros to get tagged values. */
  609. #define gcval(o) (gcref((o)->gcr))
  610. #define boolV(o) check_exp(tvisbool(o), (LJ_TFALSE - (o)->it))
  611. #if LJ_64
  612. #define lightudV(o) \
  613. check_exp(tvislightud(o), (void *)((o)->u64 & U64x(00007fff,ffffffff)))
  614. #else
  615. #define lightudV(o) check_exp(tvislightud(o), gcrefp((o)->gcr, void))
  616. #endif
  617. #define gcV(o) check_exp(tvisgcv(o), gcval(o))
  618. #define strV(o) check_exp(tvisstr(o), &gcval(o)->str)
  619. #define funcV(o) check_exp(tvisfunc(o), &gcval(o)->fn)
  620. #define threadV(o) check_exp(tvisthread(o), &gcval(o)->th)
  621. #define protoV(o) check_exp(tvisproto(o), &gcval(o)->pt)
  622. #define cdataV(o) check_exp(tviscdata(o), &gcval(o)->cd)
  623. #define tabV(o) check_exp(tvistab(o), &gcval(o)->tab)
  624. #define udataV(o) check_exp(tvisudata(o), &gcval(o)->ud)
  625. #define numV(o) check_exp(tvisnum(o), (o)->n)
  626. #define intV(o) check_exp(tvisint(o), (int32_t)(o)->i)
  627. /* Macros to set tagged values. */
  628. #define setitype(o, i) ((o)->it = (i))
  629. #define setnilV(o) ((o)->it = LJ_TNIL)
  630. #define setboolV(o, x) ((o)->it = LJ_TFALSE-(uint32_t)(x))
  631. static LJ_AINLINE void setlightudV(TValue *o, void *p)
  632. {
  633. #if LJ_64
  634. o->u64 = (uint64_t)p | (((uint64_t)0xffff) << 48);
  635. #else
  636. setgcrefp(o->gcr, p); setitype(o, LJ_TLIGHTUD);
  637. #endif
  638. }
  639. #if LJ_64
  640. #define checklightudptr(L, p) \
  641. (((uint64_t)(p) >> 47) ? (lj_err_msg(L, LJ_ERR_BADLU), NULL) : (p))
  642. #define setcont(o, f) \
  643. ((o)->u64 = (uint64_t)(void *)(f) - (uint64_t)lj_vm_asm_begin)
  644. #else
  645. #define checklightudptr(L, p) (p)
  646. #define setcont(o, f) setlightudV((o), (void *)(f))
  647. #endif
  648. #define tvchecklive(L, o) \
  649. UNUSED(L), lua_assert(!tvisgcv(o) || \
  650. ((~itype(o) == gcval(o)->gch.gct) && !isdead(G(L), gcval(o))))
  651. static LJ_AINLINE void setgcV(lua_State *L, TValue *o, GCobj *v, uint32_t itype)
  652. {
  653. setgcref(o->gcr, v); setitype(o, itype); tvchecklive(L, o);
  654. }
  655. #define define_setV(name, type, tag) \
  656. static LJ_AINLINE void name(lua_State *L, TValue *o, type *v) \
  657. { \
  658. setgcV(L, o, obj2gco(v), tag); \
  659. }
  660. define_setV(setstrV, GCstr, LJ_TSTR)
  661. define_setV(setthreadV, lua_State, LJ_TTHREAD)
  662. define_setV(setprotoV, GCproto, LJ_TPROTO)
  663. define_setV(setfuncV, GCfunc, LJ_TFUNC)
  664. define_setV(setcdataV, GCcdata, LJ_TCDATA)
  665. define_setV(settabV, GCtab, LJ_TTAB)
  666. define_setV(setudataV, GCudata, LJ_TUDATA)
  667. #define setnumV(o, x) ((o)->n = (x))
  668. #define setnanV(o) ((o)->u64 = U64x(fff80000,00000000))
  669. #define setpinfV(o) ((o)->u64 = U64x(7ff00000,00000000))
  670. #define setminfV(o) ((o)->u64 = U64x(fff00000,00000000))
  671. static LJ_AINLINE void setintV(TValue *o, int32_t i)
  672. {
  673. #if LJ_DUALNUM
  674. o->i = (uint32_t)i; setitype(o, LJ_TISNUM);
  675. #else
  676. o->n = (lua_Number)i;
  677. #endif
  678. }
  679. static LJ_AINLINE void setint64V(TValue *o, int64_t i)
  680. {
  681. if (LJ_DUALNUM && LJ_LIKELY(i == (int64_t)(int32_t)i))
  682. setintV(o, (int32_t)i);
  683. else
  684. setnumV(o, (lua_Number)i);
  685. }
  686. #if LJ_64
  687. #define setintptrV(o, i) setint64V((o), (i))
  688. #else
  689. #define setintptrV(o, i) setintV((o), (i))
  690. #endif
  691. /* Copy tagged values. */
  692. static LJ_AINLINE void copyTV(lua_State *L, TValue *o1, const TValue *o2)
  693. {
  694. *o1 = *o2; tvchecklive(L, o1);
  695. }
  696. /* -- Number to integer conversion ---------------------------------------- */
  697. #if LJ_SOFTFP
  698. LJ_ASMF int32_t lj_vm_tobit(double x);
  699. #endif
  700. static LJ_AINLINE int32_t lj_num2bit(lua_Number n)
  701. {
  702. #if LJ_SOFTFP
  703. return lj_vm_tobit(n);
  704. #else
  705. TValue o;
  706. o.n = n + 6755399441055744.0; /* 2^52 + 2^51 */
  707. return (int32_t)o.u32.lo;
  708. #endif
  709. }
  710. #if LJ_TARGET_X86 && !defined(__SSE2__)
  711. #define lj_num2int(n) lj_num2bit((n))
  712. #else
  713. #define lj_num2int(n) ((int32_t)(n))
  714. #endif
  715. static LJ_AINLINE uint64_t lj_num2u64(lua_Number n)
  716. {
  717. #ifdef _MSC_VER
  718. if (n >= 9223372036854775808.0) /* They think it's a feature. */
  719. return (uint64_t)(int64_t)(n - 18446744073709551616.0);
  720. else
  721. #endif
  722. return (uint64_t)n;
  723. }
  724. static LJ_AINLINE int32_t numberVint(cTValue *o)
  725. {
  726. if (LJ_LIKELY(tvisint(o)))
  727. return intV(o);
  728. else
  729. return lj_num2int(numV(o));
  730. }
  731. static LJ_AINLINE lua_Number numberVnum(cTValue *o)
  732. {
  733. if (LJ_UNLIKELY(tvisint(o)))
  734. return (lua_Number)intV(o);
  735. else
  736. return numV(o);
  737. }
  738. /* -- Miscellaneous object handling --------------------------------------- */
  739. /* Names and maps for internal and external object tags. */
  740. LJ_DATA const char *const lj_obj_typename[1+LUA_TCDATA+1];
  741. LJ_DATA const char *const lj_obj_itypename[~LJ_TNUMX+1];
  742. #define lj_typename(o) (lj_obj_itypename[itypemap(o)])
  743. /* Compare two objects without calling metamethods. */
  744. LJ_FUNC int lj_obj_equal(cTValue *o1, cTValue *o2);
  745. #endif