lstate.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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);
  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. */
  158. void luaE_shrinkCI (lua_State *L) {
  159. CallInfo *ci = L->ci;
  160. CallInfo *next2; /* next's next */
  161. L->nCcalls += L->nci; /* add removed elements back to 'nCcalls' */
  162. /* while there are two nexts */
  163. while (ci->next != NULL && (next2 = ci->next->next) != NULL) {
  164. luaM_free(L, ci->next); /* free next */
  165. L->nci--;
  166. ci->next = next2; /* remove 'next' from the list */
  167. next2->previous = ci;
  168. ci = next2; /* keep next's next */
  169. }
  170. L->nCcalls -= L->nci; /* adjust result */
  171. }
  172. static void stack_init (lua_State *L1, lua_State *L) {
  173. int i; CallInfo *ci;
  174. /* initialize stack array */
  175. L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, StackValue);
  176. L1->stacksize = BASIC_STACK_SIZE;
  177. for (i = 0; i < BASIC_STACK_SIZE; i++)
  178. setnilvalue(s2v(L1->stack + i)); /* erase new stack */
  179. L1->top = L1->stack;
  180. L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK;
  181. /* initialize first ci */
  182. ci = &L1->base_ci;
  183. ci->next = ci->previous = NULL;
  184. ci->callstatus = CIST_C;
  185. ci->func = L1->top;
  186. ci->u.c.k = NULL;
  187. ci->nresults = 0;
  188. setnilvalue(s2v(L1->top)); /* 'function' entry for this 'ci' */
  189. L1->top++;
  190. ci->top = L1->top + LUA_MINSTACK;
  191. L1->ci = ci;
  192. }
  193. static void freestack (lua_State *L) {
  194. if (L->stack == NULL)
  195. return; /* stack not completely built yet */
  196. L->ci = &L->base_ci; /* free the entire 'ci' list */
  197. luaE_freeCI(L);
  198. lua_assert(L->nci == 0);
  199. luaM_freearray(L, L->stack, L->stacksize); /* free stack array */
  200. }
  201. /*
  202. ** Create registry table and its predefined values
  203. */
  204. static void init_registry (lua_State *L, global_State *g) {
  205. TValue temp;
  206. /* create registry */
  207. Table *registry = luaH_new(L);
  208. sethvalue(L, &g->l_registry, registry);
  209. luaH_resize(L, registry, LUA_RIDX_LAST, 0);
  210. /* registry[LUA_RIDX_MAINTHREAD] = L */
  211. setthvalue(L, &temp, L); /* temp = L */
  212. luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);
  213. /* registry[LUA_RIDX_GLOBALS] = table of globals */
  214. sethvalue(L, &temp, luaH_new(L)); /* temp = new table (global table) */
  215. luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);
  216. }
  217. /*
  218. ** open parts of the state that may cause memory-allocation errors.
  219. ** ('g->nilvalue' being a nil value flags that the state was completely
  220. ** build.)
  221. */
  222. static void f_luaopen (lua_State *L, void *ud) {
  223. global_State *g = G(L);
  224. UNUSED(ud);
  225. stack_init(L, L); /* init stack */
  226. init_registry(L, g);
  227. luaS_init(L);
  228. luaT_init(L);
  229. luaX_init(L);
  230. g->gcrunning = 1; /* allow gc */
  231. setnilvalue(&g->nilvalue);
  232. luai_userstateopen(L);
  233. }
  234. /*
  235. ** preinitialize a thread with consistent values without allocating
  236. ** any memory (to avoid errors)
  237. */
  238. static void preinit_thread (lua_State *L, global_State *g) {
  239. G(L) = g;
  240. L->stack = NULL;
  241. L->ci = NULL;
  242. L->nci = 0;
  243. L->stacksize = 0;
  244. L->twups = L; /* thread has no upvalues */
  245. L->errorJmp = NULL;
  246. L->nCcalls = CSTACKTHREAD;
  247. L->hook = NULL;
  248. L->hookmask = 0;
  249. L->basehookcount = 0;
  250. L->allowhook = 1;
  251. resethookcount(L);
  252. L->openupval = NULL;
  253. L->status = LUA_OK;
  254. L->errfunc = 0;
  255. }
  256. static void close_state (lua_State *L) {
  257. global_State *g = G(L);
  258. luaF_close(L, L->stack, CLOSEPROTECT); /* close all upvalues */
  259. luaC_freeallobjects(L); /* collect all objects */
  260. if (ttisnil(&g->nilvalue)) /* closing a fully built state? */
  261. luai_userstateclose(L);
  262. luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
  263. freestack(L);
  264. lua_assert(gettotalbytes(g) == sizeof(LG));
  265. (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */
  266. }
  267. LUA_API lua_State *lua_newthread (lua_State *L) {
  268. global_State *g = G(L);
  269. lua_State *L1;
  270. lua_lock(L);
  271. luaC_checkGC(L);
  272. /* create new thread */
  273. L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l;
  274. L1->marked = luaC_white(g);
  275. L1->tt = LUA_TTHREAD;
  276. /* link it on list 'allgc' */
  277. L1->next = g->allgc;
  278. g->allgc = obj2gco(L1);
  279. /* anchor it on L stack */
  280. setthvalue2s(L, L->top, L1);
  281. api_incr_top(L);
  282. preinit_thread(L1, g);
  283. L1->hookmask = L->hookmask;
  284. L1->basehookcount = L->basehookcount;
  285. L1->hook = L->hook;
  286. resethookcount(L1);
  287. /* initialize L1 extra space */
  288. memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread),
  289. LUA_EXTRASPACE);
  290. luai_userstatethread(L, L1);
  291. stack_init(L1, L); /* init stack */
  292. lua_unlock(L);
  293. return L1;
  294. }
  295. void luaE_freethread (lua_State *L, lua_State *L1) {
  296. LX *l = fromstate(L1);
  297. luaF_close(L1, L1->stack, NOCLOSINGMETH); /* close all upvalues */
  298. lua_assert(L1->openupval == NULL);
  299. luai_userstatefree(L, L1);
  300. freestack(L1);
  301. luaM_free(L, l);
  302. }
  303. int lua_resetthread (lua_State *L) {
  304. CallInfo *ci;
  305. int status;
  306. lua_lock(L);
  307. ci = &L->base_ci;
  308. status = luaF_close(L, L->stack, CLOSEPROTECT);
  309. setnilvalue(s2v(L->stack)); /* 'function' entry for basic 'ci' */
  310. if (status != CLOSEPROTECT) /* real errors? */
  311. luaD_seterrorobj(L, status, L->stack + 1);
  312. else {
  313. status = LUA_OK;
  314. L->top = L->stack + 1;
  315. }
  316. ci->callstatus = CIST_C;
  317. ci->func = L->stack;
  318. ci->top = L->top + LUA_MINSTACK;
  319. L->ci = ci;
  320. L->status = status;
  321. lua_unlock(L);
  322. return status;
  323. }
  324. LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
  325. int i;
  326. lua_State *L;
  327. global_State *g;
  328. LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));
  329. if (l == NULL) return NULL;
  330. L = &l->l.l;
  331. g = &l->g;
  332. L->tt = LUA_TTHREAD;
  333. g->currentwhite = bitmask(WHITE0BIT);
  334. L->marked = luaC_white(g);
  335. preinit_thread(L, g);
  336. g->allgc = obj2gco(L); /* by now, only object is the main thread */
  337. L->next = NULL;
  338. g->Cstacklimit = L->nCcalls = LUAI_MAXCSTACK + CSTACKERR;
  339. g->frealloc = f;
  340. g->ud = ud;
  341. g->warnf = NULL;
  342. g->ud_warn = NULL;
  343. g->mainthread = L;
  344. g->seed = luai_makeseed(L);
  345. g->gcrunning = 0; /* no GC while building state */
  346. g->strt.size = g->strt.nuse = 0;
  347. g->strt.hash = NULL;
  348. setnilvalue(&g->l_registry);
  349. g->panic = NULL;
  350. g->gcstate = GCSpause;
  351. g->gckind = KGC_INC;
  352. g->gcemergency = 0;
  353. g->finobj = g->tobefnz = g->fixedgc = NULL;
  354. g->survival = g->old = g->reallyold = NULL;
  355. g->finobjsur = g->finobjold = g->finobjrold = NULL;
  356. g->sweepgc = NULL;
  357. g->gray = g->grayagain = NULL;
  358. g->weak = g->ephemeron = g->allweak = NULL;
  359. g->twups = NULL;
  360. g->totalbytes = sizeof(LG);
  361. g->GCdebt = 0;
  362. g->lastatomic = 0;
  363. setivalue(&g->nilvalue, 0); /* to signal that state is not yet built */
  364. setgcparam(g->gcpause, LUAI_GCPAUSE);
  365. setgcparam(g->gcstepmul, LUAI_GCMUL);
  366. g->gcstepsize = LUAI_GCSTEPSIZE;
  367. setgcparam(g->genmajormul, LUAI_GENMAJORMUL);
  368. g->genminormul = LUAI_GENMINORMUL;
  369. for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
  370. if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
  371. /* memory allocation error: free partial state */
  372. close_state(L);
  373. L = NULL;
  374. }
  375. return L;
  376. }
  377. LUA_API void lua_close (lua_State *L) {
  378. L = G(L)->mainthread; /* only the main thread can be closed */
  379. lua_lock(L);
  380. close_state(L);
  381. }
  382. void luaE_warning (lua_State *L, const char *msg, int tocont) {
  383. lua_WarnFunction wf = G(L)->warnf;
  384. if (wf != NULL)
  385. wf(G(L)->ud_warn, msg, tocont);
  386. }
  387. /*
  388. ** Generate a warning from an error message
  389. */
  390. void luaE_warnerror (lua_State *L, const char *where) {
  391. TValue *errobj = s2v(L->top - 1); /* error object */
  392. const char *msg = (ttisstring(errobj))
  393. ? svalue(errobj)
  394. : "error object is not a string";
  395. /* produce warning "error in %s (%s)" (where, msg) */
  396. luaE_warning(L, "error in ", 1);
  397. luaE_warning(L, where, 1);
  398. luaE_warning(L, " (", 1);
  399. luaE_warning(L, msg, 1);
  400. luaE_warning(L, ")", 0);
  401. }