interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / ldo.c

1192 lines · 40717 bytes Raw Blame History
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** these macros allow user-specific actions when a thread is
43** resumed/yielded.
44*/
45#if !defined(luai_userstateresume)
46#define luai_userstateresume(L,n) ((void)L)
47#endif
48
49#if !defined(luai_userstateyield)
50#define luai_userstateyield(L,n) ((void)L)
51#endif
52
53
54/*
55** {======================================================
56** Error-recovery functions
57** =======================================================
58*/
59
60/* chained list of long jump buffers */
61typedef struct lua_longjmp {
62 struct lua_longjmp *previous;
63 jmp_buf b;
64 volatile TStatus status; /* error code */
65} lua_longjmp;
66
67
68/*
69** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
70** default, Lua handles errors with exceptions when compiling as
71** C++ code, with _longjmp/_setjmp when available (POSIX), and with
72** longjmp/setjmp otherwise.
73*/
74#if !defined(LUAI_THROW) /* { */
75
76#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
77
78/* C++ exceptions */
79#define LUAI_THROW(L,c) throw(c)
80
81static void LUAI_TRY (lua_State *L, lua_longjmp *c, Pfunc f, void *ud) {
82 try {
83 f(L, ud); /* call function protected */
84 }
85 catch (lua_longjmp *c1) { /* Lua error */
86 if (c1 != c) /* not the correct level? */
87 throw; /* rethrow to upper level */
88 }
89 catch (...) { /* non-Lua exception */
90 c->status = -1; /* create some error code */
91 }
92}
93
94
95#elif defined(LUA_USE_POSIX) /* }{ */
96
97/* in POSIX, use _longjmp/_setjmp (more efficient) */
98#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
99#define LUAI_TRY(L,c,f,ud) if (_setjmp((c)->b) == 0) ((f)(L, ud))
100
101#else /* }{ */
102
103/* ISO C handling with long jumps */
104#define LUAI_THROW(L,c) longjmp((c)->b, 1)
105#define LUAI_TRY(L,c,f,ud) if (setjmp((c)->b) == 0) ((f)(L, ud))
106
107#endif /* } */
108
109#endif /* } */
110
111
112void luaD_seterrorobj (lua_State *L, TStatus errcode, StkId oldtop) {
113 if (errcode == LUA_ERRMEM) { /* memory error? */
114 setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
115 }
116 else {
117 lua_assert(errorstatus(errcode)); /* must be a real error */
118 lua_assert(!ttisnil(s2v(L->top.p - 1))); /* with a non-nil object */
119 setobjs2s(L, oldtop, L->top.p - 1); /* move it to 'oldtop' */
120 }
121 L->top.p = oldtop + 1; /* top goes back to old top plus error object */
122}
123
124
125l_noret luaD_throw (lua_State *L, TStatus errcode) {
126 if (L->errorJmp) { /* thread has an error handler? */
127 L->errorJmp->status = errcode; /* set status */
128 LUAI_THROW(L, L->errorJmp); /* jump to it */
129 }
130 else { /* thread has no error handler */
131 global_State *g = G(L);
132 lua_State *mainth = mainthread(g);
133 errcode = luaE_resetthread(L, errcode); /* close all upvalues */
134 L->status = errcode;
135 if (mainth->errorJmp) { /* main thread has a handler? */
136 setobjs2s(L, mainth->top.p++, L->top.p - 1); /* copy error obj. */
137 luaD_throw(mainth, errcode); /* re-throw in main thread */
138 }
139 else { /* no handler at all; abort */
140 if (g->panic) { /* panic function? */
141 lua_unlock(L);
142 g->panic(L); /* call panic function (last chance to jump out) */
143 }
144 abort();
145 }
146 }
147}
148
149
150l_noret luaD_throwbaselevel (lua_State *L, TStatus errcode) {
151 if (L->errorJmp) {
152 /* unroll error entries up to the first level */
153 while (L->errorJmp->previous != NULL)
154 L->errorJmp = L->errorJmp->previous;
155 }
156 luaD_throw(L, errcode);
157}
158
159
160TStatus luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
161 l_uint32 oldnCcalls = L->nCcalls;
162 lua_longjmp lj;
163 lj.status = LUA_OK;
164 lj.previous = L->errorJmp; /* chain new error handler */
165 L->errorJmp = &lj;
166 LUAI_TRY(L, &lj, f, ud); /* call 'f' catching errors */
167 L->errorJmp = lj.previous; /* restore old error handler */
168 L->nCcalls = oldnCcalls;
169 return lj.status;
170}
171
172/* }====================================================== */
173
174
175/*
176** {==================================================================
177** Stack reallocation
178** ===================================================================
179*/
180
181/* some stack space for error handling */
182#define STACKERRSPACE 200
183
184
185/*
186** LUAI_MAXSTACK limits the size of the Lua stack.
187** It must fit into INT_MAX/2.
188*/
189
190#if !defined(LUAI_MAXSTACK)
191#if 1000000 < (INT_MAX / 2)
192#define LUAI_MAXSTACK 1000000
193#else
194#define LUAI_MAXSTACK (INT_MAX / 2u)
195#endif
196#endif
197
198
199/* maximum stack size that respects size_t */
200#define MAXSTACK_BYSIZET ((MAX_SIZET / sizeof(StackValue)) - STACKERRSPACE)
201
202/*
203** Minimum between LUAI_MAXSTACK and MAXSTACK_BYSIZET
204** (Maximum size for the stack must respect size_t.)
205*/
206#define MAXSTACK cast_int(LUAI_MAXSTACK < MAXSTACK_BYSIZET \
207 ? LUAI_MAXSTACK : MAXSTACK_BYSIZET)
208
209
210/* stack size with extra space for error handling */
211#define ERRORSTACKSIZE (MAXSTACK + STACKERRSPACE)
212
213
214/* raise a stack error while running the message handler */
215l_noret luaD_errerr (lua_State *L) {
216 TString *msg = luaS_newliteral(L, "error in error handling");
217 setsvalue2s(L, L->top.p, msg);
218 L->top.p++; /* assume EXTRA_STACK */
219 luaD_throw(L, LUA_ERRERR);
220}
221
222
223/*
224** Check whether stacks have enough space to run a simple function (such
225** as a finalizer): At least BASIC_STACK_SIZE in the Lua stack, two
226** available CallInfos, and two "slots" in the C stack.
227*/
228int luaD_checkminstack (lua_State *L) {
229 if (getCcalls(L) >= LUAI_MAXCCALLS - 2)
230 return 0; /* not enough C-stack slots */
231 if (L->ci->next == NULL && luaE_extendCI(L, 0) == NULL)
232 return 0; /* unable to allocate first ci */
233 if (L->ci->next->next == NULL && luaE_extendCI(L, 0) == NULL)
234 return 0; /* unable to allocate second ci */
235 if (L->stack_last.p - L->top.p >= BASIC_STACK_SIZE)
236 return 1; /* enough (BASIC_STACK_SIZE) free slots in the Lua stack */
237 else /* try to grow stack to a size with enough free slots */
238 return luaD_growstack(L, BASIC_STACK_SIZE, 0);
239}
240
241
242/*
243** In ISO C, any pointer use after the pointer has been deallocated is
244** undefined behavior. So, before a stack reallocation, all pointers
245** should be changed to offsets, and after the reallocation they should
246** be changed back to pointers. As during the reallocation the pointers
247** are invalid, the reallocation cannot run emergency collections.
248** Alternatively, we can use the old address after the deallocation.
249** That is not strict ISO C, but seems to work fine everywhere.
250** The following macro chooses how strict is the code.
251*/
252#if !defined(LUAI_STRICT_ADDRESS)
253#define LUAI_STRICT_ADDRESS 1
254#endif
255
256#if LUAI_STRICT_ADDRESS
257/*
258** Change all pointers to the stack into offsets.
259*/
260static void relstack (lua_State *L) {
261 CallInfo *ci;
262 UpVal *up;
263 L->top.offset = savestack(L, L->top.p);
264 L->tbclist.offset = savestack(L, L->tbclist.p);
265 for (up = L->openupval; up != NULL; up = up->u.open.next)
266 up->v.offset = savestack(L, uplevel(up));
267 for (ci = L->ci; ci != NULL; ci = ci->previous) {
268 ci->top.offset = savestack(L, ci->top.p);
269 ci->func.offset = savestack(L, ci->func.p);
270 }
271}
272
273
274/*
275** Change back all offsets into pointers.
276*/
277static void correctstack (lua_State *L, StkId oldstack) {
278 CallInfo *ci;
279 UpVal *up;
280 UNUSED(oldstack);
281 L->top.p = restorestack(L, L->top.offset);
282 L->tbclist.p = restorestack(L, L->tbclist.offset);
283 for (up = L->openupval; up != NULL; up = up->u.open.next)
284 up->v.p = s2v(restorestack(L, up->v.offset));
285 for (ci = L->ci; ci != NULL; ci = ci->previous) {
286 ci->top.p = restorestack(L, ci->top.offset);
287 ci->func.p = restorestack(L, ci->func.offset);
288 if (isLua(ci))
289 ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
290 }
291}
292
293#else
294/*
295** Assume that it is fine to use an address after its deallocation,
296** as long as we do not dereference it.
297*/
298
299static void relstack (lua_State *L) { UNUSED(L); } /* do nothing */
300
301
302/*
303** Correct pointers into 'oldstack' to point into 'L->stack'.
304*/
305static void correctstack (lua_State *L, StkId oldstack) {
306 CallInfo *ci;
307 UpVal *up;
308 StkId newstack = L->stack.p;
309 if (oldstack == newstack)
310 return;
311 L->top.p = L->top.p - oldstack + newstack;
312 L->tbclist.p = L->tbclist.p - oldstack + newstack;
313 for (up = L->openupval; up != NULL; up = up->u.open.next)
314 up->v.p = s2v(uplevel(up) - oldstack + newstack);
315 for (ci = L->ci; ci != NULL; ci = ci->previous) {
316 ci->top.p = ci->top.p - oldstack + newstack;
317 ci->func.p = ci->func.p - oldstack + newstack;
318 if (isLua(ci))
319 ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
320 }
321}
322#endif
323
324
325/*
326** Reallocate the stack to a new size, correcting all pointers into it.
327** In case of allocation error, raise an error or return false according
328** to 'raiseerror'.
329*/
330int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
331 int oldsize = stacksize(L);
332 int i;
333 StkId newstack;
334 StkId oldstack = L->stack.p;
335 lu_byte oldgcstop = G(L)->gcstopem;
336 lua_assert(newsize <= MAXSTACK || newsize == ERRORSTACKSIZE);
337 relstack(L); /* change pointers to offsets */
338 G(L)->gcstopem = 1; /* stop emergency collection */
339 newstack = luaM_reallocvector(L, oldstack, oldsize + EXTRA_STACK,
340 newsize + EXTRA_STACK, StackValue);
341 G(L)->gcstopem = oldgcstop; /* restore emergency collection */
342 if (l_unlikely(newstack == NULL)) { /* reallocation failed? */
343 correctstack(L, oldstack); /* change offsets back to pointers */
344 if (raiseerror)
345 luaM_error(L);
346 else return 0; /* do not raise an error */
347 }
348 L->stack.p = newstack;
349 correctstack(L, oldstack); /* change offsets back to pointers */
350 L->stack_last.p = L->stack.p + newsize;
351 for (i = oldsize + EXTRA_STACK; i < newsize + EXTRA_STACK; i++)
352 setnilvalue2s(newstack + i); /* erase new segment */
353 return 1;
354}
355
356
357/*
358** Try to grow the stack by at least 'n' elements. When 'raiseerror'
359** is true, raises any error; otherwise, return 0 in case of errors.
360*/
361int luaD_growstack (lua_State *L, int n, int raiseerror) {
362 int size = stacksize(L);
363 if (l_unlikely(size > MAXSTACK)) {
364 /* if stack is larger than maximum, thread is already using the
365 extra space reserved for errors, that is, thread is handling
366 a stack error; cannot grow further than that. */
367 lua_assert(stacksize(L) == ERRORSTACKSIZE);
368 if (raiseerror)
369 luaD_errerr(L); /* stack error inside message handler */
370 return 0; /* if not 'raiseerror', just signal it */
371 }
372 else if (n < MAXSTACK) { /* avoids arithmetic overflows */
373 int newsize = size + (size >> 1); /* tentative new size (size * 1.5) */
374 int needed = cast_int(L->top.p - L->stack.p) + n;
375 if (newsize > MAXSTACK) /* cannot cross the limit */
376 newsize = MAXSTACK;
377 if (newsize < needed) /* but must respect what was asked for */
378 newsize = needed;
379 if (l_likely(newsize <= MAXSTACK))
380 return luaD_reallocstack(L, newsize, raiseerror);
381 }
382 /* else stack overflow */
383 /* add extra size to be able to handle the error message */
384 luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
385 if (raiseerror)
386 luaG_runerror(L, "stack overflow");
387 return 0;
388}
389
390
391/*
392** Compute how much of the stack is being used, by computing the
393** maximum top of all call frames in the stack and the current top.
394*/
395static int stackinuse (lua_State *L) {
396 CallInfo *ci;
397 int res;
398 StkId lim = L->top.p;
399 for (ci = L->ci; ci != NULL; ci = ci->previous) {
400 if (lim < ci->top.p) lim = ci->top.p;
401 }
402 lua_assert(lim <= L->stack_last.p + EXTRA_STACK);
403 res = cast_int(lim - L->stack.p) + 1; /* part of stack in use */
404 if (res < LUA_MINSTACK)
405 res = LUA_MINSTACK; /* ensure a minimum size */
406 return res;
407}
408
409
410/*
411** If stack size is more than 3 times the current use, reduce that size
412** to twice the current use. (So, the final stack size is at most 2/3 the
413** previous size, and half of its entries are empty.)
414** As a particular case, if stack was handling a stack overflow and now
415** it is not, 'max' (limited by MAXSTACK) will be smaller than
416** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
417** will be reduced to a "regular" size.
418*/
419void luaD_shrinkstack (lua_State *L) {
420 int inuse = stackinuse(L);
421 int max = (inuse > MAXSTACK / 3) ? MAXSTACK : inuse * 3;
422 /* if thread is currently not handling a stack overflow and its
423 size is larger than maximum "reasonable" size, shrink it */
424 if (inuse <= MAXSTACK && stacksize(L) > max) {
425 int nsize = (inuse > MAXSTACK / 2) ? MAXSTACK : inuse * 2;
426 luaD_reallocstack(L, nsize, 0); /* ok if that fails */
427 }
428 else /* don't change stack */
429 condmovestack(L,(void)0,(void)0); /* (change only for debugging) */
430 luaE_shrinkCI(L); /* shrink CI list */
431}
432
433/* }================================================================== */
434
435
436/*
437** Call a hook for the given event. Make sure there is a hook to be
438** called. (Both 'L->hook' and 'L->hookmask', which trigger this
439** function, can be changed asynchronously by signals.)
440*/
441void luaD_hook (lua_State *L, int event, int line,
442 int ftransfer, int ntransfer) {
443 lua_Hook hook = L->hook;
444 if (hook && L->allowhook) { /* make sure there is a hook */
445 CallInfo *ci = L->ci;
446 ptrdiff_t top = savestack(L, L->top.p); /* preserve original 'top' */
447 ptrdiff_t ci_top = savestack(L, ci->top.p); /* idem for 'ci->top' */
448 lua_Debug ar;
449 ar.event = event;
450 ar.currentline = line;
451 ar.i_ci = ci;
452 L->transferinfo.ftransfer = ftransfer;
453 L->transferinfo.ntransfer = ntransfer;
454 if (isLua(ci) && L->top.p < ci->top.p)
455 L->top.p = ci->top.p; /* protect entire activation register */
456 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
457 if (ci->top.p < L->top.p + LUA_MINSTACK)
458 ci->top.p = L->top.p + LUA_MINSTACK;
459 L->allowhook = 0; /* cannot call hooks inside a hook */
460 ci->callstatus |= CIST_HOOKED;
461 lua_unlock(L);
462 (*hook)(L, &ar);
463 lua_lock(L);
464 lua_assert(!L->allowhook);
465 L->allowhook = 1;
466 ci->top.p = restorestack(L, ci_top);
467 L->top.p = restorestack(L, top);
468 ci->callstatus &= ~CIST_HOOKED;
469 }
470}
471
472
473/*
474** Executes a call hook for Lua functions. This function is called
475** whenever 'hookmask' is not zero, so it checks whether call hooks are
476** active.
477*/
478void luaD_hookcall (lua_State *L, CallInfo *ci) {
479 L->oldpc = 0; /* set 'oldpc' for new function */
480 if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */
481 int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
482 : LUA_HOOKCALL;
483 Proto *p = ci_func(ci)->p;
484 ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
485 luaD_hook(L, event, -1, 1, p->numparams);
486 ci->u.l.savedpc--; /* correct 'pc' */
487 }
488}
489
490
491/*
492** Executes a return hook for Lua and C functions and sets/corrects
493** 'oldpc'. (Note that this correction is needed by the line hook, so it
494** is done even when return hooks are off.)
495*/
496static void rethook (lua_State *L, CallInfo *ci, int nres) {
497 if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
498 StkId firstres = L->top.p - nres; /* index of first result */
499 int delta = 0; /* correction for vararg functions */
500 int ftransfer;
501 if (isLua(ci)) {
502 Proto *p = ci_func(ci)->p;
503 if (p->flag & PF_VAHID)
504 delta = ci->u.l.nextraargs + p->numparams + 1;
505 }
506 ci->func.p += delta; /* if vararg, back to virtual 'func' */
507 ftransfer = cast_int(firstres - ci->func.p);
508 luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
509 ci->func.p -= delta;
510 }
511 if (isLua(ci = ci->previous))
512 L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */
513}
514
515
516/*
517** Check whether 'func' has a '__call' metafield. If so, put it in the
518** stack, below original 'func', so that 'luaD_precall' can call it.
519** Raise an error if there is no '__call' metafield.
520** Bits CIST_CCMT in status count how many _call metamethods were
521** invoked and how many corresponding extra arguments were pushed.
522** (This count will be saved in the 'callstatus' of the call).
523** Raise an error if this counter overflows.
524*/
525static unsigned tryfuncTM (lua_State *L, StkId func, unsigned status) {
526 const TValue *tm;
527 StkId p;
528 tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
529 if (l_unlikely(ttisnil(tm))) /* no metamethod? */
530 luaG_callerror(L, s2v(func));
531 for (p = L->top.p; p > func; p--) /* open space for metamethod */
532 setobjs2s(L, p, p-1);
533 L->top.p++; /* stack space pre-allocated by the caller */
534 setobj2s(L, func, tm); /* metamethod is the new function to be called */
535 if ((status & MAX_CCMT) == MAX_CCMT) /* is counter full? */
536 luaG_runerror(L, "'__call' chain too long");
537 return status + (1u << CIST_CCMT); /* increment counter */
538}
539
540
541/* Generic case for 'moveresult' */
542l_sinline void genmoveresults (lua_State *L, StkId res, int nres,
543 int wanted) {
544 StkId firstresult = L->top.p - nres; /* index of first result */
545 int i;
546 if (nres > wanted) /* extra results? */
547 nres = wanted; /* don't need them */
548 for (i = 0; i < nres; i++) /* move all results to correct place */
549 setobjs2s(L, res + i, firstresult + i);
550 for (; i < wanted; i++) /* complete wanted number of results */
551 setnilvalue2s(res + i);
552 L->top.p = res + wanted; /* top points after the last result */
553}
554
555
556/*
557** Given 'nres' results at 'firstResult', move 'fwanted-1' of them
558** to 'res'. Handle most typical cases (zero results for commands,
559** one result for expressions, multiple results for tail calls/single
560** parameters) separated. The flag CIST_TBC in 'fwanted', if set,
561** forces the switch to go to the default case.
562*/
563l_sinline void moveresults (lua_State *L, StkId res, int nres,
564 l_uint32 fwanted) {
565 switch (fwanted) { /* handle typical cases separately */
566 case 0 + 1: /* no values needed */
567 L->top.p = res;
568 return;
569 case 1 + 1: /* one value needed */
570 if (nres == 0) /* no results? */
571 setnilvalue2s(res); /* adjust with nil */
572 else /* at least one result */
573 setobjs2s(L, res, L->top.p - nres); /* move it to proper place */
574 L->top.p = res + 1;
575 return;
576 case LUA_MULTRET + 1:
577 genmoveresults(L, res, nres, nres); /* we want all results */
578 break;
579 default: { /* two/more results and/or to-be-closed variables */
580 int wanted = get_nresults(fwanted);
581 if (fwanted & CIST_TBC) { /* to-be-closed variables? */
582 L->ci->u2.nres = nres;
583 L->ci->callstatus |= CIST_CLSRET; /* in case of yields */
584 res = luaF_close(L, res, CLOSEKTOP, 1);
585 L->ci->callstatus &= ~CIST_CLSRET;
586 if (L->hookmask) { /* if needed, call hook after '__close's */
587 ptrdiff_t savedres = savestack(L, res);
588 rethook(L, L->ci, nres);
589 res = restorestack(L, savedres); /* hook can move stack */
590 }
591 if (wanted == LUA_MULTRET)
592 wanted = nres; /* we want all results */
593 }
594 genmoveresults(L, res, nres, wanted);
595 break;
596 }
597 }
598}
599
600
601/*
602** Finishes a function call: calls hook if necessary, moves current
603** number of results to proper place, and returns to previous call
604** info. If function has to close variables, hook must be called after
605** that.
606*/
607void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
608 l_uint32 fwanted = ci->callstatus & (CIST_TBC | CIST_NRESULTS);
609 if (l_unlikely(L->hookmask) && !(fwanted & CIST_TBC))
610 rethook(L, ci, nres);
611 /* move results to proper place */
612 moveresults(L, ci->func.p, nres, fwanted);
613 /* function cannot be in any of these cases when returning */
614 lua_assert(!(ci->callstatus &
615 (CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_CLSRET)));
616 L->ci = ci->previous; /* back to caller (after closing variables) */
617}
618
619
620
621#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L, 1))
622
623
624/*
625** Allocate and initialize CallInfo structure. At this point, the
626** only valid fields in the call status are number of results,
627** CIST_C (if it's a C function), and number of extra arguments.
628** (All these bit-fields fit in 16-bit values.)
629*/
630l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, unsigned status,
631 StkId top) {
632 CallInfo *ci = L->ci = next_ci(L); /* new frame */
633 ci->func.p = func;
634 lua_assert((status & ~(CIST_NRESULTS | CIST_C | MAX_CCMT)) == 0);
635 ci->callstatus = status;
636 ci->top.p = top;
637 return ci;
638}
639
640
641/*
642** precall for C functions
643*/
644l_sinline int precallC (lua_State *L, StkId func, unsigned status,
645 lua_CFunction f) {
646 int n; /* number of returns */
647 CallInfo *ci;
648 checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
649 L->ci = ci = prepCallInfo(L, func, status | CIST_C,
650 L->top.p + LUA_MINSTACK);
651 lua_assert(ci->top.p <= L->stack_last.p);
652 if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
653 int narg = cast_int(L->top.p - func) - 1;
654 luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
655 }
656 lua_unlock(L);
657 n = (*f)(L); /* do the actual call */
658 lua_lock(L);
659 api_checknelems(L, n);
660 luaD_poscall(L, ci, n);
661 return n;
662}
663
664
665/*
666** Prepare a function for a tail call, building its call info on top
667** of the current call info. 'narg1' is the number of arguments plus 1
668** (so that it includes the function itself). Return the number of
669** results, if it was a C function, or -1 for a Lua function.
670*/
671int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
672 int narg1, int delta) {
673 unsigned status = LUA_MULTRET + 1;
674 retry:
675 switch (ttypetag(s2v(func))) {
676 case LUA_VCCL: /* C closure */
677 return precallC(L, func, status, clCvalue(s2v(func))->f);
678 case LUA_VLCF: /* light C function */
679 return precallC(L, func, status, fvalue(s2v(func)));
680 case LUA_VLCL: { /* Lua function */
681 Proto *p = clLvalue(s2v(func))->p;
682 int fsize = p->maxstacksize; /* frame size */
683 int nfixparams = p->numparams;
684 int i;
685 checkstackp(L, fsize - delta, func);
686 ci->func.p -= delta; /* restore 'func' (if vararg) */
687 for (i = 0; i < narg1; i++) /* move down function and arguments */
688 setobjs2s(L, ci->func.p + i, func + i);
689 func = ci->func.p; /* moved-down function */
690 for (; narg1 <= nfixparams; narg1++)
691 setnilvalue2s(func + narg1); /* complete missing arguments */
692 ci->top.p = func + 1 + fsize; /* top for new function */
693 lua_assert(ci->top.p <= L->stack_last.p);
694 ci->u.l.savedpc = p->code; /* starting point */
695 ci->callstatus |= CIST_TAIL;
696 L->top.p = func + narg1; /* set top */
697 return -1;
698 }
699 default: { /* not a function */
700 checkstackp(L, 1, func); /* space for metamethod */
701 status = tryfuncTM(L, func, status); /* try '__call' metamethod */
702 narg1++;
703 goto retry; /* try again */
704 }
705 }
706}
707
708
709/*
710** Prepares the call to a function (C or Lua). For C functions, also do
711** the call. The function to be called is at '*func'. The arguments
712** are on the stack, right after the function. Returns the CallInfo
713** to be executed, if it was a Lua function. Otherwise (a C function)
714** returns NULL, with all the results on the stack, starting at the
715** original function position.
716*/
717CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
718 unsigned status = cast_uint(nresults + 1);
719 lua_assert(status <= MAXRESULTS + 1);
720 retry:
721 switch (ttypetag(s2v(func))) {
722 case LUA_VCCL: /* C closure */
723 precallC(L, func, status, clCvalue(s2v(func))->f);
724 return NULL;
725 case LUA_VLCF: /* light C function */
726 precallC(L, func, status, fvalue(s2v(func)));
727 return NULL;
728 case LUA_VLCL: { /* Lua function */
729 CallInfo *ci;
730 Proto *p = clLvalue(s2v(func))->p;
731 int narg = cast_int(L->top.p - func) - 1; /* number of real arguments */
732 int nfixparams = p->numparams;
733 int fsize = p->maxstacksize; /* frame size */
734 checkstackp(L, fsize, func);
735 L->ci = ci = prepCallInfo(L, func, status, func + 1 + fsize);
736 ci->u.l.savedpc = p->code; /* starting point */
737 for (; narg < nfixparams; narg++)
738 setnilvalue2s(L->top.p++); /* complete missing arguments */
739 lua_assert(ci->top.p <= L->stack_last.p);
740 return ci;
741 }
742 default: { /* not a function */
743 checkstackp(L, 1, func); /* space for metamethod */
744 status = tryfuncTM(L, func, status); /* try '__call' metamethod */
745 goto retry; /* try again with metamethod */
746 }
747 }
748}
749
750
751/*
752** Call a function (C or Lua) through C. 'inc' can be 1 (increment
753** number of recursive invocations in the C stack) or nyci (the same
754** plus increment number of non-yieldable calls).
755** This function can be called with some use of EXTRA_STACK, so it should
756** check the stack before doing anything else. 'luaD_precall' already
757** does that.
758*/
759l_sinline void ccall (lua_State *L, StkId func, int nResults, l_uint32 inc) {
760 CallInfo *ci;
761 L->nCcalls += inc;
762 if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS)) {
763 checkstackp(L, 0, func); /* free any use of EXTRA_STACK */
764 luaE_checkcstack(L);
765 }
766 if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
767 ci->callstatus |= CIST_FRESH; /* mark that it is a "fresh" execute */
768 luaV_execute(L, ci); /* call it */
769 }
770 L->nCcalls -= inc;
771}
772
773
774/*
775** External interface for 'ccall'
776*/
777void luaD_call (lua_State *L, StkId func, int nResults) {
778 ccall(L, func, nResults, 1);
779}
780
781
782/*
783** Similar to 'luaD_call', but does not allow yields during the call.
784*/
785void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
786 ccall(L, func, nResults, nyci);
787}
788
789
790/*
791** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
792** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
793** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
794** If a '__close' method yields here, eventually control will be back
795** to 'finishCcall' (when that '__close' method finally returns) and
796** 'finishpcallk' will run again and close any still pending '__close'
797** methods. Similarly, if a '__close' method errs, 'precover' calls
798** 'unroll' which calls ''finishCcall' and we are back here again, to
799** close any pending '__close' methods.
800** Note that, up to the call to 'luaF_close', the corresponding
801** 'CallInfo' is not modified, so that this repeated run works like the
802** first one (except that it has at least one less '__close' to do). In
803** particular, field CIST_RECST preserves the error status across these
804** multiple runs, changing only if there is a new error.
805*/
806static TStatus finishpcallk (lua_State *L, CallInfo *ci) {
807 TStatus status = getcistrecst(ci); /* get original status */
808 if (l_likely(status == LUA_OK)) /* no error? */
809 status = LUA_YIELD; /* was interrupted by an yield */
810 else { /* error */
811 StkId func = restorestack(L, ci->u2.funcidx);
812 L->allowhook = getoah(ci); /* restore 'allowhook' */
813 func = luaF_close(L, func, status, 1); /* can yield or raise an error */
814 luaD_seterrorobj(L, status, func);
815 luaD_shrinkstack(L); /* restore stack size in case of overflow */
816 setcistrecst(ci, LUA_OK); /* clear original status */
817 }
818 ci->callstatus &= ~CIST_YPCALL;
819 L->errfunc = ci->u.c.old_errfunc;
820 /* if it is here, there were errors or yields; unlike 'lua_pcallk',
821 do not change status */
822 return status;
823}
824
825
826/*
827** Completes the execution of a C function interrupted by an yield.
828** The interruption must have happened while the function was either
829** closing its tbc variables in 'moveresults' or executing
830** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
831** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
832** finishes the interrupted execution of 'lua_pcallk'. After that, it
833** calls the continuation of the interrupted function and finally it
834** completes the job of the 'luaD_call' that called the function. In
835** the call to 'adjustresults', we do not know the number of results
836** of the function called by 'lua_callk'/'lua_pcallk', so we are
837** conservative and use LUA_MULTRET (always adjust).
838*/
839static void finishCcall (lua_State *L, CallInfo *ci) {
840 int n; /* actual number of results from C function */
841 if (ci->callstatus & CIST_CLSRET) { /* was closing TBC variable? */
842 lua_assert(ci->callstatus & CIST_TBC);
843 n = ci->u2.nres; /* just redo 'luaD_poscall' */
844 /* don't need to reset CIST_CLSRET, as it will be set again anyway */
845 }
846 else {
847 TStatus status = LUA_YIELD; /* default if there were no errors */
848 lua_KFunction kf = ci->u.c.k; /* continuation function */
849 /* must have a continuation and must be able to call it */
850 lua_assert(kf != NULL && yieldable(L));
851 if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
852 status = finishpcallk(L, ci); /* finish it */
853 adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
854 lua_unlock(L);
855 n = (*kf)(L, APIstatus(status), ci->u.c.ctx); /* call continuation */
856 lua_lock(L);
857 api_checknelems(L, n);
858 }
859 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
860}
861
862
863/*
864** Executes "full continuation" (everything in the stack) of a
865** previously interrupted coroutine until the stack is empty (or another
866** interruption long-jumps out of the loop).
867*/
868static void unroll (lua_State *L, void *ud) {
869 CallInfo *ci;
870 UNUSED(ud);
871 while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
872 if (!isLua(ci)) /* C function? */
873 finishCcall(L, ci); /* complete its execution */
874 else { /* Lua function */
875 luaV_finishOp(L); /* finish interrupted instruction */
876 luaV_execute(L, ci); /* execute down to higher C 'boundary' */
877 }
878 }
879}
880
881
882/*
883** Try to find a suspended protected call (a "recover point") for the
884** given thread.
885*/
886static CallInfo *findpcall (lua_State *L) {
887 CallInfo *ci;
888 for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
889 if (ci->callstatus & CIST_YPCALL)
890 return ci;
891 }
892 return NULL; /* no pending pcall */
893}
894
895
896/*
897** Signal an error in the call to 'lua_resume', not in the execution
898** of the coroutine itself. (Such errors should not be handled by any
899** coroutine error handler and should not kill the coroutine.)
900*/
901static int resume_error (lua_State *L, const char *msg, int narg) {
902 api_checkpop(L, narg);
903 L->top.p -= narg; /* remove args from the stack */
904 setsvalue2s(L, L->top.p, luaS_new(L, msg)); /* push error message */
905 api_incr_top(L);
906 lua_unlock(L);
907 return LUA_ERRRUN;
908}
909
910
911/*
912** Do the work for 'lua_resume' in protected mode. Most of the work
913** depends on the status of the coroutine: initial state, suspended
914** inside a hook, or regularly suspended (optionally with a continuation
915** function), plus erroneous cases: non-suspended coroutine or dead
916** coroutine.
917*/
918static void resume (lua_State *L, void *ud) {
919 int n = *(cast(int*, ud)); /* number of arguments */
920 StkId firstArg = L->top.p - n; /* first argument */
921 CallInfo *ci = L->ci;
922 if (L->status == LUA_OK) /* starting a coroutine? */
923 ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */
924 else { /* resuming from previous yield */
925 lua_assert(L->status == LUA_YIELD);
926 L->status = LUA_OK; /* mark that it is running (again) */
927 if (isLua(ci)) { /* yielded inside a hook? */
928 /* undo increment made by 'luaG_traceexec': instruction was not
929 executed yet */
930 lua_assert(ci->callstatus & CIST_HOOKYIELD);
931 ci->u.l.savedpc--;
932 L->top.p = firstArg; /* discard arguments */
933 luaV_execute(L, ci); /* just continue running Lua code */
934 }
935 else { /* 'common' yield */
936 if (ci->u.c.k != NULL) { /* does it have a continuation function? */
937 lua_unlock(L);
938 n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
939 lua_lock(L);
940 api_checknelems(L, n);
941 }
942 luaD_poscall(L, ci, n); /* finish 'luaD_call' */
943 }
944 unroll(L, NULL); /* run continuation */
945 }
946}
947
948
949/*
950** Unrolls a coroutine in protected mode while there are recoverable
951** errors, that is, errors inside a protected call. (Any error
952** interrupts 'unroll', and this loop protects it again so it can
953** continue.) Stops with a normal end (status == LUA_OK), an yield
954** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
955** find a recover point).
956*/
957static TStatus precover (lua_State *L, TStatus status) {
958 CallInfo *ci;
959 while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
960 L->ci = ci; /* go down to recovery functions */
961 setcistrecst(ci, status); /* status to finish 'pcall' */
962 status = luaD_rawrunprotected(L, unroll, NULL);
963 }
964 return status;
965}
966
967
968LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
969 int *nresults) {
970 TStatus status;
971 lua_lock(L);
972 if (L->status == LUA_OK) { /* may be starting a coroutine */
973 if (L->ci != &L->base_ci) /* not in base level? */
974 return resume_error(L, "cannot resume non-suspended coroutine", nargs);
975 else if (L->top.p - (L->ci->func.p + 1) == nargs) /* no function? */
976 return resume_error(L, "cannot resume dead coroutine", nargs);
977 }
978 else if (L->status != LUA_YIELD) /* ended with errors? */
979 return resume_error(L, "cannot resume dead coroutine", nargs);
980 L->nCcalls = (from) ? getCcalls(from) : 0;
981 if (getCcalls(L) >= LUAI_MAXCCALLS)
982 return resume_error(L, "C stack overflow", nargs);
983 L->nCcalls++;
984 luai_userstateresume(L, nargs);
985 api_checkpop(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
986 status = luaD_rawrunprotected(L, resume, &nargs);
987 /* continue running after recoverable errors */
988 status = precover(L, status);
989 if (l_likely(!errorstatus(status)))
990 lua_assert(status == L->status); /* normal end or yield */
991 else { /* unrecoverable error */
992 L->status = status; /* mark thread as 'dead' */
993 luaD_seterrorobj(L, status, L->top.p); /* push error message */
994 L->ci->top.p = L->top.p;
995 }
996 *nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
997 : cast_int(L->top.p - (L->ci->func.p + 1));
998 lua_unlock(L);
999 return APIstatus(status);
1000}
1001
1002
1003LUA_API int lua_isyieldable (lua_State *L) {
1004 return yieldable(L);
1005}
1006
1007
1008LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
1009 lua_KFunction k) {
1010 CallInfo *ci;
1011 luai_userstateyield(L, nresults);
1012 lua_lock(L);
1013 ci = L->ci;
1014 api_checkpop(L, nresults);
1015 if (l_unlikely(!yieldable(L))) {
1016 if (L != mainthread(G(L)))
1017 luaG_runerror(L, "attempt to yield across a C-call boundary");
1018 else
1019 luaG_runerror(L, "attempt to yield from outside a coroutine");
1020 }
1021 L->status = LUA_YIELD;
1022 ci->u2.nyield = nresults; /* save number of results */
1023 if (isLua(ci)) { /* inside a hook? */
1024 lua_assert(!isLuacode(ci));
1025 api_check(L, nresults == 0, "hooks cannot yield values");
1026 api_check(L, k == NULL, "hooks cannot continue after yielding");
1027 }
1028 else {
1029 if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
1030 ci->u.c.ctx = ctx; /* save context */
1031 luaD_throw(L, LUA_YIELD);
1032 }
1033 lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
1034 lua_unlock(L);
1035 return 0; /* return to 'luaD_hook' */
1036}
1037
1038
1039/*
1040** Auxiliary structure to call 'luaF_close' in protected mode.
1041*/
1042struct CloseP {
1043 StkId level;
1044 TStatus status;
1045};
1046
1047
1048/*
1049** Auxiliary function to call 'luaF_close' in protected mode.
1050*/
1051static void closepaux (lua_State *L, void *ud) {
1052 struct CloseP *pcl = cast(struct CloseP *, ud);
1053 luaF_close(L, pcl->level, pcl->status, 0);
1054}
1055
1056
1057/*
1058** Calls 'luaF_close' in protected mode. Return the original status
1059** or, in case of errors, the new status.
1060*/
1061TStatus luaD_closeprotected (lua_State *L, ptrdiff_t level, TStatus status) {
1062 CallInfo *old_ci = L->ci;
1063 lu_byte old_allowhooks = L->allowhook;
1064 for (;;) { /* keep closing upvalues until no more errors */
1065 struct CloseP pcl;
1066 pcl.level = restorestack(L, level); pcl.status = status;
1067 status = luaD_rawrunprotected(L, &closepaux, &pcl);
1068 if (l_likely(status == LUA_OK)) /* no more errors? */
1069 return pcl.status;
1070 else { /* an error occurred; restore saved state and repeat */
1071 L->ci = old_ci;
1072 L->allowhook = old_allowhooks;
1073 }
1074 }
1075}
1076
1077
1078/*
1079** Call the C function 'func' in protected mode, restoring basic
1080** thread information ('allowhook', etc.) and in particular
1081** its stack level in case of errors.
1082*/
1083TStatus luaD_pcall (lua_State *L, Pfunc func, void *u, ptrdiff_t old_top,
1084 ptrdiff_t ef) {
1085 TStatus status;
1086 CallInfo *old_ci = L->ci;
1087 lu_byte old_allowhooks = L->allowhook;
1088 ptrdiff_t old_errfunc = L->errfunc;
1089 L->errfunc = ef;
1090 status = luaD_rawrunprotected(L, func, u);
1091 if (l_unlikely(status != LUA_OK)) { /* an error occurred? */
1092 L->ci = old_ci;
1093 L->allowhook = old_allowhooks;
1094 status = luaD_closeprotected(L, old_top, status);
1095 luaD_seterrorobj(L, status, restorestack(L, old_top));
1096 luaD_shrinkstack(L); /* restore stack size in case of overflow */
1097 }
1098 L->errfunc = old_errfunc;
1099 return status;
1100}
1101
1102
1103
1104/*
1105** Execute a protected parser.
1106*/
1107struct SParser { /* data to 'f_parser' */
1108 ZIO *z;
1109 Mbuffer buff; /* dynamic structure used by the scanner */
1110 Dyndata dyd; /* dynamic structures used by the parser */
1111 const char *mode;
1112 const char *name;
1113};
1114
1115
1116static void checkmode (lua_State *L, const char *mode, const char *x) {
1117 if (strchr(mode, x[0]) == NULL) {
1118 luaO_pushfstring(L,
1119 "attempt to load a %s chunk (mode is '%s')", x, mode);
1120 luaD_throw(L, LUA_ERRSYNTAX);
1121 }
1122}
1123
1124
1125/*
1126** Before the first call to the reader function, Lua reserves a slot
1127** with a table for anchoring stuff.
1128*/
1129static void f_parser (lua_State *L, void *ud) {
1130 LClosure *cl;
1131 struct SParser *p = cast(struct SParser *, ud);
1132 const char *mode = p->mode ? p->mode : "bt";
1133 int c;
1134 Table *anchor;
1135 ptrdiff_t otop = savestack(L, L->top.p); /* original top */
1136 luaD_checkstack(L, 2);
1137 anchor = luaH_new(L); /* create the anchor table */
1138 sethvalue2s(L, L->top.p++, anchor); /* anchor the anchor table */
1139 c = zgetc(p->z); /* read first character */
1140 if (c == LUA_SIGNATURE[0]) {
1141 int fixed = 0;
1142 if (strchr(mode, 'B') != NULL)
1143 fixed = 1;
1144 else
1145 checkmode(L, mode, "binary");
1146 cl = luaU_undump(L, p->z, anchor, p->name, fixed);
1147 }
1148 else {
1149 checkmode(L, mode, "text");
1150 cl = luaY_parser(L, p->z, anchor, &p->buff, &p->dyd, p->name, c);
1151 }
1152 L->top.p = restorestack(L, otop); /* restore stack */
1153 setclLvalue2s(L, L->top.p++, cl); /* push closure */
1154 lua_assert(cl->nupvalues == cl->p->sizeupvalues);
1155 luaF_initupvals(L, cl);
1156}
1157
1158
1159/*
1160** Anchor an object in a table in the stack. First, anchor the object
1161** temporarily in the stack, as luaH_set may call an emergency GC.
1162** Then, add it in the table with itself as its key.
1163*/
1164void luaD_anchorobj (lua_State *L, Table *anchor, GCObject *obj) {
1165 setgcovalue(L, s2v(L->top.p++), obj); /* temporary anchor in the stack */
1166 luaH_set(L, anchor, s2v(L->top.p - 1), s2v(L->top.p - 1));
1167 /* Because this is a new key, luaH_set will call the GC barrier, so
1168 we don't need to call the barrier again here */
1169 L->top.p--;
1170}
1171
1172
1173TStatus luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
1174 const char *mode) {
1175 struct SParser p;
1176 TStatus status;
1177 incnny(L); /* cannot yield during parsing */
1178 p.z = z; p.name = name; p.mode = mode;
1179 p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
1180 p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
1181 p.dyd.label.arr = NULL; p.dyd.label.size = 0;
1182 luaZ_initbuffer(L, &p.buff);
1183 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top.p), L->errfunc);
1184 luaZ_freebuffer(L, &p.buff);
1185 luaM_freearray(L, p.dyd.actvar.arr, cast_sizet(p.dyd.actvar.size));
1186 luaM_freearray(L, p.dyd.gt.arr, cast_sizet(p.dyd.gt.size));
1187 luaM_freearray(L, p.dyd.label.arr, cast_sizet(p.dyd.label.size));
1188 decnny(L);
1189 return status;
1190}
1191
1192