1 /* BEGIN CSTYLED */
2 /*
3 ** $Id: ldo.c,v 2.108.1.3 2013/11/08 18:22:50 roberto Exp $
4 ** Stack and Call structure of Lua
5 ** See Copyright Notice in lua.h
6 */
7
8
9 #define ldo_c
10 #define LUA_CORE
11
12 #include <sys/lua/lua.h>
13
14 #include "lapi.h"
15 #include "ldebug.h"
16 #include "ldo.h"
17 #include "lfunc.h"
18 #include "lgc.h"
19 #include "lmem.h"
20 #include "lobject.h"
21 #include "lopcodes.h"
22 #include "lparser.h"
23 #include "lstate.h"
24 #include "lstring.h"
25 #include "ltable.h"
26 #include "ltm.h"
27 #include "lvm.h"
28 #include "lzio.h"
29
30
31
32 /* Return the number of bytes available on the stack. */
33 #if defined (_KERNEL) && defined(__linux__)
34 #include <asm/current.h>
stack_remaining(void)35 static intptr_t stack_remaining(void) {
36 intptr_t local;
37 local = (intptr_t)&local - (intptr_t)current->stack;
38 return local;
39 }
40 #elif defined (_KERNEL) && defined(__FreeBSD__)
41 #include <sys/pcpu.h>
stack_remaining(void)42 static intptr_t stack_remaining(void) {
43 intptr_t local;
44 local = (intptr_t)&local - (intptr_t)curthread->td_kstack;
45 return local;
46 }
47 #else
stack_remaining(void)48 static intptr_t stack_remaining(void) {
49 return INTPTR_MAX;
50 }
51 #endif
52
53 /*
54 ** {======================================================
55 ** Error-recovery functions
56 ** =======================================================
57 */
58
59 /*
60 ** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
61 ** default, Lua handles errors with exceptions when compiling as
62 ** C++ code, with _longjmp/_setjmp when asked to use them, and with
63 ** longjmp/setjmp otherwise.
64 */
65 #if !defined(LUAI_THROW)
66
67 #ifdef _KERNEL
68
69 #ifdef __linux__
70 #if defined(__i386__)
71 #define JMP_BUF_CNT 6
72 #elif defined(__x86_64__)
73 #define JMP_BUF_CNT 8
74 #elif defined(__sparc__) && defined(__arch64__)
75 #define JMP_BUF_CNT 6
76 #elif defined(__powerpc__)
77 #define JMP_BUF_CNT 26
78 #elif defined(__aarch64__)
79 #define JMP_BUF_CNT 64
80 #elif defined(__arm__)
81 #define JMP_BUF_CNT 65
82 #elif defined(__mips__)
83 #define JMP_BUF_CNT 12
84 #elif defined(__s390x__)
85 #define JMP_BUF_CNT 18
86 #elif defined(__riscv)
87 #define JMP_BUF_CNT 64
88 #else
89 #define JMP_BUF_CNT 1
90 #endif
91
92 typedef struct _label_t { long long unsigned val[JMP_BUF_CNT]; } label_t;
93
94 int setjmp(label_t *) __attribute__ ((__nothrow__));
95 extern void longjmp(label_t *) __attribute__((__noreturn__));
96
97 #define LUAI_THROW(L,c) longjmp(&(c)->b)
98 #define LUAI_TRY(L,c,a) if (setjmp(&(c)->b) == 0) { a }
99 #define luai_jmpbuf label_t
100
101 /* unsupported arches will build but not be able to run lua programs */
102 #if JMP_BUF_CNT == 1
setjmp(label_t * buf)103 int setjmp (label_t *buf) {
104 return 1;
105 }
106
longjmp(label_t * buf)107 void longjmp (label_t * buf) {
108 for (;;);
109 }
110 #endif
111 #else
112 #define LUAI_THROW(L,c) longjmp((c)->b, 1)
113 #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
114 #define luai_jmpbuf jmp_buf
115 #endif
116
117 #else /* _KERNEL */
118
119 #if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)
120 /* C++ exceptions */
121 #define LUAI_THROW(L,c) throw(c)
122 #define LUAI_TRY(L,c,a) \
123 try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
124 #define luai_jmpbuf int /* dummy variable */
125
126 #elif defined(LUA_USE_ULONGJMP)
127 /* in Unix, try _longjmp/_setjmp (more efficient) */
128 #define LUAI_THROW(L,c) _longjmp((c)->b, 1)
129 #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
130 #define luai_jmpbuf jmp_buf
131
132 #else
133 /* default handling with long jumps */
134 #define LUAI_THROW(L,c) longjmp((c)->b, 1)
135 #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
136 #define luai_jmpbuf jmp_buf
137
138 #endif
139
140 #endif /* _KERNEL */
141
142 #endif /* LUAI_THROW */
143
144
145 /* chain list of long jump buffers */
146 struct lua_longjmp {
147 struct lua_longjmp *previous;
148 luai_jmpbuf b;
149 volatile int status; /* error code */
150 };
151
152
seterrorobj(lua_State * L,int errcode,StkId oldtop)153 static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
154 switch (errcode) {
155 case LUA_ERRMEM: { /* memory error? */
156 setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
157 break;
158 }
159 case LUA_ERRERR: {
160 setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
161 break;
162 }
163 default: {
164 setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
165 break;
166 }
167 }
168 L->top = oldtop + 1;
169 }
170
171
luaD_throw(lua_State * L,int errcode)172 l_noret luaD_throw (lua_State *L, int errcode) {
173 if (L->errorJmp) { /* thread has an error handler? */
174 L->errorJmp->status = errcode; /* set status */
175 LUAI_THROW(L, L->errorJmp); /* jump to it */
176 }
177 else { /* thread has no error handler */
178 L->status = cast_byte(errcode); /* mark it as dead */
179 if (G(L)->mainthread->errorJmp) { /* main thread has a handler? */
180 setobjs2s(L, G(L)->mainthread->top++, L->top - 1); /* copy error obj. */
181 luaD_throw(G(L)->mainthread, errcode); /* re-throw in main thread */
182 }
183 else { /* no handler at all; abort */
184 if (G(L)->panic) { /* panic function? */
185 lua_unlock(L);
186 G(L)->panic(L); /* call it (last chance to jump out) */
187 }
188 panic("no error handler");
189 }
190 }
191 }
192
193
luaD_rawrunprotected(lua_State * L,Pfunc f,void * ud)194 int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
195 unsigned short oldnCcalls = L->nCcalls;
196 struct lua_longjmp lj;
197 lj.status = LUA_OK;
198 lj.previous = L->errorJmp; /* chain new error handler */
199 // cppcheck-suppress autoVariables
200 L->errorJmp = &lj;
201 LUAI_TRY(L, &lj,
202 (*f)(L, ud);
203 );
204 L->errorJmp = lj.previous; /* restore old error handler */
205 L->nCcalls = oldnCcalls;
206 return lj.status;
207 }
208
209 /* }====================================================== */
210
211
correctstack(lua_State * L,TValue * oldstack)212 static void correctstack (lua_State *L, TValue *oldstack) {
213 CallInfo *ci;
214 GCObject *up;
215 L->top = (L->top - oldstack) + L->stack;
216 for (up = L->openupval; up != NULL; up = up->gch.next)
217 gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
218 for (ci = L->ci; ci != NULL; ci = ci->previous) {
219 ci->top = (ci->top - oldstack) + L->stack;
220 ci->func = (ci->func - oldstack) + L->stack;
221 if (isLua(ci))
222 ci->u.l.base = (ci->u.l.base - oldstack) + L->stack;
223 }
224 }
225
226
227 /* some space for error handling */
228 #define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
229
230
luaD_reallocstack(lua_State * L,int newsize)231 void luaD_reallocstack (lua_State *L, int newsize) {
232 TValue *oldstack = L->stack;
233 int lim = L->stacksize;
234 lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
235 lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
236 luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue);
237 for (; lim < newsize; lim++)
238 setnilvalue(L->stack + lim); /* erase new segment */
239 L->stacksize = newsize;
240 L->stack_last = L->stack + newsize - EXTRA_STACK;
241 correctstack(L, oldstack);
242 }
243
244
luaD_growstack(lua_State * L,int n)245 void luaD_growstack (lua_State *L, int n) {
246 int size = L->stacksize;
247 if (size > LUAI_MAXSTACK) /* error after extra size? */
248 luaD_throw(L, LUA_ERRERR);
249 else {
250 int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
251 int newsize = 2 * size;
252 if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK;
253 if (newsize < needed) newsize = needed;
254 if (newsize > LUAI_MAXSTACK) { /* stack overflow? */
255 luaD_reallocstack(L, ERRORSTACKSIZE);
256 luaG_runerror(L, "stack overflow");
257 }
258 else
259 luaD_reallocstack(L, newsize);
260 }
261 }
262
263
stackinuse(lua_State * L)264 static int stackinuse (lua_State *L) {
265 CallInfo *ci;
266 StkId lim = L->top;
267 for (ci = L->ci; ci != NULL; ci = ci->previous) {
268 lua_assert(ci->top <= L->stack_last);
269 if (lim < ci->top) lim = ci->top;
270 }
271 return cast_int(lim - L->stack) + 1; /* part of stack in use */
272 }
273
274
luaD_shrinkstack(lua_State * L)275 void luaD_shrinkstack (lua_State *L) {
276 int inuse = stackinuse(L);
277 int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
278 if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
279 if (inuse > LUAI_MAXSTACK || /* handling stack overflow? */
280 goodsize >= L->stacksize) /* would grow instead of shrink? */
281 condmovestack(L); /* don't change stack (change only for debugging) */
282 else
283 luaD_reallocstack(L, goodsize); /* shrink it */
284 }
285
286
luaD_hook(lua_State * L,int event,int line)287 void luaD_hook (lua_State *L, int event, int line) {
288 lua_Hook hook = L->hook;
289 if (hook && L->allowhook) {
290 CallInfo *ci = L->ci;
291 ptrdiff_t top = savestack(L, L->top);
292 ptrdiff_t ci_top = savestack(L, ci->top);
293 lua_Debug ar;
294 ar.event = event;
295 ar.currentline = line;
296 ar.i_ci = ci;
297 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
298 ci->top = L->top + LUA_MINSTACK;
299 lua_assert(ci->top <= L->stack_last);
300 L->allowhook = 0; /* cannot call hooks inside a hook */
301 ci->callstatus |= CIST_HOOKED;
302 lua_unlock(L);
303 (*hook)(L, &ar);
304 lua_lock(L);
305 lua_assert(!L->allowhook);
306 L->allowhook = 1;
307 ci->top = restorestack(L, ci_top);
308 L->top = restorestack(L, top);
309 ci->callstatus &= ~CIST_HOOKED;
310 }
311 }
312
313
callhook(lua_State * L,CallInfo * ci)314 static void callhook (lua_State *L, CallInfo *ci) {
315 int hook = LUA_HOOKCALL;
316 ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
317 if (isLua(ci->previous) &&
318 GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) {
319 ci->callstatus |= CIST_TAIL;
320 hook = LUA_HOOKTAILCALL;
321 }
322 luaD_hook(L, hook, -1);
323 ci->u.l.savedpc--; /* correct 'pc' */
324 }
325
326
adjust_varargs(lua_State * L,Proto * p,int actual)327 static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
328 int i;
329 int nfixargs = p->numparams;
330 StkId base, fixed;
331 lua_assert(actual >= nfixargs);
332 /* move fixed parameters to final position */
333 luaD_checkstack(L, p->maxstacksize); /* check again for new 'base' */
334 fixed = L->top - actual; /* first fixed argument */
335 base = L->top; /* final position of first argument */
336 for (i=0; i<nfixargs; i++) {
337 setobjs2s(L, L->top++, fixed + i);
338 setnilvalue(fixed + i);
339 }
340 return base;
341 }
342
343
tryfuncTM(lua_State * L,StkId func)344 static StkId tryfuncTM (lua_State *L, StkId func) {
345 const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
346 StkId p;
347 ptrdiff_t funcr = savestack(L, func);
348 if (!ttisfunction(tm))
349 luaG_typeerror(L, func, "call");
350 /* Open a hole inside the stack at `func' */
351 for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);
352 incr_top(L);
353 func = restorestack(L, funcr); /* previous call may change stack */
354 setobj2s(L, func, tm); /* tag method is the new function to be called */
355 return func;
356 }
357
358
359
360 #define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))
361
362
363 /*
364 ** returns true if function has been executed (C function)
365 */
luaD_precall(lua_State * L,StkId func,int nresults)366 int luaD_precall (lua_State *L, StkId func, int nresults) {
367 lua_CFunction f;
368 CallInfo *ci;
369 int n; /* number of arguments (Lua) or returns (C) */
370 ptrdiff_t funcr = savestack(L, func);
371 switch (ttype(func)) {
372 case LUA_TLCF: /* light C function */
373 f = fvalue(func);
374 goto Cfunc;
375 case LUA_TCCL: { /* C closure */
376 f = clCvalue(func)->f;
377 Cfunc:
378 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
379 ci = next_ci(L); /* now 'enter' new function */
380 ci->nresults = nresults;
381 ci->func = restorestack(L, funcr);
382 ci->top = L->top + LUA_MINSTACK;
383 lua_assert(ci->top <= L->stack_last);
384 ci->callstatus = 0;
385 luaC_checkGC(L); /* stack grow uses memory */
386 if (L->hookmask & LUA_MASKCALL)
387 luaD_hook(L, LUA_HOOKCALL, -1);
388 lua_unlock(L);
389 n = (*f)(L); /* do the actual call */
390 lua_lock(L);
391 api_checknelems(L, n);
392 luaD_poscall(L, L->top - n);
393 return 1;
394 }
395 case LUA_TLCL: { /* Lua function: prepare its call */
396 StkId base;
397 Proto *p = clLvalue(func)->p;
398 n = cast_int(L->top - func) - 1; /* number of real arguments */
399 luaD_checkstack(L, p->maxstacksize);
400 for (; n < p->numparams; n++)
401 setnilvalue(L->top++); /* complete missing arguments */
402 if (!p->is_vararg) {
403 func = restorestack(L, funcr);
404 base = func + 1;
405 }
406 else {
407 base = adjust_varargs(L, p, n);
408 func = restorestack(L, funcr); /* previous call can change stack */
409 }
410 ci = next_ci(L); /* now 'enter' new function */
411 ci->nresults = nresults;
412 ci->func = func;
413 ci->u.l.base = base;
414 ci->top = base + p->maxstacksize;
415 lua_assert(ci->top <= L->stack_last);
416 ci->u.l.savedpc = p->code; /* starting point */
417 ci->callstatus = CIST_LUA;
418 L->top = ci->top;
419 luaC_checkGC(L); /* stack grow uses memory */
420 if (L->hookmask & LUA_MASKCALL)
421 callhook(L, ci);
422 return 0;
423 }
424 default: { /* not a function */
425 func = tryfuncTM(L, func); /* retry with 'function' tag method */
426 return luaD_precall(L, func, nresults); /* now it must be a function */
427 }
428 }
429 }
430
431
luaD_poscall(lua_State * L,StkId firstResult)432 int luaD_poscall (lua_State *L, StkId firstResult) {
433 StkId res;
434 int wanted, i;
435 CallInfo *ci = L->ci;
436 if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {
437 if (L->hookmask & LUA_MASKRET) {
438 ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */
439 luaD_hook(L, LUA_HOOKRET, -1);
440 firstResult = restorestack(L, fr);
441 }
442 L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */
443 }
444 res = ci->func; /* res == final position of 1st result */
445 wanted = ci->nresults;
446 L->ci = ci = ci->previous; /* back to caller */
447 /* move results to correct place */
448 for (i = wanted; i != 0 && firstResult < L->top; i--)
449 setobjs2s(L, res++, firstResult++);
450 while (i-- > 0)
451 setnilvalue(res++);
452 L->top = res;
453 return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */
454 }
455
456
457 /*
458 ** Call a function (C or Lua). The function to be called is at *func.
459 ** The arguments are on the stack, right after the function.
460 ** When returns, all the results are on the stack, starting at the original
461 ** function position.
462 */
luaD_call(lua_State * L,StkId func,int nResults,int allowyield)463 void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) {
464 if (++L->nCcalls >= LUAI_MAXCCALLS) {
465 if (L->nCcalls == LUAI_MAXCCALLS)
466 luaG_runerror(L, "C stack overflow");
467 else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
468 luaD_throw(L, LUA_ERRERR); /* error while handling stack error */
469 }
470 intptr_t remaining = stack_remaining();
471 if (L->runerror == 0 && remaining < LUAI_MINCSTACK)
472 luaG_runerror(L, "C stack overflow");
473 if (L->runerror != 0 && remaining < LUAI_MINCSTACK / 2)
474 luaD_throw(L, LUA_ERRERR); /* error while handling stack error */
475 if (!allowyield) L->nny++;
476 if (!luaD_precall(L, func, nResults)) /* is a Lua function? */
477 luaV_execute(L); /* call it */
478 if (!allowyield) L->nny--;
479 L->nCcalls--;
480 }
481
482
finishCcall(lua_State * L)483 static void finishCcall (lua_State *L) {
484 CallInfo *ci = L->ci;
485 int n;
486 lua_assert(ci->u.c.k != NULL); /* must have a continuation */
487 lua_assert(L->nny == 0);
488 if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */
489 ci->callstatus &= ~CIST_YPCALL; /* finish 'lua_pcall' */
490 L->errfunc = ci->u.c.old_errfunc;
491 }
492 /* finish 'lua_callk'/'lua_pcall' */
493 adjustresults(L, ci->nresults);
494 /* call continuation function */
495 if (!(ci->callstatus & CIST_STAT)) /* no call status? */
496 ci->u.c.status = LUA_YIELD; /* 'default' status */
497 lua_assert(ci->u.c.status != LUA_OK);
498 ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED;
499 lua_unlock(L);
500 n = (*ci->u.c.k)(L);
501 lua_lock(L);
502 api_checknelems(L, n);
503 /* finish 'luaD_precall' */
504 luaD_poscall(L, L->top - n);
505 }
506
507
unroll(lua_State * L,void * ud)508 static void unroll (lua_State *L, void *ud) {
509 UNUSED(ud);
510 for (;;) {
511 if (L->ci == &L->base_ci) /* stack is empty? */
512 return; /* coroutine finished normally */
513 if (!isLua(L->ci)) /* C function? */
514 finishCcall(L);
515 else { /* Lua function */
516 luaV_finishOp(L); /* finish interrupted instruction */
517 luaV_execute(L); /* execute down to higher C 'boundary' */
518 }
519 }
520 }
521
522
523 /*
524 ** check whether thread has a suspended protected call
525 */
findpcall(lua_State * L)526 static CallInfo *findpcall (lua_State *L) {
527 CallInfo *ci;
528 for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
529 if (ci->callstatus & CIST_YPCALL)
530 return ci;
531 }
532 return NULL; /* no pending pcall */
533 }
534
535
recover(lua_State * L,int status)536 static int recover (lua_State *L, int status) {
537 StkId oldtop;
538 CallInfo *ci = findpcall(L);
539 if (ci == NULL) return 0; /* no recovery point */
540 /* "finish" luaD_pcall */
541 oldtop = restorestack(L, ci->extra);
542 luaF_close(L, oldtop);
543 seterrorobj(L, status, oldtop);
544 L->ci = ci;
545 L->allowhook = ci->u.c.old_allowhook;
546 L->nny = 0; /* should be zero to be yieldable */
547 luaD_shrinkstack(L);
548 L->errfunc = ci->u.c.old_errfunc;
549 ci->callstatus |= CIST_STAT; /* call has error status */
550 ci->u.c.status = status; /* (here it is) */
551 return 1; /* continue running the coroutine */
552 }
553
554
555 /*
556 ** signal an error in the call to 'resume', not in the execution of the
557 ** coroutine itself. (Such errors should not be handled by any coroutine
558 ** error handler and should not kill the coroutine.)
559 */
resume_error(lua_State * L,const char * msg,StkId firstArg)560 static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) {
561 L->top = firstArg; /* remove args from the stack */
562 setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
563 api_incr_top(L);
564 luaD_throw(L, -1); /* jump back to 'lua_resume' */
565 }
566
567
568 /*
569 ** do the work for 'lua_resume' in protected mode
570 */
resume_cb(lua_State * L,void * ud)571 static void resume_cb (lua_State *L, void *ud) {
572 int nCcalls = L->nCcalls;
573 StkId firstArg = cast(StkId, ud);
574 CallInfo *ci = L->ci;
575 if (nCcalls >= LUAI_MAXCCALLS)
576 resume_error(L, "C stack overflow", firstArg);
577 if (L->status == LUA_OK) { /* may be starting a coroutine */
578 if (ci != &L->base_ci) /* not in base level? */
579 resume_error(L, "cannot resume non-suspended coroutine", firstArg);
580 /* coroutine is in base level; start running it */
581 if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */
582 luaV_execute(L); /* call it */
583 }
584 else if (L->status != LUA_YIELD)
585 resume_error(L, "cannot resume dead coroutine", firstArg);
586 else { /* resuming from previous yield */
587 L->status = LUA_OK;
588 ci->func = restorestack(L, ci->extra);
589 if (isLua(ci)) /* yielded inside a hook? */
590 luaV_execute(L); /* just continue running Lua code */
591 else { /* 'common' yield */
592 if (ci->u.c.k != NULL) { /* does it have a continuation? */
593 int n;
594 ci->u.c.status = LUA_YIELD; /* 'default' status */
595 ci->callstatus |= CIST_YIELDED;
596 lua_unlock(L);
597 n = (*ci->u.c.k)(L); /* call continuation */
598 lua_lock(L);
599 api_checknelems(L, n);
600 firstArg = L->top - n; /* yield results come from continuation */
601 }
602 luaD_poscall(L, firstArg); /* finish 'luaD_precall' */
603 }
604 unroll(L, NULL);
605 }
606 lua_assert(nCcalls == L->nCcalls);
607 }
608
609
lua_resume(lua_State * L,lua_State * from,int nargs)610 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
611 int status;
612 int oldnny = L->nny; /* save 'nny' */
613 lua_lock(L);
614 luai_userstateresume(L, nargs);
615 L->nCcalls = (from) ? from->nCcalls + 1 : 1;
616 L->nny = 0; /* allow yields */
617 api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
618 status = luaD_rawrunprotected(L, resume_cb, L->top - nargs);
619 if (status == -1) /* error calling 'lua_resume'? */
620 status = LUA_ERRRUN;
621 else { /* yield or regular error */
622 while (status != LUA_OK && status != LUA_YIELD) { /* error? */
623 if (recover(L, status)) /* recover point? */
624 status = luaD_rawrunprotected(L, unroll, NULL); /* run continuation */
625 else { /* unrecoverable error */
626 L->status = cast_byte(status); /* mark thread as `dead' */
627 seterrorobj(L, status, L->top);
628 L->ci->top = L->top;
629 break;
630 }
631 }
632 lua_assert(status == L->status);
633 }
634 L->nny = oldnny; /* restore 'nny' */
635 L->nCcalls--;
636 lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));
637 lua_unlock(L);
638 return status;
639 }
640
641
lua_yieldk(lua_State * L,int nresults,int ctx,lua_CFunction k)642 LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) {
643 CallInfo *ci = L->ci;
644 luai_userstateyield(L, nresults);
645 lua_lock(L);
646 api_checknelems(L, nresults);
647 if (L->nny > 0) {
648 if (L != G(L)->mainthread)
649 luaG_runerror(L, "attempt to yield across a C-call boundary");
650 else
651 luaG_runerror(L, "attempt to yield from outside a coroutine");
652 }
653 L->status = LUA_YIELD;
654 ci->extra = savestack(L, ci->func); /* save current 'func' */
655 if (isLua(ci)) { /* inside a hook? */
656 api_check(L, k == NULL, "hooks cannot continue after yielding");
657 }
658 else {
659 if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
660 ci->u.c.ctx = ctx; /* save context */
661 ci->func = L->top - nresults - 1; /* protect stack below results */
662 luaD_throw(L, LUA_YIELD);
663 }
664 lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
665 lua_unlock(L);
666 return 0; /* return to 'luaD_hook' */
667 }
668
669
luaD_pcall(lua_State * L,Pfunc func,void * u,ptrdiff_t old_top,ptrdiff_t ef)670 int luaD_pcall (lua_State *L, Pfunc func, void *u,
671 ptrdiff_t old_top, ptrdiff_t ef) {
672 int status;
673 CallInfo *old_ci = L->ci;
674 lu_byte old_allowhooks = L->allowhook;
675 unsigned short old_nny = L->nny;
676 ptrdiff_t old_errfunc = L->errfunc;
677 L->errfunc = ef;
678 status = luaD_rawrunprotected(L, func, u);
679 if (status != LUA_OK) { /* an error occurred? */
680 StkId oldtop = restorestack(L, old_top);
681 luaF_close(L, oldtop); /* close possible pending closures */
682 seterrorobj(L, status, oldtop);
683 L->ci = old_ci;
684 L->allowhook = old_allowhooks;
685 L->nny = old_nny;
686 luaD_shrinkstack(L);
687 }
688 L->errfunc = old_errfunc;
689 return status;
690 }
691
692
693
694 /*
695 ** Execute a protected parser.
696 */
697 struct SParser { /* data to `f_parser' */
698 ZIO *z;
699 Mbuffer buff; /* dynamic structure used by the scanner */
700 Dyndata dyd; /* dynamic structures used by the parser */
701 const char *mode;
702 const char *name;
703 };
704
705
checkmode(lua_State * L,const char * mode,const char * x)706 static void checkmode (lua_State *L, const char *mode, const char *x) {
707 if (mode && strchr(mode, x[0]) == NULL) {
708 luaO_pushfstring(L,
709 "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode);
710 luaD_throw(L, LUA_ERRSYNTAX);
711 }
712 }
713
714
f_parser(lua_State * L,void * ud)715 static void f_parser (lua_State *L, void *ud) {
716 int i;
717 Closure *cl;
718 struct SParser *p = cast(struct SParser *, ud);
719 int c = zgetc(p->z); /* read first character */
720 lua_assert(c != LUA_SIGNATURE[0]); /* binary not supported */
721 checkmode(L, p->mode, "text");
722 cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
723 lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
724 for (i = 0; i < cl->l.nupvalues; i++) { /* initialize upvalues */
725 UpVal *up = luaF_newupval(L);
726 cl->l.upvals[i] = up;
727 luaC_objbarrier(L, cl, up);
728 }
729 }
730
731
luaD_protectedparser(lua_State * L,ZIO * z,const char * name,const char * mode)732 int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
733 const char *mode) {
734 struct SParser p;
735 int status;
736 L->nny++; /* cannot yield during parsing */
737 p.z = z; p.name = name; p.mode = mode;
738 p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
739 p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
740 p.dyd.label.arr = NULL; p.dyd.label.size = 0;
741 luaZ_initbuffer(L, &p.buff);
742 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
743 luaZ_freebuffer(L, &p.buff);
744 luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
745 luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
746 luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
747 L->nny--;
748 return status;
749 }
750 /* END CSTYLED */
751