xref: /netbsd-src/external/mit/lua/dist/src/ldebug.c (revision f89f6560d453f5e37386cc7938c072d2f528b9fa)
1 /*	$NetBSD: ldebug.c,v 1.4 2015/02/19 04:46:22 lneto Exp $	*/
2 
3 /*
4 ** Id: ldebug.c,v 2.110 2015/01/02 12:52:22 roberto Exp
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
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_TCCL)
39 
40 
41 static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name);
42 
43 
44 static int currentpc (CallInfo *ci) {
45   lua_assert(isLua(ci));
46   return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
47 }
48 
49 
50 static int currentline (CallInfo *ci) {
51   return getfuncline(ci_func(ci)->p, currentpc(ci));
52 }
53 
54 
55 /*
56 ** this function can be called asynchronous (e.g. during a signal)
57 */
58 LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
59   if (func == NULL || mask == 0) {  /* turn off hooks? */
60     mask = 0;
61     func = NULL;
62   }
63   if (isLua(L->ci))
64     L->oldpc = L->ci->u.l.savedpc;
65   L->hook = func;
66   L->basehookcount = count;
67   resethookcount(L);
68   L->hookmask = cast_byte(mask);
69 }
70 
71 
72 LUA_API lua_Hook lua_gethook (lua_State *L) {
73   return L->hook;
74 }
75 
76 
77 LUA_API int lua_gethookmask (lua_State *L) {
78   return L->hookmask;
79 }
80 
81 
82 LUA_API int lua_gethookcount (lua_State *L) {
83   return L->basehookcount;
84 }
85 
86 
87 LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
88   int status;
89   CallInfo *ci;
90   if (level < 0) return 0;  /* invalid (negative) level */
91   lua_lock(L);
92   for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)
93     level--;
94   if (level == 0 && ci != &L->base_ci) {  /* level found? */
95     status = 1;
96     ar->i_ci = ci;
97   }
98   else status = 0;  /* no such level */
99   lua_unlock(L);
100   return status;
101 }
102 
103 
104 static const char *upvalname (Proto *p, int uv) {
105   TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
106   if (s == NULL) return "?";
107   else return getstr(s);
108 }
109 
110 
111 static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
112   int nparams = clLvalue(ci->func)->p->numparams;
113   if (n >= ci->u.l.base - ci->func - nparams)
114     return NULL;  /* no such vararg */
115   else {
116     *pos = ci->func + nparams + n;
117     return "(*vararg)";  /* generic name for any vararg */
118   }
119 }
120 
121 
122 static const char *findlocal (lua_State *L, CallInfo *ci, int n,
123                               StkId *pos) {
124   const char *name = NULL;
125   StkId base;
126   if (isLua(ci)) {
127     if (n < 0)  /* access to vararg values? */
128       return findvararg(ci, -n, pos);
129     else {
130       base = ci->u.l.base;
131       name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
132     }
133   }
134   else
135     base = ci->func + 1;
136   if (name == NULL) {  /* no 'standard' name? */
137     StkId limit = (ci == L->ci) ? L->top : ci->next->func;
138     if (limit - base >= n && n > 0)  /* is 'n' inside 'ci' stack? */
139       name = "(*temporary)";  /* generic name for any valid slot */
140     else
141       return NULL;  /* no name */
142   }
143   *pos = base + (n - 1);
144   return name;
145 }
146 
147 
148 LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
149   const char *name;
150   lua_lock(L);
151   if (ar == NULL) {  /* information about non-active function? */
152     if (!isLfunction(L->top - 1))  /* not a Lua function? */
153       name = NULL;
154     else  /* consider live variables at function start (parameters) */
155       name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0);
156   }
157   else {  /* active function; get information through 'ar' */
158     StkId pos = 0;  /* to avoid warnings */
159     name = findlocal(L, ar->i_ci, n, &pos);
160     if (name) {
161       setobj2s(L, L->top, pos);
162       api_incr_top(L);
163     }
164   }
165   lua_unlock(L);
166   return name;
167 }
168 
169 
170 LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
171   StkId pos = 0;  /* to avoid warnings */
172   const char *name = findlocal(L, ar->i_ci, n, &pos);
173   lua_lock(L);
174   if (name) {
175     setobjs2s(L, pos, L->top - 1);
176     L->top--;  /* pop value */
177   }
178   lua_unlock(L);
179   return name;
180 }
181 
182 
183 static void funcinfo (lua_Debug *ar, Closure *cl) {
184   if (noLuaClosure(cl)) {
185     ar->source = "=[C]";
186     ar->linedefined = -1;
187     ar->lastlinedefined = -1;
188     ar->what = "C";
189   }
190   else {
191     Proto *p = cl->l.p;
192     ar->source = p->source ? getstr(p->source) : "=?";
193     ar->linedefined = p->linedefined;
194     ar->lastlinedefined = p->lastlinedefined;
195     ar->what = (ar->linedefined == 0) ? "main" : "Lua";
196   }
197   luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
198 }
199 
200 
201 static void collectvalidlines (lua_State *L, Closure *f) {
202   if (noLuaClosure(f)) {
203     setnilvalue(L->top);
204     api_incr_top(L);
205   }
206   else {
207     int i;
208     TValue v;
209     int *lineinfo = f->l.p->lineinfo;
210     Table *t = luaH_new(L);  /* new table to store active lines */
211     sethvalue(L, L->top, t);  /* push it on stack */
212     api_incr_top(L);
213     setbvalue(&v, 1);  /* boolean 'true' to be the value of all indices */
214     for (i = 0; i < f->l.p->sizelineinfo; i++)  /* for all lines with code */
215       luaH_setint(L, t, lineinfo[i], &v);  /* table[line] = true */
216   }
217 }
218 
219 
220 static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
221                        Closure *f, CallInfo *ci) {
222   int status = 1;
223   for (; *what; what++) {
224     switch (*what) {
225       case 'S': {
226         funcinfo(ar, f);
227         break;
228       }
229       case 'l': {
230         ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1;
231         break;
232       }
233       case 'u': {
234         ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
235         if (noLuaClosure(f)) {
236           ar->isvararg = 1;
237           ar->nparams = 0;
238         }
239         else {
240           ar->isvararg = f->l.p->is_vararg;
241           ar->nparams = f->l.p->numparams;
242         }
243         break;
244       }
245       case 't': {
246         ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0;
247         break;
248       }
249       case 'n': {
250         /* calling function is a known Lua function? */
251         if (ci && !(ci->callstatus & CIST_TAIL) && isLua(ci->previous))
252           ar->namewhat = getfuncname(L, ci->previous, &ar->name);
253         else
254           ar->namewhat = NULL;
255         if (ar->namewhat == NULL) {
256           ar->namewhat = "";  /* not found */
257           ar->name = NULL;
258         }
259         break;
260       }
261       case 'L':
262       case 'f':  /* handled by lua_getinfo */
263         break;
264       default: status = 0;  /* invalid option */
265     }
266   }
267   return status;
268 }
269 
270 
271 LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
272   int status;
273   Closure *cl;
274   CallInfo *ci;
275   StkId func;
276   lua_lock(L);
277   if (*what == '>') {
278     ci = NULL;
279     func = L->top - 1;
280     api_check(ttisfunction(func), "function expected");
281     what++;  /* skip the '>' */
282     L->top--;  /* pop function */
283   }
284   else {
285     ci = ar->i_ci;
286     func = ci->func;
287     lua_assert(ttisfunction(ci->func));
288   }
289   cl = ttisclosure(func) ? clvalue(func) : NULL;
290   status = auxgetinfo(L, what, ar, cl, ci);
291   if (strchr(what, 'f')) {
292     setobjs2s(L, L->top, func);
293     api_incr_top(L);
294   }
295   if (strchr(what, 'L'))
296     collectvalidlines(L, cl);
297   lua_unlock(L);
298   return status;
299 }
300 
301 
302 /*
303 ** {======================================================
304 ** Symbolic Execution
305 ** =======================================================
306 */
307 
308 static const char *getobjname (Proto *p, int lastpc, int reg,
309                                const char **name);
310 
311 
312 /*
313 ** find a "name" for the RK value 'c'
314 */
315 static void kname (Proto *p, int pc, int c, const char **name) {
316   if (ISK(c)) {  /* is 'c' a constant? */
317     TValue *kvalue = &p->k[INDEXK(c)];
318     if (ttisstring(kvalue)) {  /* literal constant? */
319       *name = svalue(kvalue);  /* it is its own name */
320       return;
321     }
322     /* else no reasonable name found */
323   }
324   else {  /* 'c' is a register */
325     const char *what = getobjname(p, pc, c, name); /* search for 'c' */
326     if (what && *what == 'c') {  /* found a constant name? */
327       return;  /* 'name' already filled */
328     }
329     /* else no reasonable name found */
330   }
331   *name = "?";  /* no reasonable name found */
332 }
333 
334 
335 static int filterpc (int pc, int jmptarget) {
336   if (pc < jmptarget)  /* is code conditional (inside a jump)? */
337     return -1;  /* cannot know who sets that register */
338   else return pc;  /* current position sets that register */
339 }
340 
341 
342 /*
343 ** try to find last instruction before 'lastpc' that modified register 'reg'
344 */
345 static int findsetreg (Proto *p, int lastpc, int reg) {
346   int pc;
347   int setreg = -1;  /* keep last instruction that changed 'reg' */
348   int jmptarget = 0;  /* any code before this address is conditional */
349   for (pc = 0; pc < lastpc; pc++) {
350     Instruction i = p->code[pc];
351     OpCode op = GET_OPCODE(i);
352     int a = GETARG_A(i);
353     switch (op) {
354       case OP_LOADNIL: {
355         int b = GETARG_B(i);
356         if (a <= reg && reg <= a + b)  /* set registers from 'a' to 'a+b' */
357           setreg = filterpc(pc, jmptarget);
358         break;
359       }
360       case OP_TFORCALL: {
361         if (reg >= a + 2)  /* affect all regs above its base */
362           setreg = filterpc(pc, jmptarget);
363         break;
364       }
365       case OP_CALL:
366       case OP_TAILCALL: {
367         if (reg >= a)  /* affect all registers above base */
368           setreg = filterpc(pc, jmptarget);
369         break;
370       }
371       case OP_JMP: {
372         int b = GETARG_sBx(i);
373         int dest = pc + 1 + b;
374         /* jump is forward and do not skip 'lastpc'? */
375         if (pc < dest && dest <= lastpc) {
376           if (dest > jmptarget)
377             jmptarget = dest;  /* update 'jmptarget' */
378         }
379         break;
380       }
381       default:
382         if (testAMode(op) && reg == a)  /* any instruction that set A */
383           setreg = filterpc(pc, jmptarget);
384         break;
385     }
386   }
387   return setreg;
388 }
389 
390 
391 static const char *getobjname (Proto *p, int lastpc, int reg,
392                                const char **name) {
393   int pc;
394   *name = luaF_getlocalname(p, reg + 1, lastpc);
395   if (*name)  /* is a local? */
396     return "local";
397   /* else try symbolic execution */
398   pc = findsetreg(p, lastpc, reg);
399   if (pc != -1) {  /* could find instruction? */
400     Instruction i = p->code[pc];
401     OpCode op = GET_OPCODE(i);
402     switch (op) {
403       case OP_MOVE: {
404         int b = GETARG_B(i);  /* move from 'b' to 'a' */
405         if (b < GETARG_A(i))
406           return getobjname(p, pc, b, name);  /* get name for 'b' */
407         break;
408       }
409       case OP_GETTABUP:
410       case OP_GETTABLE: {
411         int k = GETARG_C(i);  /* key index */
412         int t = GETARG_B(i);  /* table index */
413         const char *vn = (op == OP_GETTABLE)  /* name of indexed variable */
414                          ? luaF_getlocalname(p, t + 1, pc)
415                          : upvalname(p, t);
416         kname(p, pc, k, name);
417         return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";
418       }
419       case OP_GETUPVAL: {
420         *name = upvalname(p, GETARG_B(i));
421         return "upvalue";
422       }
423       case OP_LOADK:
424       case OP_LOADKX: {
425         int b = (op == OP_LOADK) ? GETARG_Bx(i)
426                                  : GETARG_Ax(p->code[pc + 1]);
427         if (ttisstring(&p->k[b])) {
428           *name = svalue(&p->k[b]);
429           return "constant";
430         }
431         break;
432       }
433       case OP_SELF: {
434         int k = GETARG_C(i);  /* key index */
435         kname(p, pc, k, name);
436         return "method";
437       }
438       default: break;  /* go through to return NULL */
439     }
440   }
441   return NULL;  /* could not find reasonable name */
442 }
443 
444 
445 static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
446   TMS tm = (TMS)0;  /* to avoid warnings */
447   Proto *p = ci_func(ci)->p;  /* calling function */
448   int pc = currentpc(ci);  /* calling instruction index */
449   Instruction i = p->code[pc];  /* calling instruction */
450   if (ci->callstatus & CIST_HOOKED) {  /* was it called inside a hook? */
451     *name = "?";
452     return "hook";
453   }
454   switch (GET_OPCODE(i)) {
455     case OP_CALL:
456     case OP_TAILCALL:  /* get function name */
457       return getobjname(p, pc, GETARG_A(i), name);
458     case OP_TFORCALL: {  /* for iterator */
459       *name = "for iterator";
460        return "for iterator";
461     }
462     /* all other instructions can call only through metamethods */
463     case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
464       tm = TM_INDEX;
465       break;
466     case OP_SETTABUP: case OP_SETTABLE:
467       tm = TM_NEWINDEX;
468       break;
469     case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD:
470 #ifndef _KERNEL
471     case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND:
472 #else /* _KERNEL */
473     case OP_IDIV: case OP_BAND:
474 #endif
475     case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: {
476       int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD);  /* ORDER OP */
477       tm = cast(TMS, offset + cast_int(TM_ADD));  /* ORDER TM */
478       break;
479     }
480     case OP_UNM: tm = TM_UNM; break;
481     case OP_BNOT: tm = TM_BNOT; break;
482     case OP_LEN: tm = TM_LEN; break;
483     case OP_CONCAT: tm = TM_CONCAT; break;
484     case OP_EQ: tm = TM_EQ; break;
485     case OP_LT: tm = TM_LT; break;
486     case OP_LE: tm = TM_LE; break;
487     default: lua_assert(0);  /* other instructions cannot call a function */
488   }
489   *name = getstr(G(L)->tmname[tm]);
490   return "metamethod";
491 }
492 
493 /* }====================================================== */
494 
495 
496 
497 /*
498 ** The subtraction of two potentially unrelated pointers is
499 ** not ISO C, but it should not crash a program; the subsequent
500 ** checks are ISO C and ensure a correct result.
501 */
502 static int isinstack (CallInfo *ci, const TValue *o) {
503   ptrdiff_t i = o - ci->u.l.base;
504   return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o);
505 }
506 
507 
508 /*
509 ** Checks whether value 'o' came from an upvalue. (That can only happen
510 ** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
511 ** upvalues.)
512 */
513 static const char *getupvalname (CallInfo *ci, const TValue *o,
514                                  const char **name) {
515   LClosure *c = ci_func(ci);
516   int i;
517   for (i = 0; i < c->nupvalues; i++) {
518     if (c->upvals[i]->v == o) {
519       *name = upvalname(c->p, i);
520       return "upvalue";
521     }
522   }
523   return NULL;
524 }
525 
526 
527 static const char *varinfo (lua_State *L, const TValue *o) {
528   const char *name = NULL;  /* to avoid warnings */
529   CallInfo *ci = L->ci;
530   const char *kind = NULL;
531   if (isLua(ci)) {
532     kind = getupvalname(ci, o, &name);  /* check whether 'o' is an upvalue */
533     if (!kind && isinstack(ci, o))  /* no? try a register */
534       kind = getobjname(ci_func(ci)->p, currentpc(ci),
535                         cast_int(o - ci->u.l.base), &name);
536   }
537   return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : "";
538 }
539 
540 
541 l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
542   const char *t = objtypename(o);
543   luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o));
544 }
545 
546 
547 l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
548   if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
549   luaG_typeerror(L, p1, "concatenate");
550 }
551 
552 
553 l_noret luaG_opinterror (lua_State *L, const TValue *p1,
554                          const TValue *p2, const char *msg) {
555   lua_Number temp;
556   if (!tonumber(p1, &temp))  /* first operand is wrong? */
557     p2 = p1;  /* now second is wrong */
558   luaG_typeerror(L, p2, msg);
559 }
560 
561 
562 /*
563 ** Error when both values are convertible to numbers, but not to integers
564 */
565 l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
566   lua_Integer temp;
567   if (!tointeger(p1, &temp))
568     p2 = p1;
569   luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
570 }
571 
572 
573 l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
574   const char *t1 = objtypename(p1);
575   const char *t2 = objtypename(p2);
576   if (t1 == t2)
577     luaG_runerror(L, "attempt to compare two %s values", t1);
578   else
579     luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
580 }
581 
582 
583 static void addinfo (lua_State *L, const char *msg) {
584   CallInfo *ci = L->ci;
585   if (isLua(ci)) {  /* is Lua code? */
586     char buff[LUA_IDSIZE];  /* add file:line information */
587     int line = currentline(ci);
588     TString *src = ci_func(ci)->p->source;
589     if (src)
590       luaO_chunkid(buff, getstr(src), LUA_IDSIZE);
591     else {  /* no source available; use "?" instead */
592       buff[0] = '?'; buff[1] = '\0';
593     }
594     luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
595   }
596 }
597 
598 
599 l_noret luaG_errormsg (lua_State *L) {
600   if (L->errfunc != 0) {  /* is there an error handling function? */
601     StkId errfunc = restorestack(L, L->errfunc);
602     setobjs2s(L, L->top, L->top - 1);  /* move argument */
603     setobjs2s(L, L->top - 1, errfunc);  /* push function */
604     L->top++;  /* assume EXTRA_STACK */
605     luaD_call(L, L->top - 2, 1, 0);  /* call it */
606   }
607   luaD_throw(L, LUA_ERRRUN);
608 }
609 
610 
611 l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
612   va_list argp;
613   va_start(argp, fmt);
614   addinfo(L, luaO_pushvfstring(L, fmt, argp));
615   va_end(argp);
616   luaG_errormsg(L);
617 }
618 
619 
620 void luaG_traceexec (lua_State *L) {
621   CallInfo *ci = L->ci;
622   lu_byte mask = L->hookmask;
623   int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0);
624   if (counthook)
625     resethookcount(L);  /* reset count */
626   if (ci->callstatus & CIST_HOOKYIELD) {  /* called hook last time? */
627     ci->callstatus &= ~CIST_HOOKYIELD;  /* erase mark */
628     return;  /* do not call hook again (VM yielded, so it did not move) */
629   }
630   if (counthook)
631     luaD_hook(L, LUA_HOOKCOUNT, -1);  /* call count hook */
632   if (mask & LUA_MASKLINE) {
633     Proto *p = ci_func(ci)->p;
634     int npc = pcRel(ci->u.l.savedpc, p);
635     int newline = getfuncline(p, npc);
636     if (npc == 0 ||  /* call linehook when enter a new function, */
637         ci->u.l.savedpc <= L->oldpc ||  /* when jump back (loop), or when */
638         newline != getfuncline(p, pcRel(L->oldpc, p)))  /* enter a new line */
639       luaD_hook(L, LUA_HOOKLINE, newline);  /* call line hook */
640   }
641   L->oldpc = ci->u.l.savedpc;
642   if (L->status == LUA_YIELD) {  /* did hook yield? */
643     if (counthook)
644       L->hookcount = 1;  /* undo decrement to zero */
645     ci->u.l.savedpc--;  /* undo increment (resume will increment it again) */
646     ci->callstatus |= CIST_HOOKYIELD;  /* mark that it yielded */
647     ci->func = L->top - 1;  /* protect stack below results */
648     luaD_throw(L, LUA_YIELD);
649   }
650 }
651 
652