1/*
2** Debugging and introspection.
3** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#define lj_debug_c
7#define LUA_CORE
8
9#include "lj_obj.h"
10#include "lj_err.h"
11#include "lj_debug.h"
12#include "lj_str.h"
13#include "lj_tab.h"
14#include "lj_state.h"
15#include "lj_frame.h"
16#include "lj_bc.h"
17#if LJ_HASJIT
18#include "lj_jit.h"
19#endif
20
21/* -- Frames -------------------------------------------------------------- */
22
23/* Get frame corresponding to a level. */
24cTValue *lj_debug_frame(lua_State *L, int level, int *size)
25{
26 cTValue *frame, *nextframe, *bot = tvref(L->stack);
27 /* Traverse frames backwards. */
28 for (nextframe = frame = L->base-1; frame > bot; ) {
29 if (frame_gc(frame) == obj2gco(L))
30 level++; /* Skip dummy frames. See lj_meta_call(). */
31 if (level-- == 0) {
32 *size = (int)(nextframe - frame);
33 return frame; /* Level found. */
34 }
35 nextframe = frame;
36 if (frame_islua(frame)) {
37 frame = frame_prevl(frame);
38 } else {
39 if (frame_isvarg(frame))
40 level++; /* Skip vararg pseudo-frame. */
41 frame = frame_prevd(frame);
42 }
43 }
44 *size = level;
45 return NULL; /* Level not found. */
46}
47
48/* Invalid bytecode position. */
49#define NO_BCPOS (~(BCPos)0)
50
51/* Return bytecode position for function/frame or NO_BCPOS. */
52static BCPos debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe)
53{
54 const BCIns *ins;
55 GCproto *pt;
56 BCPos pos;
57 lua_assert(fn->c.gct == ~LJ_TFUNC || fn->c.gct == ~LJ_TTHREAD);
58 if (!isluafunc(fn)) { /* Cannot derive a PC for non-Lua functions. */
59 return NO_BCPOS;
60 } else if (nextframe == NULL) { /* Lua function on top. */
61 void *cf = cframe_raw(L->cframe);
62 if (cf == NULL || (char *)cframe_pc(cf) == (char *)cframe_L(cf))
63 return NO_BCPOS;
64 ins = cframe_pc(cf); /* Only happens during error/hook handling. */
65 } else {
66 if (frame_islua(nextframe)) {
67 ins = frame_pc(nextframe);
68 } else if (frame_iscont(nextframe)) {
69 ins = frame_contpc(nextframe);
70 } else {
71 /* Lua function below errfunc/gc/hook: find cframe to get the PC. */
72 void *cf = cframe_raw(L->cframe);
73 TValue *f = L->base-1;
74 for (;;) {
75 if (cf == NULL)
76 return NO_BCPOS;
77 while (cframe_nres(cf) < 0) {
78 if (f >= restorestack(L, -cframe_nres(cf)))
79 break;
80 cf = cframe_raw(cframe_prev(cf));
81 if (cf == NULL)
82 return NO_BCPOS;
83 }
84 if (f < nextframe)
85 break;
86 if (frame_islua(f)) {
87 f = frame_prevl(f);
88 } else {
89 if (frame_isc(f))
90 cf = cframe_raw(cframe_prev(cf));
91 f = frame_prevd(f);
92 }
93 }
94 ins = cframe_pc(cf);
95 }
96 }
97 pt = funcproto(fn);
98 pos = proto_bcpos(pt, ins) - 1;
99#if LJ_HASJIT
100 if (pos > pt->sizebc) { /* Undo the effects of lj_trace_exit for JLOOP. */
101 GCtrace *T = (GCtrace *)((char *)(ins-1) - offsetof(GCtrace, startins));
102 lua_assert(bc_isret(bc_op(ins[-1])));
103 pos = proto_bcpos(pt, mref(T->startpc, const BCIns));
104 }
105#endif
106 return pos;
107}
108
109/* -- Line numbers -------------------------------------------------------- */
110
111/* Get line number for a bytecode position. */
112BCLine LJ_FASTCALL lj_debug_line(GCproto *pt, BCPos pc)
113{
114 const void *lineinfo = proto_lineinfo(pt);
115 if (pc <= pt->sizebc && lineinfo) {
116 BCLine first = pt->firstline;
117 if (pc == pt->sizebc) return first + pt->numline;
118 if (pc-- == 0) return first;
119 if (pt->numline < 256)
120 return first + (BCLine)((const uint8_t *)lineinfo)[pc];
121 else if (pt->numline < 65536)
122 return first + (BCLine)((const uint16_t *)lineinfo)[pc];
123 else
124 return first + (BCLine)((const uint32_t *)lineinfo)[pc];
125 }
126 return 0;
127}
128
129/* Get line number for function/frame. */
130static BCLine debug_frameline(lua_State *L, GCfunc *fn, cTValue *nextframe)
131{
132 BCPos pc = debug_framepc(L, fn, nextframe);
133 if (pc != NO_BCPOS) {
134 GCproto *pt = funcproto(fn);
135 lua_assert(pc <= pt->sizebc);
136 return lj_debug_line(pt, pc);
137 }
138 return -1;
139}
140
141/* -- Variable names ------------------------------------------------------ */
142
143/* Read ULEB128 value. */
144static uint32_t debug_read_uleb128(const uint8_t **pp)
145{
146 const uint8_t *p = *pp;
147 uint32_t v = *p++;
148 if (LJ_UNLIKELY(v >= 0x80)) {
149 int sh = 0;
150 v &= 0x7f;
151 do { v |= ((*p & 0x7f) << (sh += 7)); } while (*p++ >= 0x80);
152 }
153 *pp = p;
154 return v;
155}
156
157/* Get name of a local variable from slot number and PC. */
158static const char *debug_varname(const GCproto *pt, BCPos pc, BCReg slot)
159{
160 const uint8_t *p = proto_varinfo(pt);
161 if (p) {
162 BCPos lastpc = 0;
163 for (;;) {
164 const char *name = (const char *)p;
165 uint32_t vn = *p++;
166 BCPos startpc, endpc;
167 if (vn < VARNAME__MAX) {
168 if (vn == VARNAME_END) break; /* End of varinfo. */
169 } else {
170 while (*p++) ; /* Skip over variable name string. */
171 }
172 lastpc = startpc = lastpc + debug_read_uleb128(&p);
173 if (startpc > pc) break;
174 endpc = startpc + debug_read_uleb128(&p);
175 if (pc < endpc && slot-- == 0) {
176 if (vn < VARNAME__MAX) {
177#define VARNAMESTR(name, str) str "\0"
178 name = VARNAMEDEF(VARNAMESTR);
179#undef VARNAMESTR
180 if (--vn) while (*name++ || --vn) ;
181 }
182 return name;
183 }
184 }
185 }
186 return NULL;
187}
188
189/* Get name of local variable from 1-based slot number and function/frame. */
190static TValue *debug_localname(lua_State *L, const lua_Debug *ar,
191 const char **name, BCReg slot1)
192{
193 uint32_t offset = (uint32_t)ar->i_ci & 0xffff;
194 uint32_t size = (uint32_t)ar->i_ci >> 16;
195 TValue *frame = tvref(L->stack) + offset;
196 TValue *nextframe = size ? frame + size : NULL;
197 GCfunc *fn = frame_func(frame);
198 BCPos pc = debug_framepc(L, fn, nextframe);
199 if (!nextframe) nextframe = L->top;
200 if ((int)slot1 < 0) { /* Negative slot number is for varargs. */
201 if (pc != NO_BCPOS) {
202 GCproto *pt = funcproto(fn);
203 if ((pt->flags & PROTO_VARARG)) {
204 slot1 = pt->numparams + (BCReg)(-(int)slot1);
205 if (frame_isvarg(frame)) { /* Vararg frame has been set up? (pc!=0) */
206 nextframe = frame;
207 frame = frame_prevd(frame);
208 }
209 if (frame + slot1 < nextframe) {
210 *name = "(*vararg)";
211 return frame+slot1;
212 }
213 }
214 }
215 return NULL;
216 }
217 if (pc != NO_BCPOS &&
218 (*name = debug_varname(funcproto(fn), pc, slot1-1)) != NULL)
219 ;
220 else if (slot1 > 0 && frame + slot1 < nextframe)
221 *name = "(*temporary)";
222 return frame+slot1;
223}
224
225/* Get name of upvalue. */
226const char *lj_debug_uvname(GCproto *pt, uint32_t idx)
227{
228 const uint8_t *p = proto_uvinfo(pt);
229 lua_assert(idx < pt->sizeuv);
230 if (!p) return "";
231 if (idx) while (*p++ || --idx) ;
232 return (const char *)p;
233}
234
235/* Get name and value of upvalue. */
236const char *lj_debug_uvnamev(cTValue *o, uint32_t idx, TValue **tvp)
237{
238 if (tvisfunc(o)) {
239 GCfunc *fn = funcV(o);
240 if (isluafunc(fn)) {
241 GCproto *pt = funcproto(fn);
242 if (idx < pt->sizeuv) {
243 *tvp = uvval(&gcref(fn->l.uvptr[idx])->uv);
244 return lj_debug_uvname(pt, idx);
245 }
246 } else {
247 if (idx < fn->c.nupvalues) {
248 *tvp = &fn->c.upvalue[idx];
249 return "";
250 }
251 }
252 }
253 return NULL;
254}
255
256/* Deduce name of an object from slot number and PC. */
257const char *lj_debug_slotname(GCproto *pt, const BCIns *ip, BCReg slot,
258 const char **name)
259{
260 const char *lname;
261restart:
262 lname = debug_varname(pt, proto_bcpos(pt, ip), slot);
263 if (lname != NULL) { *name = lname; return "local"; }
264 while (--ip > proto_bc(pt)) {
265 BCIns ins = *ip;
266 BCOp op = bc_op(ins);
267 BCReg ra = bc_a(ins);
268 if (bcmode_a(op) == BCMbase) {
269 if (slot >= ra && (op != BC_KNIL || slot <= bc_d(ins)))
270 return NULL;
271 } else if (bcmode_a(op) == BCMdst && ra == slot) {
272 switch (bc_op(ins)) {
273 case BC_MOV:
274 if (ra == slot) { slot = bc_d(ins); goto restart; }
275 break;
276 case BC_GGET:
277 *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_d(ins))));
278 return "global";
279 case BC_TGETS:
280 *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_c(ins))));
281 if (ip > proto_bc(pt)) {
282 BCIns insp = ip[-1];
283 if (bc_op(insp) == BC_MOV && bc_a(insp) == ra+1 &&
284 bc_d(insp) == bc_b(ins))
285 return "method";
286 }
287 return "field";
288 case BC_UGET:
289 *name = lj_debug_uvname(pt, bc_d(ins));
290 return "upvalue";
291 default:
292 return NULL;
293 }
294 }
295 }
296 return NULL;
297}
298
299/* Deduce function name from caller of a frame. */
300const char *lj_debug_funcname(lua_State *L, TValue *frame, const char **name)
301{
302 TValue *pframe;
303 GCfunc *fn;
304 BCPos pc;
305 if (frame <= tvref(L->stack))
306 return NULL;
307 if (frame_isvarg(frame))
308 frame = frame_prevd(frame);
309 pframe = frame_prev(frame);
310 fn = frame_func(pframe);
311 pc = debug_framepc(L, fn, frame);
312 if (pc != NO_BCPOS) {
313 GCproto *pt = funcproto(fn);
314 const BCIns *ip = &proto_bc(pt)[check_exp(pc < pt->sizebc, pc)];
315 MMS mm = bcmode_mm(bc_op(*ip));
316 if (mm == MM_call) {
317 BCReg slot = bc_a(*ip);
318 if (bc_op(*ip) == BC_ITERC) slot -= 3;
319 return lj_debug_slotname(pt, ip, slot, name);
320 } else if (mm != MM__MAX) {
321 *name = strdata(mmname_str(G(L), mm));
322 return "metamethod";
323 }
324 }
325 return NULL;
326}
327
328/* -- Source code locations ----------------------------------------------- */
329
330/* Generate shortened source name. */
331void lj_debug_shortname(char *out, GCstr *str)
332{
333 const char *src = strdata(str);
334 if (*src == '=') {
335 strncpy(out, src+1, LUA_IDSIZE); /* Remove first char. */
336 out[LUA_IDSIZE-1] = '\0'; /* Ensures null termination. */
337 } else if (*src == '@') { /* Output "source", or "...source". */
338 size_t len = str->len-1;
339 src++; /* Skip the `@' */
340 if (len >= LUA_IDSIZE) {
341 src += len-(LUA_IDSIZE-4); /* Get last part of file name. */
342 *out++ = '.'; *out++ = '.'; *out++ = '.';
343 }
344 strcpy(out, src);
345 } else { /* Output [string "string"]. */
346 size_t len; /* Length, up to first control char. */
347 for (len = 0; len < LUA_IDSIZE-12; len++)
348 if (((const unsigned char *)src)[len] < ' ') break;
349 strcpy(out, "[string \""); out += 9;
350 if (src[len] != '\0') { /* Must truncate? */
351 if (len > LUA_IDSIZE-15) len = LUA_IDSIZE-15;
352 strncpy(out, src, len); out += len;
353 strcpy(out, "..."); out += 3;
354 } else {
355 strcpy(out, src); out += len;
356 }
357 strcpy(out, "\"]");
358 }
359}
360
361/* Add current location of a frame to error message. */
362void lj_debug_addloc(lua_State *L, const char *msg,
363 cTValue *frame, cTValue *nextframe)
364{
365 if (frame) {
366 GCfunc *fn = frame_func(frame);
367 if (isluafunc(fn)) {
368 BCLine line = debug_frameline(L, fn, nextframe);
369 if (line >= 0) {
370 char buf[LUA_IDSIZE];
371 lj_debug_shortname(buf, proto_chunkname(funcproto(fn)));
372 lj_str_pushf(L, "%s:%d: %s", buf, line, msg);
373 return;
374 }
375 }
376 }
377 lj_str_pushf(L, "%s", msg);
378}
379
380/* Push location string for a bytecode position to Lua stack. */
381void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc)
382{
383 GCstr *name = proto_chunkname(pt);
384 const char *s = strdata(name);
385 MSize i, len = name->len;
386 BCLine line = lj_debug_line(pt, pc);
387 if (*s == '@') {
388 s++; len--;
389 for (i = len; i > 0; i--)
390 if (s[i] == '/' || s[i] == '\\') {
391 s += i+1;
392 break;
393 }
394 lj_str_pushf(L, "%s:%d", s, line);
395 } else if (len > 40) {
396 lj_str_pushf(L, "%p:%d", pt, line);
397 } else if (*s == '=') {
398 lj_str_pushf(L, "%s:%d", s+1, line);
399 } else {
400 lj_str_pushf(L, "\"%s\":%d", s, line);
401 }
402}
403
404/* -- Public debug API ---------------------------------------------------- */
405
406/* lua_getupvalue() and lua_setupvalue() are in lj_api.c. */
407
408LUA_API const char *lua_getlocal(lua_State *L, const lua_Debug *ar, int n)
409{
410 const char *name = NULL;
411 if (ar) {
412 TValue *o = debug_localname(L, ar, &name, (BCReg)n);
413 if (name) {
414 copyTV(L, L->top, o);
415 incr_top(L);
416 }
417 } else if (tvisfunc(L->top-1) && isluafunc(funcV(L->top-1))) {
418 name = debug_varname(funcproto(funcV(L->top-1)), 0, (BCReg)n-1);
419 }
420 return name;
421}
422
423LUA_API const char *lua_setlocal(lua_State *L, const lua_Debug *ar, int n)
424{
425 const char *name = NULL;
426 TValue *o = debug_localname(L, ar, &name, (BCReg)n);
427 if (name)
428 copyTV(L, o, L->top-1);
429 L->top--;
430 return name;
431}
432
433int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar, int ext)
434{
435 int opt_f = 0, opt_L = 0;
436 TValue *frame = NULL;
437 TValue *nextframe = NULL;
438 GCfunc *fn;
439 if (*what == '>') {
440 TValue *func = L->top - 1;
441 api_check(L, tvisfunc(func));
442 fn = funcV(func);
443 L->top--;
444 what++;
445 } else {
446 uint32_t offset = (uint32_t)ar->i_ci & 0xffff;
447 uint32_t size = (uint32_t)ar->i_ci >> 16;
448 lua_assert(offset != 0);
449 frame = tvref(L->stack) + offset;
450 if (size) nextframe = frame + size;
451 lua_assert(frame <= tvref(L->maxstack) &&
452 (!nextframe || nextframe <= tvref(L->maxstack)));
453 fn = frame_func(frame);
454 lua_assert(fn->c.gct == ~LJ_TFUNC);
455 }
456 for (; *what; what++) {
457 if (*what == 'S') {
458 if (isluafunc(fn)) {
459 GCproto *pt = funcproto(fn);
460 BCLine firstline = pt->firstline;
461 GCstr *name = proto_chunkname(pt);
462 ar->source = strdata(name);
463 lj_debug_shortname(ar->short_src, name);
464 ar->linedefined = (int)firstline;
465 ar->lastlinedefined = (int)(firstline + pt->numline);
466 ar->what = firstline ? "Lua" : "main";
467 } else {
468 ar->source = "=[C]";
469 ar->short_src[0] = '[';
470 ar->short_src[1] = 'C';
471 ar->short_src[2] = ']';
472 ar->short_src[3] = '\0';
473 ar->linedefined = -1;
474 ar->lastlinedefined = -1;
475 ar->what = "C";
476 }
477 } else if (*what == 'l') {
478 ar->currentline = frame ? debug_frameline(L, fn, nextframe) : -1;
479 } else if (*what == 'u') {
480 ar->nups = fn->c.nupvalues;
481 if (ext) {
482 if (isluafunc(fn)) {
483 GCproto *pt = funcproto(fn);
484 ar->nparams = pt->numparams;
485 ar->isvararg = !!(pt->flags & PROTO_VARARG);
486 } else {
487 ar->nparams = 0;
488 ar->isvararg = 1;
489 }
490 }
491 } else if (*what == 'n') {
492 ar->namewhat = frame ? lj_debug_funcname(L, frame, &ar->name) : NULL;
493 if (ar->namewhat == NULL) {
494 ar->namewhat = "";
495 ar->name = NULL;
496 }
497 } else if (*what == 'f') {
498 opt_f = 1;
499 } else if (*what == 'L') {
500 opt_L = 1;
501 } else {
502 return 0; /* Bad option. */
503 }
504 }
505 if (opt_f) {
506 setfuncV(L, L->top, fn);
507 incr_top(L);
508 }
509 if (opt_L) {
510 if (isluafunc(fn)) {
511 GCtab *t = lj_tab_new(L, 0, 0);
512 GCproto *pt = funcproto(fn);
513 const void *lineinfo = proto_lineinfo(pt);
514 if (lineinfo) {
515 BCLine first = pt->firstline;
516 int sz = pt->numline < 256 ? 1 : pt->numline < 65536 ? 2 : 4;
517 MSize i, szl = pt->sizebc-1;
518 for (i = 0; i < szl; i++) {
519 BCLine line = first +
520 (sz == 1 ? (BCLine)((const uint8_t *)lineinfo)[i] :
521 sz == 2 ? (BCLine)((const uint16_t *)lineinfo)[i] :
522 (BCLine)((const uint32_t *)lineinfo)[i]);
523 setboolV(lj_tab_setint(L, t, line), 1);
524 }
525 }
526 settabV(L, L->top, t);
527 } else {
528 setnilV(L->top);
529 }
530 incr_top(L);
531 }
532 return 1; /* Ok. */
533}
534
535LUA_API int lua_getinfo(lua_State *L, const char *what, lua_Debug *ar)
536{
537 return lj_debug_getinfo(L, what, (lj_Debug *)ar, 0);
538}
539
540LUA_API int lua_getstack(lua_State *L, int level, lua_Debug *ar)
541{
542 int size;
543 cTValue *frame = lj_debug_frame(L, level, &size);
544 if (frame) {
545 ar->i_ci = (size << 16) + (int)(frame - tvref(L->stack));
546 return 1;
547 } else {
548 ar->i_ci = level - size;
549 return 0;
550 }
551}
552
553/* Number of frames for the leading and trailing part of a traceback. */
554#define TRACEBACK_LEVELS1 12
555#define TRACEBACK_LEVELS2 10
556
557LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
558 int level)
559{
560 int top = (int)(L->top - L->base);
561 int lim = TRACEBACK_LEVELS1;
562 lua_Debug ar;
563 if (msg) lua_pushfstring(L, "%s\n", msg);
564 lua_pushliteral(L, "stack traceback:");
565 while (lua_getstack(L1, level++, &ar)) {
566 GCfunc *fn;
567 if (level > lim) {
568 if (!lua_getstack(L1, level + TRACEBACK_LEVELS2, &ar)) {
569 level--;
570 } else {
571 lua_pushliteral(L, "\n\t...");
572 lua_getstack(L1, -10, &ar);
573 level = ar.i_ci - TRACEBACK_LEVELS2;
574 }
575 lim = 2147483647;
576 continue;
577 }
578 lua_getinfo(L1, "Snlf", &ar);
579 fn = funcV(L1->top-1); L1->top--;
580 if (isffunc(fn) && !*ar.namewhat)
581 lua_pushfstring(L, "\n\t[builtin#%d]:", fn->c.ffid);
582 else
583 lua_pushfstring(L, "\n\t%s:", ar.short_src);
584 if (ar.currentline > 0)
585 lua_pushfstring(L, "%d:", ar.currentline);
586 if (*ar.namewhat) {
587 lua_pushfstring(L, " in function " LUA_QS, ar.name);
588 } else {
589 if (*ar.what == 'm') {
590 lua_pushliteral(L, " in main chunk");
591 } else if (*ar.what == 'C') {
592 lua_pushfstring(L, " at %p", fn->c.f);
593 } else {
594 lua_pushfstring(L, " in function <%s:%d>",
595 ar.short_src, ar.linedefined);
596 }
597 }
598 if ((int)(L->top - L->base) - top >= 15)
599 lua_concat(L, (int)(L->top - L->base) - top);
600 }
601 lua_concat(L, (int)(L->top - L->base) - top);
602}
603
604