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