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