• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 ** $Id: lstate.c $
3 ** Global State
4 ** See Copyright Notice in lua.h
5 */
6 
7 #define lstate_c
8 #define LUA_CORE
9 
10 #include "lprefix.h"
11 
12 
13 #include <stddef.h>
14 #include <string.h>
15 
16 #include "lua.h"
17 
18 #include "lapi.h"
19 #include "ldebug.h"
20 #include "ldo.h"
21 #include "lfunc.h"
22 #include "lgc.h"
23 #include "llex.h"
24 #include "lmem.h"
25 #include "lstate.h"
26 #include "lstring.h"
27 #include "ltable.h"
28 #include "ltm.h"
29 
30 
31 
32 /*
33 ** thread state + extra space
34 */
35 typedef struct LX {
36   lu_byte extra_[LUA_EXTRASPACE];
37   lua_State l;
38 } LX;
39 
40 
41 /*
42 ** Main thread combines a thread state and the global state
43 */
44 typedef struct LG {
45   LX l;
46   global_State g;
47 } LG;
48 
49 
50 
51 #define fromstate(L)	(cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))
52 
53 
54 /*
55 ** A macro to create a "random" seed when a state is created;
56 ** the seed is used to randomize string hashes.
57 */
58 #if !defined(luai_makeseed)
59 
60 #include <time.h>
61 
62 /*
63 ** Compute an initial seed with some level of randomness.
64 ** Rely on Address Space Layout Randomization (if present) and
65 ** current time.
66 */
67 #define addbuff(b,p,e) \
68   { size_t t = cast_sizet(e); \
69     memcpy(b + p, &t, sizeof(t)); p += sizeof(t); }
70 
luai_makeseed(lua_State * L)71 static unsigned int luai_makeseed (lua_State *L) {
72   char buff[3 * sizeof(size_t)];
73   unsigned int h = cast_uint(time(NULL));
74   int p = 0;
75   addbuff(buff, p, L);  /* heap variable */
76   addbuff(buff, p, &h);  /* local variable */
77   addbuff(buff, p, &lua_newstate);  /* public function */
78   lua_assert(p == sizeof(buff));
79   return luaS_hash(buff, p, h, 1);
80 }
81 
82 #endif
83 
84 
85 /*
86 ** set GCdebt to a new value keeping the value (totalbytes + GCdebt)
87 ** invariant (and avoiding underflows in 'totalbytes')
88 */
luaE_setdebt(global_State * g,l_mem debt)89 void luaE_setdebt (global_State *g, l_mem debt) {
90   l_mem tb = gettotalbytes(g);
91   lua_assert(tb > 0);
92   if (debt < tb - MAX_LMEM)
93     debt = tb - MAX_LMEM;  /* will make 'totalbytes == MAX_LMEM' */
94   g->totalbytes = tb - debt;
95   g->GCdebt = debt;
96 }
97 
98 
lua_setcstacklimit(lua_State * L,unsigned int limit)99 LUA_API int lua_setcstacklimit (lua_State *L, unsigned int limit) {
100   global_State *g = G(L);
101   int ccalls;
102   luaE_freeCI(L);  /* release unused CIs */
103   ccalls = getCcalls(L);
104   if (limit >= 40000)
105     return 0;  /* out of bounds */
106   limit += CSTACKERR;
107   if (L != g-> mainthread)
108     return 0;  /* only main thread can change the C stack */
109   else if (ccalls <= CSTACKERR)
110     return 0;  /* handling overflow */
111   else {
112     int diff = limit - g->Cstacklimit;
113     if (ccalls + diff <= CSTACKERR)
114       return 0;  /* new limit would cause an overflow */
115     g->Cstacklimit = limit;  /* set new limit */
116     L->nCcalls += diff;  /* correct 'nCcalls' */
117     return limit - diff - CSTACKERR;  /* success; return previous limit */
118   }
119 }
120 
121 
122 /*
123 ** Decrement count of "C calls" and check for overflows. In case of
124 ** a stack overflow, check appropriate error ("regular" overflow or
125 ** overflow while handling stack overflow).  If 'nCcalls' is smaller
126 ** than CSTACKERR but larger than CSTACKMARK, it means it has just
127 ** entered the "overflow zone", so the function raises an overflow
128 ** error.  If 'nCcalls' is smaller than CSTACKMARK (which means it is
129 ** already handling an overflow) but larger than CSTACKERRMARK, does
130 ** not report an error (to allow message handling to work). Otherwise,
131 ** report a stack overflow while handling a stack overflow (probably
132 ** caused by a repeating error in the message handling function).
133 */
134 
luaE_enterCcall(lua_State * L)135 void luaE_enterCcall (lua_State *L) {
136   int ncalls = getCcalls(L);
137   L->nCcalls--;
138   if (ncalls <= CSTACKERR) {  /* possible overflow? */
139     luaE_freeCI(L);  /* release unused CIs */
140     ncalls = getCcalls(L);  /* update call count */
141     if (ncalls <= CSTACKERR) {  /* still overflow? */
142       if (ncalls <= CSTACKERRMARK)  /* below error-handling zone? */
143         luaD_throw(L, LUA_ERRERR);  /* error while handling stack error */
144       else if (ncalls >= CSTACKMARK) {
145         /* not in error-handling zone; raise the error now */
146         L->nCcalls = (CSTACKMARK - 1);  /* enter error-handling zone */
147         luaG_runerror(L, "C stack overflow");
148       }
149       /* else stack is in the error-handling zone;
150          allow message handler to work */
151     }
152   }
153 }
154 
155 
luaE_extendCI(lua_State * L)156 CallInfo *luaE_extendCI (lua_State *L) {
157   CallInfo *ci;
158   lua_assert(L->ci->next == NULL);
159   luaE_enterCcall(L);
160   ci = luaM_new(L, CallInfo);
161   lua_assert(L->ci->next == NULL);
162   L->ci->next = ci;
163   ci->previous = L->ci;
164   ci->next = NULL;
165   ci->u.l.trap = 0;
166   L->nci++;
167   return ci;
168 }
169 
170 
171 /*
172 ** free all CallInfo structures not in use by a thread
173 */
luaE_freeCI(lua_State * L)174 void luaE_freeCI (lua_State *L) {
175   CallInfo *ci = L->ci;
176   CallInfo *next = ci->next;
177   ci->next = NULL;
178   L->nCcalls += L->nci;  /* add removed elements back to 'nCcalls' */
179   while ((ci = next) != NULL) {
180     next = ci->next;
181     luaM_free(L, ci);
182     L->nci--;
183   }
184   L->nCcalls -= L->nci;  /* adjust result */
185 }
186 
187 
188 /*
189 ** free half of the CallInfo structures not in use by a thread,
190 ** keeping the first one.
191 */
luaE_shrinkCI(lua_State * L)192 void luaE_shrinkCI (lua_State *L) {
193   CallInfo *ci = L->ci->next;  /* first free CallInfo */
194   CallInfo *next;
195   if (ci == NULL)
196     return;  /* no extra elements */
197   L->nCcalls += L->nci;  /* add removed elements back to 'nCcalls' */
198   while ((next = ci->next) != NULL) {  /* two extra elements? */
199     CallInfo *next2 = next->next;  /* next's next */
200     ci->next = next2;  /* remove next from the list */
201     L->nci--;
202     luaM_free(L, next);  /* free next */
203     if (next2 == NULL)
204       break;  /* no more elements */
205     else {
206       next2->previous = ci;
207       ci = next2;  /* continue */
208     }
209   }
210   L->nCcalls -= L->nci;  /* adjust result */
211 }
212 
213 
stack_init(lua_State * L1,lua_State * L)214 static void stack_init (lua_State *L1, lua_State *L) {
215   int i; CallInfo *ci;
216   /* initialize stack array */
217   L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, StackValue);
218   L1->stacksize = BASIC_STACK_SIZE;
219   for (i = 0; i < BASIC_STACK_SIZE; i++)
220     setnilvalue(s2v(L1->stack + i));  /* erase new stack */
221   L1->top = L1->stack;
222   L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK;
223   /* initialize first ci */
224   ci = &L1->base_ci;
225   ci->next = ci->previous = NULL;
226   ci->callstatus = CIST_C;
227   ci->func = L1->top;
228   ci->u.c.k = NULL;
229   ci->nresults = 0;
230   setnilvalue(s2v(L1->top));  /* 'function' entry for this 'ci' */
231   L1->top++;
232   ci->top = L1->top + LUA_MINSTACK;
233   L1->ci = ci;
234 }
235 
236 
freestack(lua_State * L)237 static void freestack (lua_State *L) {
238   if (L->stack == NULL)
239     return;  /* stack not completely built yet */
240   L->ci = &L->base_ci;  /* free the entire 'ci' list */
241   luaE_freeCI(L);
242   lua_assert(L->nci == 0);
243   luaM_freearray(L, L->stack, L->stacksize);  /* free stack array */
244 }
245 
246 
247 /*
248 ** Create registry table and its predefined values
249 */
init_registry(lua_State * L,global_State * g)250 static void init_registry (lua_State *L, global_State *g) {
251   TValue temp;
252   /* create registry */
253   Table *registry = luaH_new(L);
254   sethvalue(L, &g->l_registry, registry);
255   luaH_resize(L, registry, LUA_RIDX_LAST, 0);
256   /* registry[LUA_RIDX_MAINTHREAD] = L */
257   setthvalue(L, &temp, L);  /* temp = L */
258   luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);
259   /* registry[LUA_RIDX_GLOBALS] = table of globals */
260   sethvalue(L, &temp, luaH_new(L));  /* temp = new table (global table) */
261   luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);
262 }
263 
264 
265 /*
266 ** open parts of the state that may cause memory-allocation errors.
267 ** ('g->nilvalue' being a nil value flags that the state was completely
268 ** build.)
269 */
f_luaopen(lua_State * L,void * ud)270 static void f_luaopen (lua_State *L, void *ud) {
271   global_State *g = G(L);
272   UNUSED(ud);
273   stack_init(L, L);  /* init stack */
274   init_registry(L, g);
275   luaS_init(L);
276   luaT_init(L);
277   luaX_init(L);
278   g->gcrunning = 1;  /* allow gc */
279   setnilvalue(&g->nilvalue);
280   luai_userstateopen(L);
281 }
282 
283 
284 /*
285 ** preinitialize a thread with consistent values without allocating
286 ** any memory (to avoid errors)
287 */
preinit_thread(lua_State * L,global_State * g)288 static void preinit_thread (lua_State *L, global_State *g) {
289   G(L) = g;
290   L->stack = NULL;
291   L->ci = NULL;
292   L->nci = 0;
293   L->stacksize = 0;
294   L->twups = L;  /* thread has no upvalues */
295   L->errorJmp = NULL;
296   L->hook = NULL;
297   L->hookmask = 0;
298   L->basehookcount = 0;
299   L->allowhook = 1;
300   resethookcount(L);
301   L->openupval = NULL;
302   L->status = LUA_OK;
303   L->errfunc = 0;
304   L->oldpc = 0;
305 }
306 
307 
close_state(lua_State * L)308 static void close_state (lua_State *L) {
309   global_State *g = G(L);
310   luaF_close(L, L->stack, CLOSEPROTECT);  /* close all upvalues */
311   luaC_freeallobjects(L);  /* collect all objects */
312   if (ttisnil(&g->nilvalue))  /* closing a fully built state? */
313     luai_userstateclose(L);
314   luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
315   freestack(L);
316   lua_assert(gettotalbytes(g) == sizeof(LG));
317   (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0);  /* free main block */
318 }
319 
320 
lua_newthread(lua_State * L)321 LUA_API lua_State *lua_newthread (lua_State *L) {
322   global_State *g;
323   lua_State *L1;
324   lua_lock(L);
325   g = G(L);
326   luaC_checkGC(L);
327   /* create new thread */
328   L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l;
329   L1->marked = luaC_white(g);
330   L1->tt = LUA_VTHREAD;
331   /* link it on list 'allgc' */
332   L1->next = g->allgc;
333   g->allgc = obj2gco(L1);
334   /* anchor it on L stack */
335   setthvalue2s(L, L->top, L1);
336   api_incr_top(L);
337   preinit_thread(L1, g);
338   L1->nCcalls = getCcalls(L);
339   L1->hookmask = L->hookmask;
340   L1->basehookcount = L->basehookcount;
341   L1->hook = L->hook;
342   resethookcount(L1);
343   /* initialize L1 extra space */
344   memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread),
345          LUA_EXTRASPACE);
346   luai_userstatethread(L, L1);
347   stack_init(L1, L);  /* init stack */
348   lua_unlock(L);
349   return L1;
350 }
351 
352 
luaE_freethread(lua_State * L,lua_State * L1)353 void luaE_freethread (lua_State *L, lua_State *L1) {
354   LX *l = fromstate(L1);
355   luaF_close(L1, L1->stack, NOCLOSINGMETH);  /* close all upvalues */
356   lua_assert(L1->openupval == NULL);
357   luai_userstatefree(L, L1);
358   freestack(L1);
359   luaM_free(L, l);
360 }
361 
362 
lua_resetthread(lua_State * L)363 int lua_resetthread (lua_State *L) {
364   CallInfo *ci;
365   int status;
366   lua_lock(L);
367   L->ci = ci = &L->base_ci;  /* unwind CallInfo list */
368   setnilvalue(s2v(L->stack));  /* 'function' entry for basic 'ci' */
369   ci->func = L->stack;
370   ci->callstatus = CIST_C;
371   status = luaF_close(L, L->stack, CLOSEPROTECT);
372   if (status != CLOSEPROTECT)  /* real errors? */
373     luaD_seterrorobj(L, status, L->stack + 1);
374   else {
375     status = LUA_OK;
376     L->top = L->stack + 1;
377   }
378   ci->top = L->top + LUA_MINSTACK;
379   L->status = status;
380   lua_unlock(L);
381   return status;
382 }
383 
384 
lua_newstate(lua_Alloc f,void * ud)385 LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
386   int i;
387   lua_State *L;
388   global_State *g;
389   LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));
390   if (l == NULL) return NULL;
391   L = &l->l.l;
392   g = &l->g;
393   L->tt = LUA_VTHREAD;
394   g->currentwhite = bitmask(WHITE0BIT);
395   L->marked = luaC_white(g);
396   preinit_thread(L, g);
397   g->allgc = obj2gco(L);  /* by now, only object is the main thread */
398   L->next = NULL;
399   g->Cstacklimit = L->nCcalls = LUAI_MAXCSTACK + CSTACKERR;
400   incnny(L);  /* main thread is always non yieldable */
401   g->frealloc = f;
402   g->ud = ud;
403   g->warnf = NULL;
404   g->ud_warn = NULL;
405   g->mainthread = L;
406   g->seed = luai_makeseed(L);
407   g->gcrunning = 0;  /* no GC while building state */
408   g->strt.size = g->strt.nuse = 0;
409   g->strt.hash = NULL;
410   setnilvalue(&g->l_registry);
411   g->panic = NULL;
412   g->gcstate = GCSpause;
413   g->gckind = KGC_INC;
414   g->gcemergency = 0;
415   g->finobj = g->tobefnz = g->fixedgc = NULL;
416   g->firstold1 = g->survival = g->old1 = g->reallyold = NULL;
417   g->finobjsur = g->finobjold1 = g->finobjrold = NULL;
418   g->sweepgc = NULL;
419   g->gray = g->grayagain = NULL;
420   g->weak = g->ephemeron = g->allweak = NULL;
421   g->twups = NULL;
422   g->totalbytes = sizeof(LG);
423   g->GCdebt = 0;
424   g->lastatomic = 0;
425   setivalue(&g->nilvalue, 0);  /* to signal that state is not yet built */
426   setgcparam(g->gcpause, LUAI_GCPAUSE);
427   setgcparam(g->gcstepmul, LUAI_GCMUL);
428   g->gcstepsize = LUAI_GCSTEPSIZE;
429   setgcparam(g->genmajormul, LUAI_GENMAJORMUL);
430   g->genminormul = LUAI_GENMINORMUL;
431   for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
432   if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
433     /* memory allocation error: free partial state */
434     close_state(L);
435     L = NULL;
436   }
437   return L;
438 }
439 
440 
lua_close(lua_State * L)441 LUA_API void lua_close (lua_State *L) {
442   lua_lock(L);
443   L = G(L)->mainthread;  /* only the main thread can be closed */
444   close_state(L);
445 }
446 
447 
luaE_warning(lua_State * L,const char * msg,int tocont)448 void luaE_warning (lua_State *L, const char *msg, int tocont) {
449   lua_WarnFunction wf = G(L)->warnf;
450   if (wf != NULL)
451     wf(G(L)->ud_warn, msg, tocont);
452 }
453 
454 
455 /*
456 ** Generate a warning from an error message
457 */
luaE_warnerror(lua_State * L,const char * where)458 void luaE_warnerror (lua_State *L, const char *where) {
459   TValue *errobj = s2v(L->top - 1);  /* error object */
460   const char *msg = (ttisstring(errobj))
461                   ? svalue(errobj)
462                   : "error object is not a string";
463   /* produce warning "error in %s (%s)" (where, msg) */
464   luaE_warning(L, "error in ", 1);
465   luaE_warning(L, where, 1);
466   luaE_warning(L, " (", 1);
467   luaE_warning(L, msg, 1);
468   luaE_warning(L, ")", 0);
469 }
470 
471