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