lstate.c 12 KB

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