1/*	$NetBSD: lstate.h,v 1.11 2023/06/08 21:12:08 nikita Exp $	*/
2
3/*
4** Id: lstate.h
5** Global State
6** See Copyright Notice in lua.h
7*/
8
9#ifndef lstate_h
10#define lstate_h
11
12#include "lua.h"
13
14
15/* Some header files included here need this definition */
16typedef struct CallInfo CallInfo;
17
18
19#include "lobject.h"
20#include "ltm.h"
21#include "lzio.h"
22
23
24/*
25** Some notes about garbage-collected objects: All objects in Lua must
26** be kept somehow accessible until being freed, so all objects always
27** belong to one (and only one) of these lists, using field 'next' of
28** the 'CommonHeader' for the link:
29**
30** 'allgc': all objects not marked for finalization;
31** 'finobj': all objects marked for finalization;
32** 'tobefnz': all objects ready to be finalized;
33** 'fixedgc': all objects that are not to be collected (currently
34** only small strings, such as reserved words).
35**
36** For the generational collector, some of these lists have marks for
37** generations. Each mark points to the first element in the list for
38** that particular generation; that generation goes until the next mark.
39**
40** 'allgc' -> 'survival': new objects;
41** 'survival' -> 'old': objects that survived one collection;
42** 'old1' -> 'reallyold': objects that became old in last collection;
43** 'reallyold' -> NULL: objects old for more than one cycle.
44**
45** 'finobj' -> 'finobjsur': new objects marked for finalization;
46** 'finobjsur' -> 'finobjold1': survived   """";
47** 'finobjold1' -> 'finobjrold': just old  """";
48** 'finobjrold' -> NULL: really old       """".
49**
50** All lists can contain elements older than their main ages, due
51** to 'luaC_checkfinalizer' and 'udata2finalize', which move
52** objects between the normal lists and the "marked for finalization"
53** lists. Moreover, barriers can age young objects in young lists as
54** OLD0, which then become OLD1. However, a list never contains
55** elements younger than their main ages.
56**
57** The generational collector also uses a pointer 'firstold1', which
58** points to the first OLD1 object in the list. It is used to optimize
59** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'
60** and 'reallyold', but often the list has no OLD1 objects or they are
61** after 'old1'.) Note the difference between it and 'old1':
62** 'firstold1': no OLD1 objects before this point; there can be all
63**   ages after it.
64** 'old1': no objects younger than OLD1 after this point.
65*/
66
67/*
68** Moreover, there is another set of lists that control gray objects.
69** These lists are linked by fields 'gclist'. (All objects that
70** can become gray have such a field. The field is not the same
71** in all objects, but it always has this name.)  Any gray object
72** must belong to one of these lists, and all objects in these lists
73** must be gray (with two exceptions explained below):
74**
75** 'gray': regular gray objects, still waiting to be visited.
76** 'grayagain': objects that must be revisited at the atomic phase.
77**   That includes
78**   - black objects got in a write barrier;
79**   - all kinds of weak tables during propagation phase;
80**   - all threads.
81** 'weak': tables with weak values to be cleared;
82** 'ephemeron': ephemeron tables with white->white entries;
83** 'allweak': tables with weak keys and/or weak values to be cleared.
84**
85** The exceptions to that "gray rule" are:
86** - TOUCHED2 objects in generational mode stay in a gray list (because
87** they must be visited again at the end of the cycle), but they are
88** marked black because assignments to them must activate barriers (to
89** move them back to TOUCHED1).
90** - Open upvales are kept gray to avoid barriers, but they stay out
91** of gray lists. (They don't even have a 'gclist' field.)
92*/
93
94
95
96/*
97** About 'nCcalls':  This count has two parts: the lower 16 bits counts
98** the number of recursive invocations in the C stack; the higher
99** 16 bits counts the number of non-yieldable calls in the stack.
100** (They are together so that we can change and save both with one
101** instruction.)
102*/
103
104
105/* true if this thread does not have non-yieldable calls in the stack */
106#define yieldable(L)		(((L)->nCcalls & 0xffff0000) == 0)
107
108/* real number of C calls */
109#define getCcalls(L)	((L)->nCcalls & 0xffff)
110
111
112/* Increment the number of non-yieldable calls */
113#define incnny(L)	((L)->nCcalls += 0x10000)
114
115/* Decrement the number of non-yieldable calls */
116#define decnny(L)	((L)->nCcalls -= 0x10000)
117
118/* Non-yieldable call increment */
119#define nyci	(0x10000 | 1)
120
121
122
123
124struct lua_longjmp;  /* defined in ldo.c */
125
126
127/*
128** Atomic type (relative to signals) to better ensure that 'lua_sethook'
129** is thread safe
130*/
131#if !defined(l_signalT)
132#include <signal.h>
133#define l_signalT	sig_atomic_t
134#endif
135
136
137/*
138** Extra stack space to handle TM calls and some other extras. This
139** space is not included in 'stack_last'. It is used only to avoid stack
140** checks, either because the element will be promptly popped or because
141** there will be a stack check soon after the push. Function frames
142** never use this extra space, so it does not need to be kept clean.
143*/
144#define EXTRA_STACK   5
145
146
147#define BASIC_STACK_SIZE        (2*LUA_MINSTACK)
148
149#define stacksize(th)	cast_int((th)->stack_last.p - (th)->stack.p)
150
151
152/* kinds of Garbage Collection */
153#define KGC_INC		0	/* incremental gc */
154#define KGC_GEN		1	/* generational gc */
155
156
157typedef struct stringtable {
158  TString **hash;
159  int nuse;  /* number of elements */
160  int size;
161} stringtable;
162
163
164/*
165** Information about a call.
166** About union 'u':
167** - field 'l' is used only for Lua functions;
168** - field 'c' is used only for C functions.
169** About union 'u2':
170** - field 'funcidx' is used only by C functions while doing a
171** protected call;
172** - field 'nyield' is used only while a function is "doing" an
173** yield (from the yield until the next resume);
174** - field 'nres' is used only while closing tbc variables when
175** returning from a function;
176** - field 'transferinfo' is used only during call/returnhooks,
177** before the function starts or after it ends.
178*/
179struct CallInfo {
180  StkIdRel func;  /* function index in the stack */
181  StkIdRel	top;  /* top for this function */
182  struct CallInfo *previous, *next;  /* dynamic call link */
183  union {
184    struct {  /* only for Lua functions */
185      const Instruction *savedpc;
186      volatile l_signalT trap;
187      int nextraargs;  /* # of extra arguments in vararg functions */
188    } l;
189    struct {  /* only for C functions */
190      lua_KFunction k;  /* continuation in case of yields */
191      ptrdiff_t old_errfunc;
192      lua_KContext ctx;  /* context info. in case of yields */
193    } c;
194  } u;
195  union {
196    int funcidx;  /* called-function index */
197    int nyield;  /* number of values yielded */
198    int nres;  /* number of values returned */
199    struct {  /* info about transferred values (for call/return hooks) */
200      unsigned short ftransfer;  /* offset of first value transferred */
201      unsigned short ntransfer;  /* number of values transferred */
202    } transferinfo;
203  } u2;
204  short nresults;  /* expected number of results from this function */
205  unsigned short callstatus;
206};
207
208
209/*
210** Bits in CallInfo status
211*/
212#define CIST_OAH	(1<<0)	/* original value of 'allowhook' */
213#define CIST_C		(1<<1)	/* call is running a C function */
214#define CIST_FRESH	(1<<2)	/* call is on a fresh "luaV_execute" frame */
215#define CIST_HOOKED	(1<<3)	/* call is running a debug hook */
216#define CIST_YPCALL	(1<<4)	/* doing a yieldable protected call */
217#define CIST_TAIL	(1<<5)	/* call was tail called */
218#define CIST_HOOKYIELD	(1<<6)	/* last hook called yielded */
219#define CIST_FIN	(1<<7)	/* function "called" a finalizer */
220#define CIST_TRAN	(1<<8)	/* 'ci' has transfer information */
221#define CIST_CLSRET	(1<<9)  /* function is closing tbc variables */
222/* Bits 10-12 are used for CIST_RECST (see below) */
223#define CIST_RECST	10
224#if defined(LUA_COMPAT_LT_LE)
225#define CIST_LEQ	(1<<13)  /* using __lt for __le */
226#endif
227
228
229/*
230** Field CIST_RECST stores the "recover status", used to keep the error
231** status while closing to-be-closed variables in coroutines, so that
232** Lua can correctly resume after an yield from a __close method called
233** because of an error.  (Three bits are enough for error status.)
234*/
235#define getcistrecst(ci)     (((ci)->callstatus >> CIST_RECST) & 7)
236#define setcistrecst(ci,st)  \
237  check_exp(((st) & 7) == (st),   /* status must fit in three bits */  \
238            ((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST))  \
239                                                  | ((st) << CIST_RECST)))
240
241
242/* active function is a Lua function */
243#define isLua(ci)	(!((ci)->callstatus & CIST_C))
244
245/* call is running Lua code (not a hook) */
246#define isLuacode(ci)	(!((ci)->callstatus & (CIST_C | CIST_HOOKED)))
247
248/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
249#define setoah(st,v)	((st) = ((st) & ~CIST_OAH) | (v))
250#define getoah(st)	((st) & CIST_OAH)
251
252
253/*
254** 'global state', shared by all threads of this state
255*/
256typedef struct global_State {
257  lua_Alloc frealloc;  /* function to reallocate memory */
258  void *ud;         /* auxiliary data to 'frealloc' */
259  l_mem totalbytes;  /* number of bytes currently allocated - GCdebt */
260  l_mem GCdebt;  /* bytes allocated not yet compensated by the collector */
261  lu_mem GCestimate;  /* an estimate of the non-garbage memory in use */
262  lu_mem lastatomic;  /* see function 'genstep' in file 'lgc.c' */
263  stringtable strt;  /* hash table for strings */
264  TValue l_registry;
265  TValue nilvalue;  /* a nil value */
266  unsigned int seed;  /* randomized seed for hashes */
267  lu_byte currentwhite;
268  lu_byte gcstate;  /* state of garbage collector */
269  lu_byte gckind;  /* kind of GC running */
270  lu_byte gcstopem;  /* stops emergency collections */
271  lu_byte genminormul;  /* control for minor generational collections */
272  lu_byte genmajormul;  /* control for major generational collections */
273  lu_byte gcstp;  /* control whether GC is running */
274  lu_byte gcemergency;  /* true if this is an emergency collection */
275  lu_byte gcpause;  /* size of pause between successive GCs */
276  lu_byte gcstepmul;  /* GC "speed" */
277  lu_byte gcstepsize;  /* (log2 of) GC granularity */
278  GCObject *allgc;  /* list of all collectable objects */
279  GCObject **sweepgc;  /* current position of sweep in list */
280  GCObject *finobj;  /* list of collectable objects with finalizers */
281  GCObject *gray;  /* list of gray objects */
282  GCObject *grayagain;  /* list of objects to be traversed atomically */
283  GCObject *weak;  /* list of tables with weak values */
284  GCObject *ephemeron;  /* list of ephemeron tables (weak keys) */
285  GCObject *allweak;  /* list of all-weak tables */
286  GCObject *tobefnz;  /* list of userdata to be GC */
287  GCObject *fixedgc;  /* list of objects not to be collected */
288  /* fields for generational collector */
289  GCObject *survival;  /* start of objects that survived one GC cycle */
290  GCObject *old1;  /* start of old1 objects */
291  GCObject *reallyold;  /* objects more than one cycle old ("really old") */
292  GCObject *firstold1;  /* first OLD1 object in the list (if any) */
293  GCObject *finobjsur;  /* list of survival objects with finalizers */
294  GCObject *finobjold1;  /* list of old1 objects with finalizers */
295  GCObject *finobjrold;  /* list of really old objects with finalizers */
296  struct lua_State *twups;  /* list of threads with open upvalues */
297  lua_CFunction panic;  /* to be called in unprotected errors */
298  struct lua_State *mainthread;
299  TString *memerrmsg;  /* message for memory-allocation errors */
300  TString *tmname[TM_N];  /* array with tag-method names */
301  struct Table *mt[LUA_NUMTYPES];  /* metatables for basic types */
302  TString *strcache[STRCACHE_N][STRCACHE_M];  /* cache for strings in API */
303  lua_WarnFunction warnf;  /* warning function */
304  void *ud_warn;         /* auxiliary data to 'warnf' */
305} global_State;
306
307
308/*
309** 'per thread' state
310*/
311struct lua_State {
312  CommonHeader;
313  lu_byte status;
314  lu_byte allowhook;
315  unsigned short nci;  /* number of items in 'ci' list */
316  StkIdRel top;  /* first free slot in the stack */
317  global_State *l_G;
318  CallInfo *ci;  /* call info for current function */
319  StkIdRel stack_last;  /* end of stack (last element + 1) */
320  StkIdRel stack;  /* stack base */
321  UpVal *openupval;  /* list of open upvalues in this stack */
322  StkIdRel tbclist;  /* list of to-be-closed variables */
323  GCObject *gclist;
324  struct lua_State *twups;  /* list of threads with open upvalues */
325  struct lua_longjmp *errorJmp;  /* current error recover point */
326  CallInfo base_ci;  /* CallInfo for first level (C calling Lua) */
327  volatile lua_Hook hook;
328  ptrdiff_t errfunc;  /* current error handling function (stack index) */
329  l_uint32 nCcalls;  /* number of nested (non-yieldable | C)  calls */
330  int oldpc;  /* last pc traced */
331  int basehookcount;
332  int hookcount;
333  volatile l_signalT hookmask;
334};
335
336
337#define G(L)	(L->l_G)
338
339/*
340** 'g->nilvalue' being a nil value flags that the state was completely
341** build.
342*/
343#define completestate(g)	ttisnil(&g->nilvalue)
344
345
346/*
347** Union of all collectable objects (only for conversions)
348** ISO C99, 6.5.2.3 p.5:
349** "if a union contains several structures that share a common initial
350** sequence [...], and if the union object currently contains one
351** of these structures, it is permitted to inspect the common initial
352** part of any of them anywhere that a declaration of the complete type
353** of the union is visible."
354*/
355union GCUnion {
356  GCObject gc;  /* common header */
357  struct TString ts;
358  struct Udata u;
359  union Closure cl;
360  struct Table h;
361  struct Proto p;
362  struct lua_State th;  /* thread */
363  struct UpVal upv;
364};
365
366
367/*
368** ISO C99, 6.7.2.1 p.14:
369** "A pointer to a union object, suitably converted, points to each of
370** its members [...], and vice versa."
371*/
372#define cast_u(o)	cast(union GCUnion *, (o))
373
374/* macros to convert a GCObject into a specific value */
375#define gco2ts(o)  \
376	check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
377#define gco2u(o)  check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
378#define gco2lcl(o)  check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
379#define gco2ccl(o)  check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
380#define gco2cl(o)  \
381	check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
382#define gco2t(o)  check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
383#define gco2p(o)  check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
384#define gco2th(o)  check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
385#define gco2upv(o)	check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
386
387
388/*
389** macro to convert a Lua object into a GCObject
390** (The access to 'tt' tries to ensure that 'v' is actually a Lua object.)
391*/
392#define obj2gco(v)	check_exp((v)->tt >= LUA_TSTRING, &(cast_u(v)->gc))
393
394
395/* actual number of total bytes allocated */
396#define gettotalbytes(g)	cast(lu_mem, (g)->totalbytes + (g)->GCdebt)
397
398LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
399LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
400LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
401LUAI_FUNC void luaE_freeCI (lua_State *L);
402LUAI_FUNC void luaE_shrinkCI (lua_State *L);
403LUAI_FUNC void luaE_checkcstack (lua_State *L);
404LUAI_FUNC void luaE_incCstack (lua_State *L);
405LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
406LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
407LUAI_FUNC int luaE_resetthread (lua_State *L, int status);
408
409
410#endif
411
412