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 CLOSEPROTECT: {
102 setnilvalue(s2v(oldtop)); /* no error message */
103 break;
104 }
105 default: {
106 setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
107 break;
108 }
109 }
110 L->top = oldtop + 1;
111 }
112
113
luaD_throw(lua_State * L,int errcode)114 l_noret luaD_throw (lua_State *L, int errcode) {
115 if (L->errorJmp) { /* thread has an error handler? */
116 L->errorJmp->status = errcode; /* set status */
117 LUAI_THROW(L, L->errorJmp); /* jump to it */
118 }
119 else { /* thread has no error handler */
120 global_State *g = G(L);
121 errcode = luaF_close(L, L->stack, errcode); /* close all upvalues */
122 L->status = cast_byte(errcode); /* mark it as dead */
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 luaD_seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */
130 if (L->ci->top < L->top)
131 L->ci->top = L->top; /* pushing msg. can break this invariant */
132 lua_unlock(L);
133 g->panic(L); /* call panic function (last chance to jump out) */
134 }
135 abort();
136 }
137 }
138 }
139
140
luaD_rawrunprotected(lua_State * L,Pfunc f,void * ud)141 int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
142 global_State *g = G(L);
143 l_uint32 oldnCcalls = g->Cstacklimit - (L->nCcalls + L->nci);
144 struct lua_longjmp lj;
145 lj.status = LUA_OK;
146 lj.previous = L->errorJmp; /* chain new error handler */
147 L->errorJmp = &lj;
148 LUAI_TRY(L, &lj,
149 (*f)(L, ud);
150 );
151 L->errorJmp = lj.previous; /* restore old error handler */
152 L->nCcalls = g->Cstacklimit - oldnCcalls - L->nci;
153 return lj.status;
154 }
155
156 /* }====================================================== */
157
158
159 /*
160 ** {==================================================================
161 ** Stack reallocation
162 ** ===================================================================
163 */
correctstack(lua_State * L,StkId oldstack,StkId newstack)164 static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
165 CallInfo *ci;
166 UpVal *up;
167 if (oldstack == newstack)
168 return; /* stack address did not change */
169 L->top = (L->top - oldstack) + newstack;
170 for (up = L->openupval; up != NULL; up = up->u.open.next)
171 up->v = s2v((uplevel(up) - oldstack) + newstack);
172 for (ci = L->ci; ci != NULL; ci = ci->previous) {
173 ci->top = (ci->top - oldstack) + newstack;
174 ci->func = (ci->func - oldstack) + newstack;
175 if (isLua(ci))
176 ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
177 }
178 }
179
180
181 /* some space for error handling */
182 #define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
183
184
luaD_reallocstack(lua_State * L,int newsize,int raiseerror)185 int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
186 int lim = L->stacksize;
187 StkId newstack = luaM_reallocvector(L, L->stack, lim, newsize, StackValue);
188 lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
189 lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
190 if (unlikely(newstack == NULL)) { /* reallocation failed? */
191 if (raiseerror)
192 luaM_error(L);
193 else return 0; /* do not raise an error */
194 }
195 for (; lim < newsize; lim++)
196 setnilvalue(s2v(newstack + lim)); /* erase new segment */
197 correctstack(L, L->stack, newstack);
198 L->stack = newstack;
199 L->stacksize = newsize;
200 L->stack_last = L->stack + newsize - EXTRA_STACK;
201 return 1;
202 }
203
204
205 /*
206 ** Try to grow the stack by at least 'n' elements. when 'raiseerror'
207 ** is true, raises any error; otherwise, return 0 in case of errors.
208 */
luaD_growstack(lua_State * L,int n,int raiseerror)209 int luaD_growstack (lua_State *L, int n, int raiseerror) {
210 int size = L->stacksize;
211 int newsize = 2 * size; /* tentative new size */
212 if (unlikely(size > LUAI_MAXSTACK)) { /* need more space after extra size? */
213 if (raiseerror)
214 luaD_throw(L, LUA_ERRERR); /* error inside message handler */
215 else return 0;
216 }
217 else {
218 int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
219 if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
220 newsize = LUAI_MAXSTACK;
221 if (newsize < needed) /* but must respect what was asked for */
222 newsize = needed;
223 if (unlikely(newsize > LUAI_MAXSTACK)) { /* stack overflow? */
224 /* add extra size to be able to handle the error message */
225 luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
226 if (raiseerror)
227 luaG_runerror(L, "stack overflow");
228 else return 0;
229 }
230 } /* else no errors */
231 return luaD_reallocstack(L, newsize, raiseerror);
232 }
233
234
stackinuse(lua_State * L)235 static int stackinuse (lua_State *L) {
236 CallInfo *ci;
237 StkId lim = L->top;
238 for (ci = L->ci; ci != NULL; ci = ci->previous) {
239 if (lim < ci->top) lim = ci->top;
240 }
241 lua_assert(lim <= L->stack_last);
242 return cast_int(lim - L->stack) + 1; /* part of stack in use */
243 }
244
245
luaD_shrinkstack(lua_State * L)246 void luaD_shrinkstack (lua_State *L) {
247 int inuse = stackinuse(L);
248 int goodsize = inuse + BASIC_STACK_SIZE;
249 if (goodsize > LUAI_MAXSTACK)
250 goodsize = LUAI_MAXSTACK; /* respect stack limit */
251 /* if thread is currently not handling a stack overflow and its
252 good size is smaller than current size, shrink its stack */
253 if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) && goodsize < L->stacksize)
254 luaD_reallocstack(L, goodsize, 0); /* ok if that fails */
255 else /* don't change stack */
256 condmovestack(L,{},{}); /* (change only for debugging) */
257 luaE_shrinkCI(L); /* shrink CI list */
258 }
259
260
luaD_inctop(lua_State * L)261 void luaD_inctop (lua_State *L) {
262 luaD_checkstack(L, 1);
263 L->top++;
264 }
265
266 /* }================================================================== */
267
268
269 /*
270 ** Call a hook for the given event. Make sure there is a hook to be
271 ** called. (Both 'L->hook' and 'L->hookmask', which trigger this
272 ** function, can be changed asynchronously by signals.)
273 */
luaD_hook(lua_State * L,int event,int line,int ftransfer,int ntransfer)274 void luaD_hook (lua_State *L, int event, int line,
275 int ftransfer, int ntransfer) {
276 lua_Hook hook = L->hook;
277 if (hook && L->allowhook) { /* make sure there is a hook */
278 int mask = CIST_HOOKED;
279 CallInfo *ci = L->ci;
280 ptrdiff_t top = savestack(L, L->top);
281 ptrdiff_t ci_top = savestack(L, ci->top);
282 lua_Debug ar;
283 ar.event = event;
284 ar.currentline = line;
285 ar.i_ci = ci;
286 if (ntransfer != 0) {
287 mask |= CIST_TRAN; /* 'ci' has transfer information */
288 ci->u2.transferinfo.ftransfer = ftransfer;
289 ci->u2.transferinfo.ntransfer = ntransfer;
290 }
291 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
292 if (L->top + LUA_MINSTACK > ci->top)
293 ci->top = L->top + LUA_MINSTACK;
294 L->allowhook = 0; /* cannot call hooks inside a hook */
295 ci->callstatus |= mask;
296 lua_unlock(L);
297 (*hook)(L, &ar);
298 lua_lock(L);
299 lua_assert(!L->allowhook);
300 L->allowhook = 1;
301 ci->top = restorestack(L, ci_top);
302 L->top = restorestack(L, top);
303 ci->callstatus &= ~mask;
304 }
305 }
306
307
308 /*
309 ** Executes a call hook for Lua functions. This function is called
310 ** whenever 'hookmask' is not zero, so it checks whether call hooks are
311 ** active.
312 */
luaD_hookcall(lua_State * L,CallInfo * ci)313 void luaD_hookcall (lua_State *L, CallInfo *ci) {
314 int hook = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL : LUA_HOOKCALL;
315 Proto *p;
316 if (!(L->hookmask & LUA_MASKCALL)) /* some other hook? */
317 return; /* don't call hook */
318 p = clLvalue(s2v(ci->func))->p;
319 L->top = ci->top; /* prepare top */
320 ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
321 luaD_hook(L, hook, -1, 1, p->numparams);
322 ci->u.l.savedpc--; /* correct 'pc' */
323 }
324
325
rethook(lua_State * L,CallInfo * ci,StkId firstres,int nres)326 static StkId rethook (lua_State *L, CallInfo *ci, StkId firstres, int nres) {
327 ptrdiff_t oldtop = savestack(L, L->top); /* hook may change top */
328 int delta = 0;
329 if (isLuacode(ci)) {
330 Proto *p = ci_func(ci)->p;
331 if (p->is_vararg)
332 delta = ci->u.l.nextraargs + p->numparams + 1;
333 if (L->top < ci->top)
334 L->top = ci->top; /* correct top to run hook */
335 }
336 if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
337 int ftransfer;
338 ci->func += delta; /* if vararg, back to virtual 'func' */
339 ftransfer = cast(unsigned short, firstres - ci->func);
340 luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
341 ci->func -= delta;
342 }
343 if (isLua(ci = ci->previous))
344 L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* update 'oldpc' */
345 return restorestack(L, oldtop);
346 }
347
348
349 /*
350 ** Check whether 'func' has a '__call' metafield. If so, put it in the
351 ** stack, below original 'func', so that 'luaD_call' can call it. Raise
352 ** an error if there is no '__call' metafield.
353 */
luaD_tryfuncTM(lua_State * L,StkId func)354 void luaD_tryfuncTM (lua_State *L, StkId func) {
355 const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
356 StkId p;
357 if (unlikely(ttisnil(tm)))
358 luaG_typeerror(L, s2v(func), "call"); /* nothing to call */
359 for (p = L->top; p > func; p--) /* open space for metamethod */
360 setobjs2s(L, p, p-1);
361 L->top++; /* stack space pre-allocated by the caller */
362 setobj2s(L, func, tm); /* metamethod is the new function to be called */
363 }
364
365
366 /*
367 ** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
368 ** Handle most typical cases (zero results for commands, one result for
369 ** expressions, multiple results for tail calls/single parameters)
370 ** separated.
371 */
moveresults(lua_State * L,StkId res,int nres,int wanted)372 static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
373 StkId firstresult;
374 int i;
375 switch (wanted) { /* handle typical cases separately */
376 case 0: /* no values needed */
377 L->top = res;
378 return;
379 case 1: /* one value needed */
380 if (nres == 0) /* no results? */
381 setnilvalue(s2v(res)); /* adjust with nil */
382 else
383 setobjs2s(L, res, L->top - nres); /* move it to proper place */
384 L->top = res + 1;
385 return;
386 case LUA_MULTRET:
387 wanted = nres; /* we want all results */
388 break;
389 default: /* multiple results (or to-be-closed variables) */
390 if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
391 ptrdiff_t savedres = savestack(L, res);
392 luaF_close(L, res, LUA_OK); /* may change the stack */
393 res = restorestack(L, savedres);
394 wanted = codeNresults(wanted); /* correct value */
395 if (wanted == LUA_MULTRET)
396 wanted = nres;
397 }
398 break;
399 }
400 firstresult = L->top - nres; /* index of first result */
401 /* move all results to correct place */
402 for (i = 0; i < nres && i < wanted; i++)
403 setobjs2s(L, res + i, firstresult + i);
404 for (; i < wanted; i++) /* complete wanted number of results */
405 setnilvalue(s2v(res + i));
406 L->top = res + wanted; /* top points after the last result */
407 }
408
409
410 /*
411 ** Finishes a function call: calls hook if necessary, removes CallInfo,
412 ** moves current number of results to proper place.
413 */
luaD_poscall(lua_State * L,CallInfo * ci,int nres)414 void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
415 if (L->hookmask)
416 L->top = rethook(L, ci, L->top - nres, nres);
417 L->ci = ci->previous; /* back to caller */
418 /* move results to proper place */
419 moveresults(L, ci->func, nres, ci->nresults);
420 }
421
422
423
424 #define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
425
426
427 /*
428 ** Prepare a function for a tail call, building its call info on top
429 ** of the current call info. 'narg1' is the number of arguments plus 1
430 ** (so that it includes the function itself).
431 */
luaD_pretailcall(lua_State * L,CallInfo * ci,StkId func,int narg1)432 void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) {
433 Proto *p = clLvalue(s2v(func))->p;
434 int fsize = p->maxstacksize; /* frame size */
435 int nfixparams = p->numparams;
436 int i;
437 for (i = 0; i < narg1; i++) /* move down function and arguments */
438 setobjs2s(L, ci->func + i, func + i);
439 checkstackGC(L, fsize);
440 func = ci->func; /* moved-down function */
441 for (; narg1 <= nfixparams; narg1++)
442 setnilvalue(s2v(func + narg1)); /* complete missing arguments */
443 ci->top = func + 1 + fsize; /* top for new function */
444 lua_assert(ci->top <= L->stack_last);
445 ci->u.l.savedpc = p->code; /* starting point */
446 ci->callstatus |= CIST_TAIL;
447 L->top = func + narg1; /* set top */
448 }
449
450
451 /*
452 ** Call a function (C or Lua). The function to be called is at *func.
453 ** The arguments are on the stack, right after the function.
454 ** When returns, all the results are on the stack, starting at the original
455 ** function position.
456 */
luaD_call(lua_State * L,StkId func,int nresults)457 void luaD_call (lua_State *L, StkId func, int nresults) {
458 lua_CFunction f;
459 retry:
460 switch (ttypetag(s2v(func))) {
461 case LUA_VCCL: /* C closure */
462 f = clCvalue(s2v(func))->f;
463 goto Cfunc;
464 case LUA_VLCF: /* light C function */
465 f = fvalue(s2v(func));
466 Cfunc: {
467 int n; /* number of returns */
468 CallInfo *ci;
469 checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
470 L->ci = ci = next_ci(L);
471 ci->nresults = nresults;
472 ci->callstatus = CIST_C;
473 ci->top = L->top + LUA_MINSTACK;
474 ci->func = func;
475 lua_assert(ci->top <= L->stack_last);
476 if (L->hookmask & LUA_MASKCALL) {
477 int narg = cast_int(L->top - func) - 1;
478 luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
479 }
480 lua_unlock(L);
481 n = (*f)(L); /* do the actual call */
482 lua_lock(L);
483 api_checknelems(L, n);
484 luaD_poscall(L, ci, n);
485 break;
486 }
487 case LUA_VLCL: { /* Lua function */
488 CallInfo *ci;
489 Proto *p = clLvalue(s2v(func))->p;
490 int narg = cast_int(L->top - func) - 1; /* number of real arguments */
491 int nfixparams = p->numparams;
492 int fsize = p->maxstacksize; /* frame size */
493 checkstackGCp(L, fsize, func);
494 L->ci = ci = next_ci(L);
495 ci->nresults = nresults;
496 ci->u.l.savedpc = p->code; /* starting point */
497 ci->callstatus = 0;
498 ci->top = func + 1 + fsize;
499 ci->func = func;
500 L->ci = ci;
501 for (; narg < nfixparams; narg++)
502 setnilvalue(s2v(L->top++)); /* complete missing arguments */
503 lua_assert(ci->top <= L->stack_last);
504 luaV_execute(L, ci); /* run the function */
505 break;
506 }
507 default: { /* not a function */
508 checkstackGCp(L, 1, func); /* space for metamethod */
509 luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
510 goto retry; /* try again with metamethod */
511 }
512 }
513 }
514
515
516 /*
517 ** Similar to 'luaD_call', but does not allow yields during the call.
518 */
luaD_callnoyield(lua_State * L,StkId func,int nResults)519 void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
520 incXCcalls(L);
521 if (getCcalls(L) <= CSTACKERR) { /* possible C stack overflow? */
522 luaE_exitCcall(L); /* to compensate decrement in next call */
523 luaE_enterCcall(L); /* check properly */
524 }
525 luaD_call(L, func, nResults);
526 decXCcalls(L);
527 }
528
529
530 /*
531 ** Completes the execution of an interrupted C function, calling its
532 ** continuation function.
533 */
finishCcall(lua_State * L,int status)534 static void finishCcall (lua_State *L, int status) {
535 CallInfo *ci = L->ci;
536 int n;
537 /* must have a continuation and must be able to call it */
538 lua_assert(ci->u.c.k != NULL && yieldable(L));
539 /* error status can only happen in a protected call */
540 lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
541 if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */
542 ci->callstatus &= ~CIST_YPCALL; /* continuation is also inside it */
543 L->errfunc = ci->u.c.old_errfunc; /* with the same error function */
544 }
545 /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
546 handled */
547 adjustresults(L, ci->nresults);
548 lua_unlock(L);
549 n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation function */
550 lua_lock(L);
551 api_checknelems(L, n);
552 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
553 }
554
555
556 /*
557 ** Executes "full continuation" (everything in the stack) of a
558 ** previously interrupted coroutine until the stack is empty (or another
559 ** interruption long-jumps out of the loop). If the coroutine is
560 ** recovering from an error, 'ud' points to the error status, which must
561 ** be passed to the first continuation function (otherwise the default
562 ** status is LUA_YIELD).
563 */
unroll(lua_State * L,void * ud)564 static void unroll (lua_State *L, void *ud) {
565 CallInfo *ci;
566 if (ud != NULL) /* error status? */
567 finishCcall(L, *(int *)ud); /* finish 'lua_pcallk' callee */
568 while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
569 if (!isLua(ci)) /* C function? */
570 finishCcall(L, LUA_YIELD); /* complete its execution */
571 else { /* Lua function */
572 luaV_finishOp(L); /* finish interrupted instruction */
573 luaV_execute(L, ci); /* execute down to higher C 'boundary' */
574 }
575 }
576 }
577
578
579 /*
580 ** Try to find a suspended protected call (a "recover point") for the
581 ** given thread.
582 */
findpcall(lua_State * L)583 static CallInfo *findpcall (lua_State *L) {
584 CallInfo *ci;
585 for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
586 if (ci->callstatus & CIST_YPCALL)
587 return ci;
588 }
589 return NULL; /* no pending pcall */
590 }
591
592
593 /*
594 ** Recovers from an error in a coroutine. Finds a recover point (if
595 ** there is one) and completes the execution of the interrupted
596 ** 'luaD_pcall'. If there is no recover point, returns zero.
597 */
recover(lua_State * L,int status)598 static int recover (lua_State *L, int status) {
599 StkId oldtop;
600 CallInfo *ci = findpcall(L);
601 if (ci == NULL) return 0; /* no recovery point */
602 /* "finish" luaD_pcall */
603 oldtop = restorestack(L, ci->u2.funcidx);
604 luaF_close(L, oldtop, status); /* may change the stack */
605 oldtop = restorestack(L, ci->u2.funcidx);
606 luaD_seterrorobj(L, status, oldtop);
607 L->ci = ci;
608 L->allowhook = getoah(ci->callstatus); /* restore original 'allowhook' */
609 luaD_shrinkstack(L);
610 L->errfunc = ci->u.c.old_errfunc;
611 return 1; /* continue running the coroutine */
612 }
613
614
615 /*
616 ** Signal an error in the call to 'lua_resume', not in the execution
617 ** of the coroutine itself. (Such errors should not be handled by any
618 ** coroutine error handler and should not kill the coroutine.)
619 */
resume_error(lua_State * L,const char * msg,int narg)620 static int resume_error (lua_State *L, const char *msg, int narg) {
621 L->top -= narg; /* remove args from the stack */
622 setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
623 api_incr_top(L);
624 lua_unlock(L);
625 return LUA_ERRRUN;
626 }
627
628
629 /*
630 ** Do the work for 'lua_resume' in protected mode. Most of the work
631 ** depends on the status of the coroutine: initial state, suspended
632 ** inside a hook, or regularly suspended (optionally with a continuation
633 ** function), plus erroneous cases: non-suspended coroutine or dead
634 ** coroutine.
635 */
resume(lua_State * L,void * ud)636 static void resume (lua_State *L, void *ud) {
637 int n = *(cast(int*, ud)); /* number of arguments */
638 StkId firstArg = L->top - n; /* first argument */
639 CallInfo *ci = L->ci;
640 if (L->status == LUA_OK) { /* starting a coroutine? */
641 luaD_call(L, firstArg - 1, LUA_MULTRET);
642 }
643 else { /* resuming from previous yield */
644 lua_assert(L->status == LUA_YIELD);
645 L->status = LUA_OK; /* mark that it is running (again) */
646 if (isLua(ci)) /* yielded inside a hook? */
647 luaV_execute(L, ci); /* just continue running Lua code */
648 else { /* 'common' yield */
649 if (ci->u.c.k != NULL) { /* does it have a continuation function? */
650 lua_unlock(L);
651 n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
652 lua_lock(L);
653 api_checknelems(L, n);
654 }
655 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
656 }
657 unroll(L, NULL); /* run continuation */
658 }
659 }
660
lua_resume(lua_State * L,lua_State * from,int nargs,int * nresults)661 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
662 int *nresults) {
663 int status;
664 lua_lock(L);
665 if (L->status == LUA_OK) { /* may be starting a coroutine */
666 if (L->ci != &L->base_ci) /* not in base level? */
667 return resume_error(L, "cannot resume non-suspended coroutine", nargs);
668 else if (L->top - (L->ci->func + 1) == nargs) /* no function? */
669 return resume_error(L, "cannot resume dead coroutine", nargs);
670 }
671 else if (L->status != LUA_YIELD) /* ended with errors? */
672 return resume_error(L, "cannot resume dead coroutine", nargs);
673 if (from == NULL)
674 L->nCcalls = CSTACKTHREAD;
675 else /* correct 'nCcalls' for this thread */
676 L->nCcalls = getCcalls(from) - L->nci - CSTACKCF;
677 if (L->nCcalls <= CSTACKERR)
678 return resume_error(L, "C stack overflow", nargs);
679 luai_userstateresume(L, nargs);
680 api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
681 status = luaD_rawrunprotected(L, resume, &nargs);
682 /* continue running after recoverable errors */
683 while (errorstatus(status) && recover(L, status)) {
684 /* unroll continuation */
685 status = luaD_rawrunprotected(L, unroll, &status);
686 }
687 if (likely(!errorstatus(status)))
688 lua_assert(status == L->status); /* normal end or yield */
689 else { /* unrecoverable error */
690 L->status = cast_byte(status); /* mark thread as 'dead' */
691 luaD_seterrorobj(L, status, L->top); /* push error message */
692 L->ci->top = L->top;
693 }
694 *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
695 : cast_int(L->top - (L->ci->func + 1));
696 lua_unlock(L);
697 return status;
698 }
699
700
lua_isyieldable(lua_State * L)701 LUA_API int lua_isyieldable (lua_State *L) {
702 return yieldable(L);
703 }
704
705
lua_yieldk(lua_State * L,int nresults,lua_KContext ctx,lua_KFunction k)706 LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
707 lua_KFunction k) {
708 CallInfo *ci;
709 luai_userstateyield(L, nresults);
710 lua_lock(L);
711 ci = L->ci;
712 api_checknelems(L, nresults);
713 if (unlikely(!yieldable(L))) {
714 if (L != G(L)->mainthread)
715 luaG_runerror(L, "attempt to yield across a C-call boundary");
716 else
717 luaG_runerror(L, "attempt to yield from outside a coroutine");
718 }
719 L->status = LUA_YIELD;
720 if (isLua(ci)) { /* inside a hook? */
721 lua_assert(!isLuacode(ci));
722 api_check(L, k == NULL, "hooks cannot continue after yielding");
723 ci->u2.nyield = 0; /* no results */
724 }
725 else {
726 if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
727 ci->u.c.ctx = ctx; /* save context */
728 ci->u2.nyield = nresults; /* save number of results */
729 luaD_throw(L, LUA_YIELD);
730 }
731 lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
732 lua_unlock(L);
733 return 0; /* return to 'luaD_hook' */
734 }
735
736
737 /*
738 ** Call the C function 'func' in protected mode, restoring basic
739 ** thread information ('allowhook', etc.) and in particular
740 ** its stack level in case of errors.
741 */
luaD_pcall(lua_State * L,Pfunc func,void * u,ptrdiff_t old_top,ptrdiff_t ef)742 int luaD_pcall (lua_State *L, Pfunc func, void *u,
743 ptrdiff_t old_top, ptrdiff_t ef) {
744 int status;
745 CallInfo *old_ci = L->ci;
746 lu_byte old_allowhooks = L->allowhook;
747 ptrdiff_t old_errfunc = L->errfunc;
748 L->errfunc = ef;
749 status = luaD_rawrunprotected(L, func, u);
750 if (unlikely(status != LUA_OK)) { /* an error occurred? */
751 StkId oldtop = restorestack(L, old_top);
752 L->ci = old_ci;
753 L->allowhook = old_allowhooks;
754 status = luaF_close(L, oldtop, status);
755 oldtop = restorestack(L, old_top); /* previous call may change stack */
756 luaD_seterrorobj(L, status, oldtop);
757 luaD_shrinkstack(L);
758 }
759 L->errfunc = old_errfunc;
760 return status;
761 }
762
763
764
765 /*
766 ** Execute a protected parser.
767 */
768 struct SParser { /* data to 'f_parser' */
769 ZIO *z;
770 Mbuffer buff; /* dynamic structure used by the scanner */
771 Dyndata dyd; /* dynamic structures used by the parser */
772 const char *mode;
773 const char *name;
774 };
775
776
checkmode(lua_State * L,const char * mode,const char * x)777 static void checkmode (lua_State *L, const char *mode, const char *x) {
778 if (mode && strchr(mode, x[0]) == NULL) {
779 luaO_pushfstring(L,
780 "attempt to load a %s chunk (mode is '%s')", x, mode);
781 luaD_throw(L, LUA_ERRSYNTAX);
782 }
783 }
784
785
f_parser(lua_State * L,void * ud)786 static void f_parser (lua_State *L, void *ud) {
787 LClosure *cl;
788 struct SParser *p = cast(struct SParser *, ud);
789 int c = zgetc(p->z); /* read first character */
790 if (c == LUA_SIGNATURE[0]) {
791 checkmode(L, p->mode, "binary");
792 cl = luaU_undump(L, p->z, p->name);
793 }
794 else {
795 checkmode(L, p->mode, "text");
796 cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
797 }
798 lua_assert(cl->nupvalues == cl->p->sizeupvalues);
799 luaF_initupvals(L, cl);
800 }
801
802
luaD_protectedparser(lua_State * L,ZIO * z,const char * name,const char * mode)803 int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
804 const char *mode) {
805 struct SParser p;
806 int status;
807 incnny(L); /* cannot yield during parsing */
808 p.z = z; p.name = name; p.mode = mode;
809 p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
810 p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
811 p.dyd.label.arr = NULL; p.dyd.label.size = 0;
812 luaZ_initbuffer(L, &p.buff);
813 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
814 luaZ_freebuffer(L, &p.buff);
815 luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
816 luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
817 luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
818 decnny(L);
819 return status;
820 }
821
822
823