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