1 /*
2 ** $Id: ldo.c $
3 ** Stack and Call structure of Lua
4 ** See Copyright Notice in lua.h
5 */
6
7 #define ldo_c
8 #define LUA_CORE
9
10 #include "lprefix.h"
11
12
13 #include <setjmp.h>
14 #include <stdlib.h>
15 #include <string.h>
16
17 #include "lua.h"
18
19 #include "lapi.h"
20 #include "ldebug.h"
21 #include "ldo.h"
22 #include "lfunc.h"
23 #include "lgc.h"
24 #include "lmem.h"
25 #include "lobject.h"
26 #include "lopcodes.h"
27 #include "lparser.h"
28 #include "lstate.h"
29 #include "lstring.h"
30 #include "ltable.h"
31 #include "ltm.h"
32 #include "lundump.h"
33 #include "lvm.h"
34 #include "lzio.h"
35
36
37
38 #define errorstatus(s) ((s) > LUA_YIELD)
39
40
41 /*
42 ** {======================================================
43 ** Error-recovery functions
44 ** =======================================================
45 */
46
47 /*
48 ** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
49 ** default, Lua handles errors with exceptions when compiling as
50 ** C++ code, with _longjmp/_setjmp when asked to use them, and with
51 ** longjmp/setjmp otherwise.
52 */
53 #if !defined(LUAI_THROW) /* { */
54
55 #if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
56
57 /* C++ exceptions */
58 #define LUAI_THROW(L,c) throw(c)
59 #define LUAI_TRY(L,c,a) \
60 try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
61 #define luai_jmpbuf int /* dummy variable */
62
63 #elif defined(LUA_USE_POSIX) /* }{ */
64
65 /* in POSIX, try _longjmp/_setjmp (more efficient) */
66 #define LUAI_THROW(L,c) _longjmp((c)->b, 1)
67 #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
68 #define luai_jmpbuf jmp_buf
69
70 #else /* }{ */
71
72 /* ISO C handling with long jumps */
73 #define LUAI_THROW(L,c) longjmp((c)->b, 1)
74 #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
75 #define luai_jmpbuf jmp_buf
76
77 #endif /* } */
78
79 #endif /* } */
80
81
82
83 /* chain list of long jump buffers */
84 struct lua_longjmp {
85 struct lua_longjmp *previous;
86 luai_jmpbuf b;
87 volatile int status; /* error code */
88 };
89
90
luaD_seterrorobj(lua_State * L,int errcode,StkId oldtop)91 void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
92 switch (errcode) {
93 case LUA_ERRMEM: { /* memory error? */
94 setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
95 break;
96 }
97 case LUA_ERRERR: {
98 setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
99 break;
100 }
101 case LUA_OK: { /* special case only for closing upvalues */
102 setnilvalue(s2v(oldtop)); /* no error message */
103 break;
104 }
105 default: {
106 lua_assert(errorstatus(errcode)); /* real error */
107 setobjs2s(L, oldtop, L->top.p - 1); /* error message on current top */
108 break;
109 }
110 }
111 L->top.p = oldtop + 1;
112 }
113
114
luaD_throw(lua_State * L,int errcode)115 l_noret luaD_throw (lua_State *L, int errcode) {
116 if (L->errorJmp) { /* thread has an error handler? */
117 L->errorJmp->status = errcode; /* set status */
118 LUAI_THROW(L, L->errorJmp); /* jump to it */
119 }
120 else { /* thread has no error handler */
121 global_State *g = G(L);
122 errcode = luaE_resetthread(L, errcode); /* close all upvalues */
123 if (g->mainthread->errorJmp) { /* main thread has a handler? */
124 setobjs2s(L, g->mainthread->top.p++, L->top.p - 1); /* copy error obj. */
125 luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
126 }
127 else { /* no handler at all; abort */
128 if (g->panic) { /* panic function? */
129 lua_unlock(L);
130 g->panic(L); /* call panic function (last chance to jump out) */
131 }
132 abort();
133 }
134 }
135 }
136
137
luaD_rawrunprotected(lua_State * L,Pfunc f,void * ud)138 int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
139 l_uint32 oldnCcalls = L->nCcalls;
140 struct lua_longjmp lj;
141 lj.status = LUA_OK;
142 lj.previous = L->errorJmp; /* chain new error handler */
143 L->errorJmp = &lj;
144 LUAI_TRY(L, &lj,
145 (*f)(L, ud);
146 );
147 L->errorJmp = lj.previous; /* restore old error handler */
148 L->nCcalls = oldnCcalls;
149 return lj.status;
150 }
151
152 /* }====================================================== */
153
154
155 /*
156 ** {==================================================================
157 ** Stack reallocation
158 ** ===================================================================
159 */
160
161
162 /*
163 ** Change all pointers to the stack into offsets.
164 */
relstack(lua_State * L)165 static void relstack (lua_State *L) {
166 CallInfo *ci;
167 UpVal *up;
168 L->top.offset = savestack(L, L->top.p);
169 L->tbclist.offset = savestack(L, L->tbclist.p);
170 for (up = L->openupval; up != NULL; up = up->u.open.next)
171 up->v.offset = savestack(L, uplevel(up));
172 for (ci = L->ci; ci != NULL; ci = ci->previous) {
173 ci->top.offset = savestack(L, ci->top.p);
174 ci->func.offset = savestack(L, ci->func.p);
175 }
176 }
177
178
179 /*
180 ** Change back all offsets into pointers.
181 */
correctstack(lua_State * L)182 static void correctstack (lua_State *L) {
183 CallInfo *ci;
184 UpVal *up;
185 L->top.p = restorestack(L, L->top.offset);
186 L->tbclist.p = restorestack(L, L->tbclist.offset);
187 for (up = L->openupval; up != NULL; up = up->u.open.next)
188 up->v.p = s2v(restorestack(L, up->v.offset));
189 for (ci = L->ci; ci != NULL; ci = ci->previous) {
190 ci->top.p = restorestack(L, ci->top.offset);
191 ci->func.p = restorestack(L, ci->func.offset);
192 if (isLua(ci))
193 ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
194 }
195 }
196
197
198 /* some space for error handling */
199 #define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
200
201 /*
202 ** Reallocate the stack to a new size, correcting all pointers into it.
203 ** In ISO C, any pointer use after the pointer has been deallocated is
204 ** undefined behavior. So, before the reallocation, all pointers are
205 ** changed to offsets, and after the reallocation they are changed back
206 ** to pointers. As during the reallocation the pointers are invalid, the
207 ** reallocation cannot run emergency collections.
208 **
209 ** In case of allocation error, raise an error or return false according
210 ** to 'raiseerror'.
211 */
luaD_reallocstack(lua_State * L,int newsize,int raiseerror)212 int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
213 int oldsize = stacksize(L);
214 int i;
215 StkId newstack;
216 int oldgcstop = G(L)->gcstopem;
217 lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
218 relstack(L); /* change pointers to offsets */
219 G(L)->gcstopem = 1; /* stop emergency collection */
220 newstack = luaM_reallocvector(L, L->stack.p, oldsize + EXTRA_STACK,
221 newsize + EXTRA_STACK, StackValue);
222 G(L)->gcstopem = oldgcstop; /* restore emergency collection */
223 if (l_unlikely(newstack == NULL)) { /* reallocation failed? */
224 correctstack(L); /* change offsets back to pointers */
225 if (raiseerror)
226 luaM_error(L);
227 else return 0; /* do not raise an error */
228 }
229 L->stack.p = newstack;
230 correctstack(L); /* change offsets back to pointers */
231 L->stack_last.p = L->stack.p + newsize;
232 for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)
233 setnilvalue(s2v(newstack + i)); /* erase new segment */
234 return 1;
235 }
236
237
238 /*
239 ** Try to grow the stack by at least 'n' elements. When 'raiseerror'
240 ** is true, raises any error; otherwise, return 0 in case of errors.
241 */
luaD_growstack(lua_State * L,int n,int raiseerror)242 int luaD_growstack (lua_State *L, int n, int raiseerror) {
243 int size = stacksize(L);
244 if (l_unlikely(size > LUAI_MAXSTACK)) {
245 /* if stack is larger than maximum, thread is already using the
246 extra space reserved for errors, that is, thread is handling
247 a stack error; cannot grow further than that. */
248 lua_assert(stacksize(L) == ERRORSTACKSIZE);
249 if (raiseerror)
250 luaD_throw(L, LUA_ERRERR); /* error inside message handler */
251 return 0; /* if not 'raiseerror', just signal it */
252 }
253 else if (n < LUAI_MAXSTACK) { /* avoids arithmetic overflows */
254 int newsize = 2 * size; /* tentative new size */
255 int needed = cast_int(L->top.p - L->stack.p) + n;
256 if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
257 newsize = LUAI_MAXSTACK;
258 if (newsize < needed) /* but must respect what was asked for */
259 newsize = needed;
260 if (l_likely(newsize <= LUAI_MAXSTACK))
261 return luaD_reallocstack(L, newsize, raiseerror);
262 }
263 /* else stack overflow */
264 /* add extra size to be able to handle the error message */
265 luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
266 if (raiseerror)
267 luaG_runerror(L, "stack overflow");
268 return 0;
269 }
270
271
272 /*
273 ** Compute how much of the stack is being used, by computing the
274 ** maximum top of all call frames in the stack and the current top.
275 */
stackinuse(lua_State * L)276 static int stackinuse (lua_State *L) {
277 CallInfo *ci;
278 int res;
279 StkId lim = L->top.p;
280 for (ci = L->ci; ci != NULL; ci = ci->previous) {
281 if (lim < ci->top.p) lim = ci->top.p;
282 }
283 lua_assert(lim <= L->stack_last.p + EXTRA_STACK);
284 res = cast_int(lim - L->stack.p) + 1; /* part of stack in use */
285 if (res < LUA_MINSTACK)
286 res = LUA_MINSTACK; /* ensure a minimum size */
287 return res;
288 }
289
290
291 /*
292 ** If stack size is more than 3 times the current use, reduce that size
293 ** to twice the current use. (So, the final stack size is at most 2/3 the
294 ** previous size, and half of its entries are empty.)
295 ** As a particular case, if stack was handling a stack overflow and now
296 ** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than
297 ** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
298 ** will be reduced to a "regular" size.
299 */
luaD_shrinkstack(lua_State * L)300 void luaD_shrinkstack (lua_State *L) {
301 int inuse = stackinuse(L);
302 int max = (inuse > LUAI_MAXSTACK / 3) ? LUAI_MAXSTACK : inuse * 3;
303 /* if thread is currently not handling a stack overflow and its
304 size is larger than maximum "reasonable" size, shrink it */
305 if (inuse <= LUAI_MAXSTACK && stacksize(L) > max) {
306 int nsize = (inuse > LUAI_MAXSTACK / 2) ? LUAI_MAXSTACK : inuse * 2;
307 luaD_reallocstack(L, nsize, 0); /* ok if that fails */
308 }
309 else /* don't change stack */
310 condmovestack(L,{},{}); /* (change only for debugging) */
311 luaE_shrinkCI(L); /* shrink CI list */
312 }
313
314
luaD_inctop(lua_State * L)315 void luaD_inctop (lua_State *L) {
316 luaD_checkstack(L, 1);
317 L->top.p++;
318 }
319
320 /* }================================================================== */
321
322
323 /*
324 ** Call a hook for the given event. Make sure there is a hook to be
325 ** called. (Both 'L->hook' and 'L->hookmask', which trigger this
326 ** function, can be changed asynchronously by signals.)
327 */
luaD_hook(lua_State * L,int event,int line,int ftransfer,int ntransfer)328 void luaD_hook (lua_State *L, int event, int line,
329 int ftransfer, int ntransfer) {
330 lua_Hook hook = L->hook;
331 if (hook && L->allowhook) { /* make sure there is a hook */
332 int mask = CIST_HOOKED;
333 CallInfo *ci = L->ci;
334 ptrdiff_t top = savestack(L, L->top.p); /* preserve original 'top' */
335 ptrdiff_t ci_top = savestack(L, ci->top.p); /* idem for 'ci->top' */
336 lua_Debug ar;
337 ar.event = event;
338 ar.currentline = line;
339 ar.i_ci = ci;
340 if (ntransfer != 0) {
341 mask |= CIST_TRAN; /* 'ci' has transfer information */
342 ci->u2.transferinfo.ftransfer = ftransfer;
343 ci->u2.transferinfo.ntransfer = ntransfer;
344 }
345 if (isLua(ci) && L->top.p < ci->top.p)
346 L->top.p = ci->top.p; /* protect entire activation register */
347 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
348 if (ci->top.p < L->top.p + LUA_MINSTACK)
349 ci->top.p = L->top.p + LUA_MINSTACK;
350 L->allowhook = 0; /* cannot call hooks inside a hook */
351 ci->callstatus |= mask;
352 lua_unlock(L);
353 (*hook)(L, &ar);
354 lua_lock(L);
355 lua_assert(!L->allowhook);
356 L->allowhook = 1;
357 ci->top.p = restorestack(L, ci_top);
358 L->top.p = restorestack(L, top);
359 ci->callstatus &= ~mask;
360 }
361 }
362
363
364 /*
365 ** Executes a call hook for Lua functions. This function is called
366 ** whenever 'hookmask' is not zero, so it checks whether call hooks are
367 ** active.
368 */
luaD_hookcall(lua_State * L,CallInfo * ci)369 void luaD_hookcall (lua_State *L, CallInfo *ci) {
370 L->oldpc = 0; /* set 'oldpc' for new function */
371 if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */
372 int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
373 : LUA_HOOKCALL;
374 Proto *p = ci_func(ci)->p;
375 ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
376 luaD_hook(L, event, -1, 1, p->numparams);
377 ci->u.l.savedpc--; /* correct 'pc' */
378 }
379 }
380
381
382 /*
383 ** Executes a return hook for Lua and C functions and sets/corrects
384 ** 'oldpc'. (Note that this correction is needed by the line hook, so it
385 ** is done even when return hooks are off.)
386 */
rethook(lua_State * L,CallInfo * ci,int nres)387 static void rethook (lua_State *L, CallInfo *ci, int nres) {
388 if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
389 StkId firstres = L->top.p - nres; /* index of first result */
390 int delta = 0; /* correction for vararg functions */
391 int ftransfer;
392 if (isLua(ci)) {
393 Proto *p = ci_func(ci)->p;
394 if (p->is_vararg)
395 delta = ci->u.l.nextraargs + p->numparams + 1;
396 }
397 ci->func.p += delta; /* if vararg, back to virtual 'func' */
398 ftransfer = cast(unsigned short, firstres - ci->func.p);
399 luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
400 ci->func.p -= delta;
401 }
402 if (isLua(ci = ci->previous))
403 L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */
404 }
405
406
407 /*
408 ** Check whether 'func' has a '__call' metafield. If so, put it in the
409 ** stack, below original 'func', so that 'luaD_precall' can call it. Raise
410 ** an error if there is no '__call' metafield.
411 */
luaD_tryfuncTM(lua_State * L,StkId func)412 StkId luaD_tryfuncTM (lua_State *L, StkId func) {
413 const TValue *tm;
414 StkId p;
415 checkstackGCp(L, 1, func); /* space for metamethod */
416 tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); /* (after previous GC) */
417 if (l_unlikely(ttisnil(tm)))
418 luaG_callerror(L, s2v(func)); /* nothing to call */
419 for (p = L->top.p; p > func; p--) /* open space for metamethod */
420 setobjs2s(L, p, p-1);
421 L->top.p++; /* stack space pre-allocated by the caller */
422 setobj2s(L, func, tm); /* metamethod is the new function to be called */
423 return func;
424 }
425
426
427 /*
428 ** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
429 ** Handle most typical cases (zero results for commands, one result for
430 ** expressions, multiple results for tail calls/single parameters)
431 ** separated.
432 */
moveresults(lua_State * L,StkId res,int nres,int wanted)433 l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) {
434 StkId firstresult;
435 int i;
436 switch (wanted) { /* handle typical cases separately */
437 case 0: /* no values needed */
438 L->top.p = res;
439 return;
440 case 1: /* one value needed */
441 if (nres == 0) /* no results? */
442 setnilvalue(s2v(res)); /* adjust with nil */
443 else /* at least one result */
444 setobjs2s(L, res, L->top.p - nres); /* move it to proper place */
445 L->top.p = res + 1;
446 return;
447 case LUA_MULTRET:
448 wanted = nres; /* we want all results */
449 break;
450 default: /* two/more results and/or to-be-closed variables */
451 if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
452 L->ci->callstatus |= CIST_CLSRET; /* in case of yields */
453 L->ci->u2.nres = nres;
454 res = luaF_close(L, res, CLOSEKTOP, 1);
455 L->ci->callstatus &= ~CIST_CLSRET;
456 if (L->hookmask) { /* if needed, call hook after '__close's */
457 ptrdiff_t savedres = savestack(L, res);
458 rethook(L, L->ci, nres);
459 res = restorestack(L, savedres); /* hook can move stack */
460 }
461 wanted = decodeNresults(wanted);
462 if (wanted == LUA_MULTRET)
463 wanted = nres; /* we want all results */
464 }
465 break;
466 }
467 /* generic case */
468 firstresult = L->top.p - nres; /* index of first result */
469 if (nres > wanted) /* extra results? */
470 nres = wanted; /* don't need them */
471 for (i = 0; i < nres; i++) /* move all results to correct place */
472 setobjs2s(L, res + i, firstresult + i);
473 for (; i < wanted; i++) /* complete wanted number of results */
474 setnilvalue(s2v(res + i));
475 L->top.p = res + wanted; /* top points after the last result */
476 }
477
478
479 /*
480 ** Finishes a function call: calls hook if necessary, moves current
481 ** number of results to proper place, and returns to previous call
482 ** info. If function has to close variables, hook must be called after
483 ** that.
484 */
luaD_poscall(lua_State * L,CallInfo * ci,int nres)485 void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
486 int wanted = ci->nresults;
487 if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted)))
488 rethook(L, ci, nres);
489 /* move results to proper place */
490 moveresults(L, ci->func.p, nres, wanted);
491 /* function cannot be in any of these cases when returning */
492 lua_assert(!(ci->callstatus &
493 (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET)));
494 L->ci = ci->previous; /* back to caller (after closing variables) */
495 }
496
497
498
499 #define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
500
501
prepCallInfo(lua_State * L,StkId func,int nret,int mask,StkId top)502 l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret,
503 int mask, StkId top) {
504 CallInfo *ci = L->ci = next_ci(L); /* new frame */
505 ci->func.p = func;
506 ci->nresults = nret;
507 ci->callstatus = mask;
508 ci->top.p = top;
509 return ci;
510 }
511
512
513 /*
514 ** precall for C functions
515 */
precallC(lua_State * L,StkId func,int nresults,lua_CFunction f)516 l_sinline int precallC (lua_State *L, StkId func, int nresults,
517 lua_CFunction f) {
518 int n; /* number of returns */
519 CallInfo *ci;
520 checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
521 L->ci = ci = prepCallInfo(L, func, nresults, CIST_C,
522 L->top.p + LUA_MINSTACK);
523 lua_assert(ci->top.p <= L->stack_last.p);
524 if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
525 int narg = cast_int(L->top.p - func) - 1;
526 luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
527 }
528 lua_unlock(L);
529 n = (*f)(L); /* do the actual call */
530 lua_lock(L);
531 api_checknelems(L, n);
532 luaD_poscall(L, ci, n);
533 return n;
534 }
535
536
537 /*
538 ** Prepare a function for a tail call, building its call info on top
539 ** of the current call info. 'narg1' is the number of arguments plus 1
540 ** (so that it includes the function itself). Return the number of
541 ** results, if it was a C function, or -1 for a Lua function.
542 */
luaD_pretailcall(lua_State * L,CallInfo * ci,StkId func,int narg1,int delta)543 int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
544 int narg1, int delta) {
545 retry:
546 switch (ttypetag(s2v(func))) {
547 case LUA_VCCL: /* C closure */
548 return precallC(L, func, LUA_MULTRET, clCvalue(s2v(func))->f);
549 case LUA_VLCF: /* light C function */
550 return precallC(L, func, LUA_MULTRET, fvalue(s2v(func)));
551 case LUA_VLCL: { /* Lua function */
552 Proto *p = clLvalue(s2v(func))->p;
553 int fsize = p->maxstacksize; /* frame size */
554 int nfixparams = p->numparams;
555 int i;
556 checkstackGCp(L, fsize - delta, func);
557 ci->func.p -= delta; /* restore 'func' (if vararg) */
558 for (i = 0; i < narg1; i++) /* move down function and arguments */
559 setobjs2s(L, ci->func.p + i, func + i);
560 func = ci->func.p; /* moved-down function */
561 for (; narg1 <= nfixparams; narg1++)
562 setnilvalue(s2v(func + narg1)); /* complete missing arguments */
563 ci->top.p = func + 1 + fsize; /* top for new function */
564 lua_assert(ci->top.p <= L->stack_last.p);
565 ci->u.l.savedpc = p->code; /* starting point */
566 ci->callstatus |= CIST_TAIL;
567 L->top.p = func + narg1; /* set top */
568 return -1;
569 }
570 default: { /* not a function */
571 func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
572 /* return luaD_pretailcall(L, ci, func, narg1 + 1, delta); */
573 narg1++;
574 goto retry; /* try again */
575 }
576 }
577 }
578
579
580 /*
581 ** Prepares the call to a function (C or Lua). For C functions, also do
582 ** the call. The function to be called is at '*func'. The arguments
583 ** are on the stack, right after the function. Returns the CallInfo
584 ** to be executed, if it was a Lua function. Otherwise (a C function)
585 ** returns NULL, with all the results on the stack, starting at the
586 ** original function position.
587 */
luaD_precall(lua_State * L,StkId func,int nresults)588 CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
589 retry:
590 switch (ttypetag(s2v(func))) {
591 case LUA_VCCL: /* C closure */
592 precallC(L, func, nresults, clCvalue(s2v(func))->f);
593 return NULL;
594 case LUA_VLCF: /* light C function */
595 precallC(L, func, nresults, fvalue(s2v(func)));
596 return NULL;
597 case LUA_VLCL: { /* Lua function */
598 CallInfo *ci;
599 Proto *p = clLvalue(s2v(func))->p;
600 int narg = cast_int(L->top.p - func) - 1; /* number of real arguments */
601 int nfixparams = p->numparams;
602 int fsize = p->maxstacksize; /* frame size */
603 checkstackGCp(L, fsize, func);
604 L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize);
605 ci->u.l.savedpc = p->code; /* starting point */
606 for (; narg < nfixparams; narg++)
607 setnilvalue(s2v(L->top.p++)); /* complete missing arguments */
608 lua_assert(ci->top.p <= L->stack_last.p);
609 return ci;
610 }
611 default: { /* not a function */
612 func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
613 /* return luaD_precall(L, func, nresults); */
614 goto retry; /* try again with metamethod */
615 }
616 }
617 }
618
619
620 /*
621 ** Call a function (C or Lua) through C. 'inc' can be 1 (increment
622 ** number of recursive invocations in the C stack) or nyci (the same
623 ** plus increment number of non-yieldable calls).
624 ** This function can be called with some use of EXTRA_STACK, so it should
625 ** check the stack before doing anything else. 'luaD_precall' already
626 ** does that.
627 */
ccall(lua_State * L,StkId func,int nResults,l_uint32 inc)628 l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {
629 CallInfo *ci;
630 L->nCcalls += inc;
631 if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {
632 checkstackp(L, 0, func); /* free any use of EXTRA_STACK */
633 luaE_checkcstack(L);
634 }
635 if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
636 ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */
637 luaV_execute(L, ci); /* call it */
638 }
639 L->nCcalls -= inc;
640 }
641
642
643 /*
644 ** External interface for 'ccall'
645 */
luaD_call(lua_State * L,StkId func,int nResults)646 void luaD_call (lua_State *L, StkId func, int nResults) {
647 ccall(L, func, nResults, 1);
648 }
649
650
651 /*
652 ** Similar to 'luaD_call', but does not allow yields during the call.
653 */
luaD_callnoyield(lua_State * L,StkId func,int nResults)654 void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
655 ccall(L, func, nResults, nyci);
656 }
657
658
659 /*
660 ** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
661 ** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
662 ** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
663 ** If a '__close' method yields here, eventually control will be back
664 ** to 'finishCcall' (when that '__close' method finally returns) and
665 ** 'finishpcallk' will run again and close any still pending '__close'
666 ** methods. Similarly, if a '__close' method errs, 'precover' calls
667 ** 'unroll' which calls ''finishCcall' and we are back here again, to
668 ** close any pending '__close' methods.
669 ** Note that, up to the call to 'luaF_close', the corresponding
670 ** 'CallInfo' is not modified, so that this repeated run works like the
671 ** first one (except that it has at least one less '__close' to do). In
672 ** particular, field CIST_RECST preserves the error status across these
673 ** multiple runs, changing only if there is a new error.
674 */
finishpcallk(lua_State * L,CallInfo * ci)675 static int finishpcallk (lua_State *L, CallInfo *ci) {
676 int status = getcistrecst(ci); /* get original status */
677 if (l_likely(status == LUA_OK)) /* no error? */
678 status = LUA_YIELD; /* was interrupted by an yield */
679 else { /* error */
680 StkId func = restorestack(L, ci->u2.funcidx);
681 L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */
682 func = luaF_close(L, func, status, 1); /* can yield or raise an error */
683 luaD_seterrorobj(L, status, func);
684 luaD_shrinkstack(L); /* restore stack size in case of overflow */
685 setcistrecst(ci, LUA_OK); /* clear original status */
686 }
687 ci->callstatus &= ~CIST_YPCALL;
688 L->errfunc = ci->u.c.old_errfunc;
689 /* if it is here, there were errors or yields; unlike 'lua_pcallk',
690 do not change status */
691 return status;
692 }
693
694
695 /*
696 ** Completes the execution of a C function interrupted by an yield.
697 ** The interruption must have happened while the function was either
698 ** closing its tbc variables in 'moveresults' or executing
699 ** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
700 ** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
701 ** finishes the interrupted execution of 'lua_pcallk'. After that, it
702 ** calls the continuation of the interrupted function and finally it
703 ** completes the job of the 'luaD_call' that called the function. In
704 ** the call to 'adjustresults', we do not know the number of results
705 ** of the function called by 'lua_callk'/'lua_pcallk', so we are
706 ** conservative and use LUA_MULTRET (always adjust).
707 */
finishCcall(lua_State * L,CallInfo * ci)708 static void finishCcall (lua_State *L, CallInfo *ci) {
709 int n; /* actual number of results from C function */
710 if (ci->callstatus & CIST_CLSRET) { /* was returning? */
711 lua_assert(hastocloseCfunc(ci->nresults));
712 n = ci->u2.nres; /* just redo 'luaD_poscall' */
713 /* don't need to reset CIST_CLSRET, as it will be set again anyway */
714 }
715 else {
716 int status = LUA_YIELD; /* default if there were no errors */
717 /* must have a continuation and must be able to call it */
718 lua_assert(ci->u.c.k != NULL && yieldable(L));
719 if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
720 status = finishpcallk(L, ci); /* finish it */
721 adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
722 lua_unlock(L);
723 n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */
724 lua_lock(L);
725 api_checknelems(L, n);
726 }
727 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
728 }
729
730
731 /*
732 ** Executes "full continuation" (everything in the stack) of a
733 ** previously interrupted coroutine until the stack is empty (or another
734 ** interruption long-jumps out of the loop).
735 */
unroll(lua_State * L,void * ud)736 static void unroll (lua_State *L, void *ud) {
737 CallInfo *ci;
738 UNUSED(ud);
739 while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
740 if (!isLua(ci)) /* C function? */
741 finishCcall(L, ci); /* complete its execution */
742 else { /* Lua function */
743 luaV_finishOp(L); /* finish interrupted instruction */
744 luaV_execute(L, ci); /* execute down to higher C 'boundary' */
745 }
746 }
747 }
748
749
750 /*
751 ** Try to find a suspended protected call (a "recover point") for the
752 ** given thread.
753 */
findpcall(lua_State * L)754 static CallInfo *findpcall (lua_State *L) {
755 CallInfo *ci;
756 for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
757 if (ci->callstatus & CIST_YPCALL)
758 return ci;
759 }
760 return NULL; /* no pending pcall */
761 }
762
763
764 /*
765 ** Signal an error in the call to 'lua_resume', not in the execution
766 ** of the coroutine itself. (Such errors should not be handled by any
767 ** coroutine error handler and should not kill the coroutine.)
768 */
resume_error(lua_State * L,const char * msg,int narg)769 static int resume_error (lua_State *L, const char *msg, int narg) {
770 L->top.p -= narg; /* remove args from the stack */
771 setsvalue2s(L, L->top.p, luaS_new(L, msg)); /* push error message */
772 api_incr_top(L);
773 lua_unlock(L);
774 return LUA_ERRRUN;
775 }
776
777
778 /*
779 ** Do the work for 'lua_resume' in protected mode. Most of the work
780 ** depends on the status of the coroutine: initial state, suspended
781 ** inside a hook, or regularly suspended (optionally with a continuation
782 ** function), plus erroneous cases: non-suspended coroutine or dead
783 ** coroutine.
784 */
resume(lua_State * L,void * ud)785 static void resume (lua_State *L, void *ud) {
786 int n = *(cast(int*, ud)); /* number of arguments */
787 StkId firstArg = L->top.p - n; /* first argument */
788 CallInfo *ci = L->ci;
789 if (L->status == LUA_OK) /* starting a coroutine? */
790 ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */
791 else { /* resuming from previous yield */
792 lua_assert(L->status == LUA_YIELD);
793 L->status = LUA_OK; /* mark that it is running (again) */
794 if (isLua(ci)) { /* yielded inside a hook? */
795 L->top.p = firstArg; /* discard arguments */
796 luaV_execute(L, ci); /* just continue running Lua code */
797 }
798 else { /* 'common' yield */
799 if (ci->u.c.k != NULL) { /* does it have a continuation function? */
800 lua_unlock(L);
801 n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
802 lua_lock(L);
803 api_checknelems(L, n);
804 }
805 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
806 }
807 unroll(L, NULL); /* run continuation */
808 }
809 }
810
811
812 /*
813 ** Unrolls a coroutine in protected mode while there are recoverable
814 ** errors, that is, errors inside a protected call. (Any error
815 ** interrupts 'unroll', and this loop protects it again so it can
816 ** continue.) Stops with a normal end (status == LUA_OK), an yield
817 ** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
818 ** find a recover point).
819 */
precover(lua_State * L,int status)820 static int precover (lua_State *L, int status) {
821 CallInfo *ci;
822 while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
823 L->ci = ci; /* go down to recovery functions */
824 setcistrecst(ci, status); /* status to finish 'pcall' */
825 status = luaD_rawrunprotected(L, unroll, NULL);
826 }
827 return status;
828 }
829
830
lua_resume(lua_State * L,lua_State * from,int nargs,int * nresults)831 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
832 int *nresults) {
833 int status;
834 lua_lock(L);
835 if (L->status == LUA_OK) { /* may be starting a coroutine */
836 if (L->ci != &L->base_ci) /* not in base level? */
837 return resume_error(L, "cannot resume non-suspended coroutine", nargs);
838 else if (L->top.p - (L->ci->func.p + 1) == nargs) /* no function? */
839 return resume_error(L, "cannot resume dead coroutine", nargs);
840 }
841 else if (L->status != LUA_YIELD) /* ended with errors? */
842 return resume_error(L, "cannot resume dead coroutine", nargs);
843 L->nCcalls = (from) ? getCcalls(from) : 0;
844 if (getCcalls(L) >= LUAI_MAXCCALLS)
845 return resume_error(L, "C stack overflow", nargs);
846 L->nCcalls++;
847 luai_userstateresume(L, nargs);
848 api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
849 status = luaD_rawrunprotected(L, resume, &nargs);
850 /* continue running after recoverable errors */
851 status = precover(L, status);
852 if (l_likely(!errorstatus(status)))
853 lua_assert(status == L->status); /* normal end or yield */
854 else { /* unrecoverable error */
855 L->status = cast_byte(status); /* mark thread as 'dead' */
856 luaD_seterrorobj(L, status, L->top.p); /* push error message */
857 L->ci->top.p = L->top.p;
858 }
859 *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
860 : cast_int(L->top.p - (L->ci->func.p + 1));
861 lua_unlock(L);
862 return status;
863 }
864
865
lua_isyieldable(lua_State * L)866 LUA_API int lua_isyieldable (lua_State *L) {
867 return yieldable(L);
868 }
869
870
lua_yieldk(lua_State * L,int nresults,lua_KContext ctx,lua_KFunction k)871 LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
872 lua_KFunction k) {
873 CallInfo *ci;
874 luai_userstateyield(L, nresults);
875 lua_lock(L);
876 ci = L->ci;
877 api_checknelems(L, nresults);
878 if (l_unlikely(!yieldable(L))) {
879 if (L != G(L)->mainthread)
880 luaG_runerror(L, "attempt to yield across a C-call boundary");
881 else
882 luaG_runerror(L, "attempt to yield from outside a coroutine");
883 }
884 L->status = LUA_YIELD;
885 ci->u2.nyield = nresults; /* save number of results */
886 if (isLua(ci)) { /* inside a hook? */
887 lua_assert(!isLuacode(ci));
888 api_check(L, nresults == 0, "hooks cannot yield values");
889 api_check(L, k == NULL, "hooks cannot continue after yielding");
890 }
891 else {
892 if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
893 ci->u.c.ctx = ctx; /* save context */
894 luaD_throw(L, LUA_YIELD);
895 }
896 lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
897 lua_unlock(L);
898 return 0; /* return to 'luaD_hook' */
899 }
900
901
902 /*
903 ** Auxiliary structure to call 'luaF_close' in protected mode.
904 */
905 struct CloseP {
906 StkId level;
907 int status;
908 };
909
910
911 /*
912 ** Auxiliary function to call 'luaF_close' in protected mode.
913 */
closepaux(lua_State * L,void * ud)914 static void closepaux (lua_State *L, void *ud) {
915 struct CloseP *pcl = cast(struct CloseP *, ud);
916 luaF_close(L, pcl->level, pcl->status, 0);
917 }
918
919
920 /*
921 ** Calls 'luaF_close' in protected mode. Return the original status
922 ** or, in case of errors, the new status.
923 */
luaD_closeprotected(lua_State * L,ptrdiff_t level,int status)924 int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {
925 CallInfo *old_ci = L->ci;
926 lu_byte old_allowhooks = L->allowhook;
927 for (;;) { /* keep closing upvalues until no more errors */
928 struct CloseP pcl;
929 pcl.level = restorestack(L, level); pcl.status = status;
930 status = luaD_rawrunprotected(L, &closepaux, &pcl);
931 if (l_likely(status == LUA_OK)) /* no more errors? */
932 return pcl.status;
933 else { /* an error occurred; restore saved state and repeat */
934 L->ci = old_ci;
935 L->allowhook = old_allowhooks;
936 }
937 }
938 }
939
940
941 /*
942 ** Call the C function 'func' in protected mode, restoring basic
943 ** thread information ('allowhook', etc.) and in particular
944 ** its stack level in case of errors.
945 */
luaD_pcall(lua_State * L,Pfunc func,void * u,ptrdiff_t old_top,ptrdiff_t ef)946 int luaD_pcall (lua_State *L, Pfunc func, void *u,
947 ptrdiff_t old_top, ptrdiff_t ef) {
948 int status;
949 CallInfo *old_ci = L->ci;
950 lu_byte old_allowhooks = L->allowhook;
951 ptrdiff_t old_errfunc = L->errfunc;
952 L->errfunc = ef;
953 status = luaD_rawrunprotected(L, func, u);
954 if (l_unlikely(status != LUA_OK)) { /* an error occurred? */
955 L->ci = old_ci;
956 L->allowhook = old_allowhooks;
957 status = luaD_closeprotected(L, old_top, status);
958 luaD_seterrorobj(L, status, restorestack(L, old_top));
959 luaD_shrinkstack(L); /* restore stack size in case of overflow */
960 }
961 L->errfunc = old_errfunc;
962 return status;
963 }
964
965
966
967 /*
968 ** Execute a protected parser.
969 */
970 struct SParser { /* data to 'f_parser' */
971 ZIO *z;
972 Mbuffer buff; /* dynamic structure used by the scanner */
973 Dyndata dyd; /* dynamic structures used by the parser */
974 const char *mode;
975 const char *name;
976 };
977
978
checkmode(lua_State * L,const char * mode,const char * x)979 static void checkmode (lua_State *L, const char *mode, const char *x) {
980 if (mode && strchr(mode, x[0]) == NULL) {
981 luaO_pushfstring(L,
982 "attempt to load a %s chunk (mode is '%s')", x, mode);
983 luaD_throw(L, LUA_ERRSYNTAX);
984 }
985 }
986
987
f_parser(lua_State * L,void * ud)988 static void f_parser (lua_State *L, void *ud) {
989 LClosure *cl;
990 struct SParser *p = cast(struct SParser *, ud);
991 int c = zgetc(p->z); /* read first character */
992 if (c == LUA_SIGNATURE[0]) {
993 checkmode(L, p->mode, "binary");
994 cl = luaU_undump(L, p->z, p->name);
995 }
996 else {
997 checkmode(L, p->mode, "text");
998 cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
999 }
1000 lua_assert(cl->nupvalues == cl->p->sizeupvalues);
1001 luaF_initupvals(L, cl);
1002 }
1003
1004
luaD_protectedparser(lua_State * L,ZIO * z,const char * name,const char * mode)1005 int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
1006 const char *mode) {
1007 struct SParser p;
1008 int status;
1009 incnny(L); /* cannot yield during parsing */
1010 p.z = z; p.name = name; p.mode = mode;
1011 p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
1012 p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
1013 p.dyd.label.arr = NULL; p.dyd.label.size = 0;
1014 luaZ_initbuffer(L, &p.buff);
1015 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);
1016 luaZ_freebuffer(L, &p.buff);
1017 luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
1018 luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
1019 luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
1020 decnny(L);
1021 return status;
1022 }
1023
1024
1025