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