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