1 /* $NetBSD: ldebug.c,v 1.14 2023/06/08 21:12:08 nikita Exp $ */
2
3 /*
4 ** Id: ldebug.c
5 ** Debug Interface
6 ** See Copyright Notice in lua.h
7 */
8
9 #define ldebug_c
10 #define LUA_CORE
11
12 #include "lprefix.h"
13
14
15 #include <stdarg.h>
16 #ifndef _KERNEL
17 #include <stddef.h>
18 #include <string.h>
19 #endif /* _KERNEL */
20
21 #include "lua.h"
22
23 #include "lapi.h"
24 #include "lcode.h"
25 #include "ldebug.h"
26 #include "ldo.h"
27 #include "lfunc.h"
28 #include "lobject.h"
29 #include "lopcodes.h"
30 #include "lstate.h"
31 #include "lstring.h"
32 #include "ltable.h"
33 #include "ltm.h"
34 #include "lvm.h"
35
36
37
38 #define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_VCCL)
39
40
41 static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
42 const char **name);
43
44
currentpc(CallInfo * ci)45 static int currentpc (CallInfo *ci) {
46 lua_assert(isLua(ci));
47 return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
48 }
49
50
51 /*
52 ** Get a "base line" to find the line corresponding to an instruction.
53 ** Base lines are regularly placed at MAXIWTHABS intervals, so usually
54 ** an integer division gets the right place. When the source file has
55 ** large sequences of empty/comment lines, it may need extra entries,
56 ** so the original estimate needs a correction.
57 ** If the original estimate is -1, the initial 'if' ensures that the
58 ** 'while' will run at least once.
59 ** The assertion that the estimate is a lower bound for the correct base
60 ** is valid as long as the debug info has been generated with the same
61 ** value for MAXIWTHABS or smaller. (Previous releases use a little
62 ** smaller value.)
63 */
getbaseline(const Proto * f,int pc,int * basepc)64 static int getbaseline (const Proto *f, int pc, int *basepc) {
65 if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) {
66 *basepc = -1; /* start from the beginning */
67 return f->linedefined;
68 }
69 else {
70 int i = cast_uint(pc) / MAXIWTHABS - 1; /* get an estimate */
71 /* estimate must be a lower bound of the correct base */
72 lua_assert(i < 0 ||
73 (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc));
74 while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc)
75 i++; /* low estimate; adjust it */
76 *basepc = f->abslineinfo[i].pc;
77 return f->abslineinfo[i].line;
78 }
79 }
80
81
82 /*
83 ** Get the line corresponding to instruction 'pc' in function 'f';
84 ** first gets a base line and from there does the increments until
85 ** the desired instruction.
86 */
luaG_getfuncline(const Proto * f,int pc)87 int luaG_getfuncline (const Proto *f, int pc) {
88 if (f->lineinfo == NULL) /* no debug information? */
89 return -1;
90 else {
91 int basepc;
92 int baseline = getbaseline(f, pc, &basepc);
93 while (basepc++ < pc) { /* walk until given instruction */
94 lua_assert(f->lineinfo[basepc] != ABSLINEINFO);
95 baseline += f->lineinfo[basepc]; /* correct line */
96 }
97 return baseline;
98 }
99 }
100
101
getcurrentline(CallInfo * ci)102 static int getcurrentline (CallInfo *ci) {
103 return luaG_getfuncline(ci_func(ci)->p, currentpc(ci));
104 }
105
106
107 /*
108 ** Set 'trap' for all active Lua frames.
109 ** This function can be called during a signal, under "reasonable"
110 ** assumptions. A new 'ci' is completely linked in the list before it
111 ** becomes part of the "active" list, and we assume that pointers are
112 ** atomic; see comment in next function.
113 ** (A compiler doing interprocedural optimizations could, theoretically,
114 ** reorder memory writes in such a way that the list could be
115 ** temporarily broken while inserting a new element. We simply assume it
116 ** has no good reasons to do that.)
117 */
settraps(CallInfo * ci)118 static void settraps (CallInfo *ci) {
119 for (; ci != NULL; ci = ci->previous)
120 if (isLua(ci))
121 ci->u.l.trap = 1;
122 }
123
124
125 /*
126 ** This function can be called during a signal, under "reasonable"
127 ** assumptions.
128 ** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount')
129 ** are for debug only, and it is no problem if they get arbitrary
130 ** values (causes at most one wrong hook call). 'hookmask' is an atomic
131 ** value. We assume that pointers are atomic too (e.g., gcc ensures that
132 ** for all platforms where it runs). Moreover, 'hook' is always checked
133 ** before being called (see 'luaD_hook').
134 */
lua_sethook(lua_State * L,lua_Hook func,int mask,int count)135 LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
136 if (func == NULL || mask == 0) { /* turn off hooks? */
137 mask = 0;
138 func = NULL;
139 }
140 L->hook = func;
141 L->basehookcount = count;
142 resethookcount(L);
143 L->hookmask = cast_byte(mask);
144 if (mask)
145 settraps(L->ci); /* to trace inside 'luaV_execute' */
146 }
147
148
lua_gethook(lua_State * L)149 LUA_API lua_Hook lua_gethook (lua_State *L) {
150 return L->hook;
151 }
152
153
lua_gethookmask(lua_State * L)154 LUA_API int lua_gethookmask (lua_State *L) {
155 return L->hookmask;
156 }
157
158
lua_gethookcount(lua_State * L)159 LUA_API int lua_gethookcount (lua_State *L) {
160 return L->basehookcount;
161 }
162
163
lua_getstack(lua_State * L,int level,lua_Debug * ar)164 LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
165 int status;
166 CallInfo *ci;
167 if (level < 0) return 0; /* invalid (negative) level */
168 lua_lock(L);
169 for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)
170 level--;
171 if (level == 0 && ci != &L->base_ci) { /* level found? */
172 status = 1;
173 ar->i_ci = ci;
174 }
175 else status = 0; /* no such level */
176 lua_unlock(L);
177 return status;
178 }
179
180
upvalname(const Proto * p,int uv)181 static const char *upvalname (const Proto *p, int uv) {
182 TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
183 if (s == NULL) return "?";
184 else return getstr(s);
185 }
186
187
findvararg(CallInfo * ci,int n,StkId * pos)188 static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
189 if (clLvalue(s2v(ci->func.p))->p->is_vararg) {
190 int nextra = ci->u.l.nextraargs;
191 if (n >= -nextra) { /* 'n' is negative */
192 *pos = ci->func.p - nextra - (n + 1);
193 return "(vararg)"; /* generic name for any vararg */
194 }
195 }
196 return NULL; /* no such vararg */
197 }
198
199
luaG_findlocal(lua_State * L,CallInfo * ci,int n,StkId * pos)200 const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) {
201 StkId base = ci->func.p + 1;
202 const char *name = NULL;
203 if (isLua(ci)) {
204 if (n < 0) /* access to vararg values? */
205 return findvararg(ci, n, pos);
206 else
207 name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
208 }
209 if (name == NULL) { /* no 'standard' name? */
210 StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p;
211 if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */
212 /* generic name for any valid slot */
213 name = isLua(ci) ? "(temporary)" : "(C temporary)";
214 }
215 else
216 return NULL; /* no name */
217 }
218 if (pos)
219 *pos = base + (n - 1);
220 return name;
221 }
222
223
lua_getlocal(lua_State * L,const lua_Debug * ar,int n)224 LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
225 const char *name;
226 lua_lock(L);
227 if (ar == NULL) { /* information about non-active function? */
228 if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */
229 name = NULL;
230 else /* consider live variables at function start (parameters) */
231 name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0);
232 }
233 else { /* active function; get information through 'ar' */
234 StkId pos = NULL; /* to avoid warnings */
235 name = luaG_findlocal(L, ar->i_ci, n, &pos);
236 if (name) {
237 setobjs2s(L, L->top.p, pos);
238 api_incr_top(L);
239 }
240 }
241 lua_unlock(L);
242 return name;
243 }
244
245
lua_setlocal(lua_State * L,const lua_Debug * ar,int n)246 LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
247 StkId pos = NULL; /* to avoid warnings */
248 const char *name;
249 lua_lock(L);
250 name = luaG_findlocal(L, ar->i_ci, n, &pos);
251 if (name) {
252 setobjs2s(L, pos, L->top.p - 1);
253 L->top.p--; /* pop value */
254 }
255 lua_unlock(L);
256 return name;
257 }
258
259
funcinfo(lua_Debug * ar,Closure * cl)260 static void funcinfo (lua_Debug *ar, Closure *cl) {
261 if (noLuaClosure(cl)) {
262 ar->source = "=[C]";
263 ar->srclen = LL("=[C]");
264 ar->linedefined = -1;
265 ar->lastlinedefined = -1;
266 ar->what = "C";
267 }
268 else {
269 const Proto *p = cl->l.p;
270 if (p->source) {
271 ar->source = getstr(p->source);
272 ar->srclen = tsslen(p->source);
273 }
274 else {
275 ar->source = "=?";
276 ar->srclen = LL("=?");
277 }
278 ar->linedefined = p->linedefined;
279 ar->lastlinedefined = p->lastlinedefined;
280 ar->what = (ar->linedefined == 0) ? "main" : "Lua";
281 }
282 luaO_chunkid(ar->short_src, ar->source, ar->srclen);
283 }
284
285
nextline(const Proto * p,int currentline,int pc)286 static int nextline (const Proto *p, int currentline, int pc) {
287 if (p->lineinfo[pc] != ABSLINEINFO)
288 return currentline + p->lineinfo[pc];
289 else
290 return luaG_getfuncline(p, pc);
291 }
292
293
collectvalidlines(lua_State * L,Closure * f)294 static void collectvalidlines (lua_State *L, Closure *f) {
295 if (noLuaClosure(f)) {
296 setnilvalue(s2v(L->top.p));
297 api_incr_top(L);
298 }
299 else {
300 int i;
301 TValue v;
302 const Proto *p = f->l.p;
303 int currentline = p->linedefined;
304 Table *t = luaH_new(L); /* new table to store active lines */
305 sethvalue2s(L, L->top.p, t); /* push it on stack */
306 api_incr_top(L);
307 setbtvalue(&v); /* boolean 'true' to be the value of all indices */
308 if (!p->is_vararg) /* regular function? */
309 i = 0; /* consider all instructions */
310 else { /* vararg function */
311 lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP);
312 currentline = nextline(p, currentline, 0);
313 i = 1; /* skip first instruction (OP_VARARGPREP) */
314 }
315 for (; i < p->sizelineinfo; i++) { /* for each instruction */
316 currentline = nextline(p, currentline, i); /* get its line */
317 luaH_setint(L, t, currentline, &v); /* table[line] = true */
318 }
319 }
320 }
321
322
getfuncname(lua_State * L,CallInfo * ci,const char ** name)323 static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
324 /* calling function is a known function? */
325 if (ci != NULL && !(ci->callstatus & CIST_TAIL))
326 return funcnamefromcall(L, ci->previous, name);
327 else return NULL; /* no way to find a name */
328 }
329
330
auxgetinfo(lua_State * L,const char * what,lua_Debug * ar,Closure * f,CallInfo * ci)331 static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
332 Closure *f, CallInfo *ci) {
333 int status = 1;
334 for (; *what; what++) {
335 switch (*what) {
336 case 'S': {
337 funcinfo(ar, f);
338 break;
339 }
340 case 'l': {
341 ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1;
342 break;
343 }
344 case 'u': {
345 ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
346 if (noLuaClosure(f)) {
347 ar->isvararg = 1;
348 ar->nparams = 0;
349 }
350 else {
351 ar->isvararg = f->l.p->is_vararg;
352 ar->nparams = f->l.p->numparams;
353 }
354 break;
355 }
356 case 't': {
357 ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0;
358 break;
359 }
360 case 'n': {
361 ar->namewhat = getfuncname(L, ci, &ar->name);
362 if (ar->namewhat == NULL) {
363 ar->namewhat = ""; /* not found */
364 ar->name = NULL;
365 }
366 break;
367 }
368 case 'r': {
369 if (ci == NULL || !(ci->callstatus & CIST_TRAN))
370 ar->ftransfer = ar->ntransfer = 0;
371 else {
372 ar->ftransfer = ci->u2.transferinfo.ftransfer;
373 ar->ntransfer = ci->u2.transferinfo.ntransfer;
374 }
375 break;
376 }
377 case 'L':
378 case 'f': /* handled by lua_getinfo */
379 break;
380 default: status = 0; /* invalid option */
381 }
382 }
383 return status;
384 }
385
386
lua_getinfo(lua_State * L,const char * what,lua_Debug * ar)387 LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
388 int status;
389 Closure *cl;
390 CallInfo *ci;
391 TValue *func;
392 lua_lock(L);
393 if (*what == '>') {
394 ci = NULL;
395 func = s2v(L->top.p - 1);
396 api_check(L, ttisfunction(func), "function expected");
397 what++; /* skip the '>' */
398 L->top.p--; /* pop function */
399 }
400 else {
401 ci = ar->i_ci;
402 func = s2v(ci->func.p);
403 lua_assert(ttisfunction(func));
404 }
405 cl = ttisclosure(func) ? clvalue(func) : NULL;
406 status = auxgetinfo(L, what, ar, cl, ci);
407 if (strchr(what, 'f')) {
408 setobj2s(L, L->top.p, func);
409 api_incr_top(L);
410 }
411 if (strchr(what, 'L'))
412 collectvalidlines(L, cl);
413 lua_unlock(L);
414 return status;
415 }
416
417
418 /*
419 ** {======================================================
420 ** Symbolic Execution
421 ** =======================================================
422 */
423
424 static const char *getobjname (const Proto *p, int lastpc, int reg,
425 const char **name);
426
427
428 /*
429 ** Find a "name" for the constant 'c'.
430 */
kname(const Proto * p,int c,const char ** name)431 static void kname (const Proto *p, int c, const char **name) {
432 TValue *kvalue = &p->k[c];
433 *name = (ttisstring(kvalue)) ? svalue(kvalue) : "?";
434 }
435
436
437 /*
438 ** Find a "name" for the register 'c'.
439 */
rname(const Proto * p,int pc,int c,const char ** name)440 static void rname (const Proto *p, int pc, int c, const char **name) {
441 const char *what = getobjname(p, pc, c, name); /* search for 'c' */
442 if (!(what && *what == 'c')) /* did not find a constant name? */
443 *name = "?";
444 }
445
446
447 /*
448 ** Find a "name" for a 'C' value in an RK instruction.
449 */
rkname(const Proto * p,int pc,Instruction i,const char ** name)450 static void rkname (const Proto *p, int pc, Instruction i, const char **name) {
451 int c = GETARG_C(i); /* key index */
452 if (GETARG_k(i)) /* is 'c' a constant? */
453 kname(p, c, name);
454 else /* 'c' is a register */
455 rname(p, pc, c, name);
456 }
457
458
filterpc(int pc,int jmptarget)459 static int filterpc (int pc, int jmptarget) {
460 if (pc < jmptarget) /* is code conditional (inside a jump)? */
461 return -1; /* cannot know who sets that register */
462 else return pc; /* current position sets that register */
463 }
464
465
466 /*
467 ** Try to find last instruction before 'lastpc' that modified register 'reg'.
468 */
findsetreg(const Proto * p,int lastpc,int reg)469 static int findsetreg (const Proto *p, int lastpc, int reg) {
470 int pc;
471 int setreg = -1; /* keep last instruction that changed 'reg' */
472 int jmptarget = 0; /* any code before this address is conditional */
473 if (testMMMode(GET_OPCODE(p->code[lastpc])))
474 lastpc--; /* previous instruction was not actually executed */
475 for (pc = 0; pc < lastpc; pc++) {
476 Instruction i = p->code[pc];
477 OpCode op = GET_OPCODE(i);
478 int a = GETARG_A(i);
479 int change; /* true if current instruction changed 'reg' */
480 switch (op) {
481 case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */
482 int b = GETARG_B(i);
483 change = (a <= reg && reg <= a + b);
484 break;
485 }
486 case OP_TFORCALL: { /* affect all regs above its base */
487 change = (reg >= a + 2);
488 break;
489 }
490 case OP_CALL:
491 case OP_TAILCALL: { /* affect all registers above base */
492 change = (reg >= a);
493 break;
494 }
495 case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */
496 int b = GETARG_sJ(i);
497 int dest = pc + 1 + b;
498 /* jump does not skip 'lastpc' and is larger than current one? */
499 if (dest <= lastpc && dest > jmptarget)
500 jmptarget = dest; /* update 'jmptarget' */
501 change = 0;
502 break;
503 }
504 default: /* any instruction that sets A */
505 change = (testAMode(op) && reg == a);
506 break;
507 }
508 if (change)
509 setreg = filterpc(pc, jmptarget);
510 }
511 return setreg;
512 }
513
514
515 /*
516 ** Check whether table being indexed by instruction 'i' is the
517 ** environment '_ENV'
518 */
gxf(const Proto * p,int pc,Instruction i,int isup)519 static const char *gxf (const Proto *p, int pc, Instruction i, int isup) {
520 int t = GETARG_B(i); /* table index */
521 const char *name; /* name of indexed variable */
522 if (isup) /* is an upvalue? */
523 name = upvalname(p, t);
524 else
525 getobjname(p, pc, t, &name);
526 return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field";
527 }
528
529
getobjname(const Proto * p,int lastpc,int reg,const char ** name)530 static const char *getobjname (const Proto *p, int lastpc, int reg,
531 const char **name) {
532 int pc;
533 *name = luaF_getlocalname(p, reg + 1, lastpc);
534 if (*name) /* is a local? */
535 return "local";
536 /* else try symbolic execution */
537 pc = findsetreg(p, lastpc, reg);
538 if (pc != -1) { /* could find instruction? */
539 Instruction i = p->code[pc];
540 OpCode op = GET_OPCODE(i);
541 switch (op) {
542 case OP_MOVE: {
543 int b = GETARG_B(i); /* move from 'b' to 'a' */
544 if (b < GETARG_A(i))
545 return getobjname(p, pc, b, name); /* get name for 'b' */
546 break;
547 }
548 case OP_GETTABUP: {
549 int k = GETARG_C(i); /* key index */
550 kname(p, k, name);
551 return gxf(p, pc, i, 1);
552 }
553 case OP_GETTABLE: {
554 int k = GETARG_C(i); /* key index */
555 rname(p, pc, k, name);
556 return gxf(p, pc, i, 0);
557 }
558 case OP_GETI: {
559 *name = "integer index";
560 return "field";
561 }
562 case OP_GETFIELD: {
563 int k = GETARG_C(i); /* key index */
564 kname(p, k, name);
565 return gxf(p, pc, i, 0);
566 }
567 case OP_GETUPVAL: {
568 *name = upvalname(p, GETARG_B(i));
569 return "upvalue";
570 }
571 case OP_LOADK:
572 case OP_LOADKX: {
573 int b = (op == OP_LOADK) ? GETARG_Bx(i)
574 : GETARG_Ax(p->code[pc + 1]);
575 if (ttisstring(&p->k[b])) {
576 *name = svalue(&p->k[b]);
577 return "constant";
578 }
579 break;
580 }
581 case OP_SELF: {
582 rkname(p, pc, i, name);
583 return "method";
584 }
585 default: break; /* go through to return NULL */
586 }
587 }
588 return NULL; /* could not find reasonable name */
589 }
590
591
592 /*
593 ** Try to find a name for a function based on the code that called it.
594 ** (Only works when function was called by a Lua function.)
595 ** Returns what the name is (e.g., "for iterator", "method",
596 ** "metamethod") and sets '*name' to point to the name.
597 */
funcnamefromcode(lua_State * L,const Proto * p,int pc,const char ** name)598 static const char *funcnamefromcode (lua_State *L, const Proto *p,
599 int pc, const char **name) {
600 TMS tm = (TMS)0; /* (initial value avoids warnings) */
601 Instruction i = p->code[pc]; /* calling instruction */
602 switch (GET_OPCODE(i)) {
603 case OP_CALL:
604 case OP_TAILCALL:
605 return getobjname(p, pc, GETARG_A(i), name); /* get function name */
606 case OP_TFORCALL: { /* for iterator */
607 *name = "for iterator";
608 return "for iterator";
609 }
610 /* other instructions can do calls through metamethods */
611 case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
612 case OP_GETI: case OP_GETFIELD:
613 tm = TM_INDEX;
614 break;
615 case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD:
616 tm = TM_NEWINDEX;
617 break;
618 case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
619 tm = cast(TMS, GETARG_C(i));
620 break;
621 }
622 case OP_UNM: tm = TM_UNM; break;
623 case OP_BNOT: tm = TM_BNOT; break;
624 case OP_LEN: tm = TM_LEN; break;
625 case OP_CONCAT: tm = TM_CONCAT; break;
626 case OP_EQ: tm = TM_EQ; break;
627 /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */
628 case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break;
629 case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break;
630 case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break;
631 default:
632 return NULL; /* cannot find a reasonable name */
633 }
634 *name = getstr(G(L)->tmname[tm]) + 2;
635 return "metamethod";
636 }
637
638
639 /*
640 ** Try to find a name for a function based on how it was called.
641 */
funcnamefromcall(lua_State * L,CallInfo * ci,const char ** name)642 static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
643 const char **name) {
644 if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
645 *name = "?";
646 return "hook";
647 }
648 else if (ci->callstatus & CIST_FIN) { /* was it called as a finalizer? */
649 *name = "__gc";
650 return "metamethod"; /* report it as such */
651 }
652 else if (isLua(ci))
653 return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name);
654 else
655 return NULL;
656 }
657
658 /* }====================================================== */
659
660
661
662 /*
663 ** Check whether pointer 'o' points to some value in the stack frame of
664 ** the current function and, if so, returns its index. Because 'o' may
665 ** not point to a value in this stack, we cannot compare it with the
666 ** region boundaries (undefined behavior in ISO C).
667 */
instack(CallInfo * ci,const TValue * o)668 static int instack (CallInfo *ci, const TValue *o) {
669 int pos;
670 StkId base = ci->func.p + 1;
671 for (pos = 0; base + pos < ci->top.p; pos++) {
672 if (o == s2v(base + pos))
673 return pos;
674 }
675 return -1; /* not found */
676 }
677
678
679 /*
680 ** Checks whether value 'o' came from an upvalue. (That can only happen
681 ** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
682 ** upvalues.)
683 */
getupvalname(CallInfo * ci,const TValue * o,const char ** name)684 static const char *getupvalname (CallInfo *ci, const TValue *o,
685 const char **name) {
686 LClosure *c = ci_func(ci);
687 int i;
688 for (i = 0; i < c->nupvalues; i++) {
689 if (c->upvals[i]->v.p == o) {
690 *name = upvalname(c->p, i);
691 return "upvalue";
692 }
693 }
694 return NULL;
695 }
696
697
formatvarinfo(lua_State * L,const char * kind,const char * name)698 static const char *formatvarinfo (lua_State *L, const char *kind,
699 const char *name) {
700 if (kind == NULL)
701 return ""; /* no information */
702 else
703 return luaO_pushfstring(L, " (%s '%s')", kind, name);
704 }
705
706 /*
707 ** Build a string with a "description" for the value 'o', such as
708 ** "variable 'x'" or "upvalue 'y'".
709 */
varinfo(lua_State * L,const TValue * o)710 static const char *varinfo (lua_State *L, const TValue *o) {
711 CallInfo *ci = L->ci;
712 const char *name = NULL; /* to avoid warnings */
713 const char *kind = NULL;
714 if (isLua(ci)) {
715 kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
716 if (!kind) { /* not an upvalue? */
717 int reg = instack(ci, o); /* try a register */
718 if (reg >= 0) /* is 'o' a register? */
719 kind = getobjname(ci_func(ci)->p, currentpc(ci), reg, &name);
720 }
721 }
722 return formatvarinfo(L, kind, name);
723 }
724
725
726 /*
727 ** Raise a type error
728 */
typeerror(lua_State * L,const TValue * o,const char * op,const char * extra)729 static l_noret typeerror (lua_State *L, const TValue *o, const char *op,
730 const char *extra) {
731 const char *t = luaT_objtypename(L, o);
732 luaG_runerror(L, "attempt to %s a %s value%s", op, t, extra);
733 }
734
735
736 /*
737 ** Raise a type error with "standard" information about the faulty
738 ** object 'o' (using 'varinfo').
739 */
luaG_typeerror(lua_State * L,const TValue * o,const char * op)740 l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
741 typeerror(L, o, op, varinfo(L, o));
742 }
743
744
745 /*
746 ** Raise an error for calling a non-callable object. Try to find a name
747 ** for the object based on how it was called ('funcnamefromcall'); if it
748 ** cannot get a name there, try 'varinfo'.
749 */
luaG_callerror(lua_State * L,const TValue * o)750 l_noret luaG_callerror (lua_State *L, const TValue *o) {
751 CallInfo *ci = L->ci;
752 const char *name = NULL; /* to avoid warnings */
753 const char *kind = funcnamefromcall(L, ci, &name);
754 const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o);
755 typeerror(L, o, "call", extra);
756 }
757
758
luaG_forerror(lua_State * L,const TValue * o,const char * what)759 l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) {
760 luaG_runerror(L, "bad 'for' %s (number expected, got %s)",
761 what, luaT_objtypename(L, o));
762 }
763
764
luaG_concaterror(lua_State * L,const TValue * p1,const TValue * p2)765 l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
766 if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
767 luaG_typeerror(L, p1, "concatenate");
768 }
769
770
luaG_opinterror(lua_State * L,const TValue * p1,const TValue * p2,const char * msg)771 l_noret luaG_opinterror (lua_State *L, const TValue *p1,
772 const TValue *p2, const char *msg) {
773 if (!ttisnumber(p1)) /* first operand is wrong? */
774 p2 = p1; /* now second is wrong */
775 luaG_typeerror(L, p2, msg);
776 }
777
778
779 /*
780 ** Error when both values are convertible to numbers, but not to integers
781 */
luaG_tointerror(lua_State * L,const TValue * p1,const TValue * p2)782 l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
783 lua_Integer temp;
784 if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I))
785 p2 = p1;
786 luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
787 }
788
789
luaG_ordererror(lua_State * L,const TValue * p1,const TValue * p2)790 l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
791 const char *t1 = luaT_objtypename(L, p1);
792 const char *t2 = luaT_objtypename(L, p2);
793 if (strcmp(t1, t2) == 0)
794 luaG_runerror(L, "attempt to compare two %s values", t1);
795 else
796 luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
797 }
798
799
800 /* add src:line information to 'msg' */
luaG_addinfo(lua_State * L,const char * msg,TString * src,int line)801 const char *luaG_addinfo (lua_State *L, const char *msg, TString *src,
802 int line) {
803 char buff[LUA_IDSIZE];
804 if (src)
805 luaO_chunkid(buff, getstr(src), tsslen(src));
806 else { /* no source available; use "?" instead */
807 buff[0] = '?'; buff[1] = '\0';
808 }
809 return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
810 }
811
812
luaG_errormsg(lua_State * L)813 l_noret luaG_errormsg (lua_State *L) {
814 if (L->errfunc != 0) { /* is there an error handling function? */
815 StkId errfunc = restorestack(L, L->errfunc);
816 lua_assert(ttisfunction(s2v(errfunc)));
817 setobjs2s(L, L->top.p, L->top.p - 1); /* move argument */
818 setobjs2s(L, L->top.p - 1, errfunc); /* push function */
819 L->top.p++; /* assume EXTRA_STACK */
820 luaD_callnoyield(L, L->top.p - 2, 1); /* call it */
821 }
822 luaD_throw(L, LUA_ERRRUN);
823 }
824
825
luaG_runerror(lua_State * L,const char * fmt,...)826 l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
827 CallInfo *ci = L->ci;
828 const char *msg;
829 va_list argp;
830 luaC_checkGC(L); /* error message uses memory */
831 va_start(argp, fmt);
832 msg = luaO_pushvfstring(L, fmt, argp); /* format message */
833 va_end(argp);
834 if (isLua(ci)) { /* if Lua function, add source:line information */
835 luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
836 setobjs2s(L, L->top.p - 2, L->top.p - 1); /* remove 'msg' */
837 L->top.p--;
838 }
839 luaG_errormsg(L);
840 }
841
842
843 /*
844 ** Check whether new instruction 'newpc' is in a different line from
845 ** previous instruction 'oldpc'. More often than not, 'newpc' is only
846 ** one or a few instructions after 'oldpc' (it must be after, see
847 ** caller), so try to avoid calling 'luaG_getfuncline'. If they are
848 ** too far apart, there is a good chance of a ABSLINEINFO in the way,
849 ** so it goes directly to 'luaG_getfuncline'.
850 */
changedline(const Proto * p,int oldpc,int newpc)851 static int changedline (const Proto *p, int oldpc, int newpc) {
852 if (p->lineinfo == NULL) /* no debug information? */
853 return 0;
854 if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */
855 int delta = 0; /* line difference */
856 int pc = oldpc;
857 for (;;) {
858 int lineinfo = p->lineinfo[++pc];
859 if (lineinfo == ABSLINEINFO)
860 break; /* cannot compute delta; fall through */
861 delta += lineinfo;
862 if (pc == newpc)
863 return (delta != 0); /* delta computed successfully */
864 }
865 }
866 /* either instructions are too far apart or there is an absolute line
867 info in the way; compute line difference explicitly */
868 return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc));
869 }
870
871
872 /*
873 ** Traces the execution of a Lua function. Called before the execution
874 ** of each opcode, when debug is on. 'L->oldpc' stores the last
875 ** instruction traced, to detect line changes. When entering a new
876 ** function, 'npci' will be zero and will test as a new line whatever
877 ** the value of 'oldpc'. Some exceptional conditions may return to
878 ** a function without setting 'oldpc'. In that case, 'oldpc' may be
879 ** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc'
880 ** at most causes an extra call to a line hook.)
881 ** This function is not "Protected" when called, so it should correct
882 ** 'L->top.p' before calling anything that can run the GC.
883 */
luaG_traceexec(lua_State * L,const Instruction * pc)884 int luaG_traceexec (lua_State *L, const Instruction *pc) {
885 CallInfo *ci = L->ci;
886 lu_byte mask = L->hookmask;
887 const Proto *p = ci_func(ci)->p;
888 int counthook;
889 if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */
890 ci->u.l.trap = 0; /* don't need to stop again */
891 return 0; /* turn off 'trap' */
892 }
893 pc++; /* reference is always next instruction */
894 ci->u.l.savedpc = pc; /* save 'pc' */
895 counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT));
896 if (counthook)
897 resethookcount(L); /* reset count */
898 else if (!(mask & LUA_MASKLINE))
899 return 1; /* no line hook and count != 0; nothing to be done now */
900 if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */
901 ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
902 return 1; /* do not call hook again (VM yielded, so it did not move) */
903 }
904 if (!isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */
905 L->top.p = ci->top.p; /* correct top */
906 if (counthook)
907 luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */
908 if (mask & LUA_MASKLINE) {
909 /* 'L->oldpc' may be invalid; use zero in this case */
910 int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0;
911 int npci = pcRel(pc, p);
912 if (npci <= oldpc || /* call hook when jump back (loop), */
913 changedline(p, oldpc, npci)) { /* or when enter new line */
914 int newline = luaG_getfuncline(p, npci);
915 luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */
916 }
917 L->oldpc = npci; /* 'pc' of last call to line hook */
918 }
919 if (L->status == LUA_YIELD) { /* did hook yield? */
920 if (counthook)
921 L->hookcount = 1; /* undo decrement to zero */
922 ci->u.l.savedpc--; /* undo increment (resume will increment it again) */
923 ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */
924 luaD_throw(L, LUA_YIELD);
925 }
926 return 1; /* keep 'trap' on */
927 }
928
929