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