2 ** Debugging and introspection.
3 ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
17 #include "lj_strfmt.h"
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
)+LJ_FR2
;
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_err_optype_call(). */
33 *size
= (int)(nextframe
- frame
);
34 return frame
; /* Level found. */
37 if (frame_islua(frame
)) {
38 frame
= frame_prevl(frame
);
40 if (frame_isvarg(frame
))
41 level
++; /* Skip vararg pseudo-frame. */
42 frame
= frame_prevd(frame
);
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
)
58 lj_assertL(fn
->c
.gct
== ~LJ_TFUNC
|| fn
->c
.gct
== ~LJ_TTHREAD
,
59 "function or frame expected");
60 if (!isluafunc(fn
)) { /* Cannot derive a PC for non-Lua functions. */
62 } else if (nextframe
== NULL
) { /* Lua function on top. */
63 void *cf
= cframe_raw(L
->cframe
);
64 if (cf
== NULL
|| (char *)cframe_pc(cf
) == (char *)cframe_L(cf
))
66 ins
= cframe_pc(cf
); /* Only happens during error/hook handling. */
68 if (frame_islua(nextframe
)) {
69 ins
= frame_pc(nextframe
);
70 } else if (frame_iscont(nextframe
)) {
71 ins
= frame_contpc(nextframe
);
73 /* Lua function below errfunc/gc/hook: find cframe to get the PC. */
74 void *cf
= cframe_raw(L
->cframe
);
75 TValue
*f
= L
->base
-1;
79 while (cframe_nres(cf
) < 0) {
80 if (f
>= restorestack(L
, -cframe_nres(cf
)))
82 cf
= cframe_raw(cframe_prev(cf
));
91 if (frame_isc(f
) || (frame_iscont(f
) && frame_iscont_fficb(f
)))
92 cf
= cframe_raw(cframe_prev(cf
));
97 if (!ins
) return NO_BCPOS
;
101 pos
= proto_bcpos(pt
, ins
) - 1;
103 if (pos
> pt
->sizebc
) { /* Undo the effects of lj_trace_exit for JLOOP. */
104 if (bc_isret(bc_op(ins
[-1]))) {
105 GCtrace
*T
= (GCtrace
*)((char *)(ins
-1) - offsetof(GCtrace
, startins
));
106 pos
= proto_bcpos(pt
, mref(T
->startpc
, const BCIns
));
108 pos
= NO_BCPOS
; /* Punt in case of stack overflow for stitched trace. */
115 /* -- Line numbers -------------------------------------------------------- */
117 /* Get line number for a bytecode position. */
118 BCLine LJ_FASTCALL
lj_debug_line(GCproto
*pt
, BCPos pc
)
120 const void *lineinfo
= proto_lineinfo(pt
);
121 if (pc
<= pt
->sizebc
&& lineinfo
) {
122 BCLine first
= pt
->firstline
;
123 if (pc
== pt
->sizebc
) return first
+ pt
->numline
;
124 if (pc
-- == 0) return first
;
125 if (pt
->numline
< 256)
126 return first
+ (BCLine
)((const uint8_t *)lineinfo
)[pc
];
127 else if (pt
->numline
< 65536)
128 return first
+ (BCLine
)((const uint16_t *)lineinfo
)[pc
];
130 return first
+ (BCLine
)((const uint32_t *)lineinfo
)[pc
];
135 /* Get line number for function/frame. */
136 static BCLine
debug_frameline(lua_State
*L
, GCfunc
*fn
, cTValue
*nextframe
)
138 BCPos pc
= debug_framepc(L
, fn
, nextframe
);
139 if (pc
!= NO_BCPOS
) {
140 GCproto
*pt
= funcproto(fn
);
141 lj_assertL(pc
<= pt
->sizebc
, "PC out of range");
142 return lj_debug_line(pt
, pc
);
147 /* -- Variable names ------------------------------------------------------ */
149 /* Get name of a local variable from slot number and PC. */
150 static const char *debug_varname(const GCproto
*pt
, BCPos pc
, BCReg slot
)
152 const char *p
= (const char *)proto_varinfo(pt
);
156 const char *name
= p
;
157 uint32_t vn
= *(const uint8_t *)p
;
158 BCPos startpc
, endpc
;
159 if (vn
< VARNAME__MAX
) {
160 if (vn
== VARNAME_END
) break; /* End of varinfo. */
162 do { p
++; } while (*(const uint8_t *)p
); /* Skip over variable name. */
165 lastpc
= startpc
= lastpc
+ lj_buf_ruleb128(&p
);
166 if (startpc
> pc
) break;
167 endpc
= startpc
+ lj_buf_ruleb128(&p
);
168 if (pc
< endpc
&& slot
-- == 0) {
169 if (vn
< VARNAME__MAX
) {
170 #define VARNAMESTR(name, str) str "\0"
171 name
= VARNAMEDEF(VARNAMESTR
);
173 if (--vn
) while (*name
++ || --vn
) ;
182 /* Get name of local variable from 1-based slot number and function/frame. */
183 static TValue
*debug_localname(lua_State
*L
, const lua_Debug
*ar
,
184 const char **name
, BCReg slot1
)
186 uint32_t offset
= (uint32_t)ar
->i_ci
& 0xffff;
187 uint32_t size
= (uint32_t)ar
->i_ci
>> 16;
188 TValue
*frame
= tvref(L
->stack
) + offset
;
189 TValue
*nextframe
= size
? frame
+ size
: NULL
;
190 GCfunc
*fn
= frame_func(frame
);
191 BCPos pc
= debug_framepc(L
, fn
, nextframe
);
192 if (!nextframe
) nextframe
= L
->top
+LJ_FR2
;
193 if ((int)slot1
< 0) { /* Negative slot number is for varargs. */
194 if (pc
!= NO_BCPOS
) {
195 GCproto
*pt
= funcproto(fn
);
196 if ((pt
->flags
& PROTO_VARARG
)) {
197 slot1
= pt
->numparams
+ (BCReg
)(-(int)slot1
);
198 if (frame_isvarg(frame
)) { /* Vararg frame has been set up? (pc!=0) */
200 frame
= frame_prevd(frame
);
202 if (frame
+ slot1
+LJ_FR2
< nextframe
) {
210 if (pc
!= NO_BCPOS
&&
211 (*name
= debug_varname(funcproto(fn
), pc
, slot1
-1)) != NULL
)
213 else if (slot1
> 0 && frame
+ slot1
+LJ_FR2
< nextframe
)
214 *name
= "(*temporary)";
218 /* Get name of upvalue. */
219 const char *lj_debug_uvname(GCproto
*pt
, uint32_t idx
)
221 const uint8_t *p
= proto_uvinfo(pt
);
222 lj_assertX(idx
< pt
->sizeuv
, "bad upvalue index");
224 if (idx
) while (*p
++ || --idx
) ;
225 return (const char *)p
;
228 /* Get name and value of upvalue. */
229 const char *lj_debug_uvnamev(cTValue
*o
, uint32_t idx
, TValue
**tvp
, GCobj
**op
)
232 GCfunc
*fn
= funcV(o
);
234 GCproto
*pt
= funcproto(fn
);
235 if (idx
< pt
->sizeuv
) {
236 GCobj
*uvo
= gcref(fn
->l
.uvptr
[idx
]);
237 *tvp
= uvval(&uvo
->uv
);
239 return lj_debug_uvname(pt
, idx
);
242 if (idx
< fn
->c
.nupvalues
) {
243 *tvp
= &fn
->c
.upvalue
[idx
];
252 /* Deduce name of an object from slot number and PC. */
253 const char *lj_debug_slotname(GCproto
*pt
, const BCIns
*ip
, BCReg slot
,
258 lname
= debug_varname(pt
, proto_bcpos(pt
, ip
), slot
);
259 if (lname
!= NULL
) { *name
= lname
; return "local"; }
260 while (--ip
> proto_bc(pt
)) {
262 BCOp op
= bc_op(ins
);
263 BCReg ra
= bc_a(ins
);
264 if (bcmode_a(op
) == BCMbase
) {
265 if (slot
>= ra
&& (op
!= BC_KNIL
|| slot
<= bc_d(ins
)))
267 } else if (bcmode_a(op
) == BCMdst
&& ra
== slot
) {
268 switch (bc_op(ins
)) {
270 if (ra
== slot
) { slot
= bc_d(ins
); goto restart
; }
273 *name
= strdata(gco2str(proto_kgc(pt
, ~(ptrdiff_t)bc_d(ins
))));
276 *name
= strdata(gco2str(proto_kgc(pt
, ~(ptrdiff_t)bc_c(ins
))));
277 if (ip
> proto_bc(pt
)) {
279 if (bc_op(insp
) == BC_MOV
&& bc_a(insp
) == ra
+1+LJ_FR2
&&
280 bc_d(insp
) == bc_b(ins
))
285 *name
= lj_debug_uvname(pt
, bc_d(ins
));
295 /* Deduce function name from caller of a frame. */
296 const char *lj_debug_funcname(lua_State
*L
, cTValue
*frame
, const char **name
)
301 if (frame
<= tvref(L
->stack
)+LJ_FR2
)
303 if (frame_isvarg(frame
))
304 frame
= frame_prevd(frame
);
305 pframe
= frame_prev(frame
);
306 fn
= frame_func(pframe
);
307 pc
= debug_framepc(L
, fn
, frame
);
308 if (pc
!= NO_BCPOS
) {
309 GCproto
*pt
= funcproto(fn
);
310 const BCIns
*ip
= &proto_bc(pt
)[check_exp(pc
< pt
->sizebc
, pc
)];
311 MMS mm
= bcmode_mm(bc_op(*ip
));
313 BCReg slot
= bc_a(*ip
);
314 if (bc_op(*ip
) == BC_ITERC
) slot
-= 3;
315 return lj_debug_slotname(pt
, ip
, slot
, name
);
316 } else if (mm
!= MM__MAX
) {
317 *name
= strdata(mmname_str(G(L
), mm
));
324 /* -- Source code locations ----------------------------------------------- */
326 /* Generate shortened source name. */
327 void lj_debug_shortname(char *out
, GCstr
*str
, BCLine line
)
329 const char *src
= strdata(str
);
331 strncpy(out
, src
+1, LUA_IDSIZE
); /* Remove first char. */
332 out
[LUA_IDSIZE
-1] = '\0'; /* Ensures null termination. */
333 } else if (*src
== '@') { /* Output "source", or "...source". */
334 size_t len
= str
->len
-1;
335 src
++; /* Skip the `@' */
336 if (len
>= LUA_IDSIZE
) {
337 src
+= len
-(LUA_IDSIZE
-4); /* Get last part of file name. */
338 *out
++ = '.'; *out
++ = '.'; *out
++ = '.';
341 } else { /* Output [string "string"] or [builtin:name]. */
342 size_t len
; /* Length, up to first control char. */
343 for (len
= 0; len
< LUA_IDSIZE
-12; len
++)
344 if (((const unsigned char *)src
)[len
] < ' ') break;
345 strcpy(out
, line
== ~(BCLine
)0 ? "[builtin:" : "[string \""); out
+= 9;
346 if (src
[len
] != '\0') { /* Must truncate? */
347 if (len
> LUA_IDSIZE
-15) len
= LUA_IDSIZE
-15;
348 strncpy(out
, src
, len
); out
+= len
;
349 strcpy(out
, "..."); out
+= 3;
351 strcpy(out
, src
); out
+= len
;
353 strcpy(out
, line
== ~(BCLine
)0 ? "]" : "\"]");
357 /* Add current location of a frame to error message. */
358 void lj_debug_addloc(lua_State
*L
, const char *msg
,
359 cTValue
*frame
, cTValue
*nextframe
)
362 GCfunc
*fn
= frame_func(frame
);
364 BCLine line
= debug_frameline(L
, fn
, nextframe
);
366 GCproto
*pt
= funcproto(fn
);
367 char buf
[LUA_IDSIZE
];
368 lj_debug_shortname(buf
, proto_chunkname(pt
), pt
->firstline
);
369 lj_strfmt_pushf(L
, "%s:%d: %s", buf
, line
, msg
);
374 lj_strfmt_pushf(L
, "%s", msg
);
377 /* Push location string for a bytecode position to Lua stack. */
378 void lj_debug_pushloc(lua_State
*L
, GCproto
*pt
, BCPos pc
)
380 GCstr
*name
= proto_chunkname(pt
);
381 const char *s
= strdata(name
);
382 MSize i
, len
= name
->len
;
383 BCLine line
= lj_debug_line(pt
, pc
);
384 if (pt
->firstline
== ~(BCLine
)0) {
385 lj_strfmt_pushf(L
, "builtin:%s", s
);
386 } else if (*s
== '@') {
388 for (i
= len
; i
> 0; i
--)
389 if (s
[i
] == '/' || s
[i
] == '\\') {
393 lj_strfmt_pushf(L
, "%s:%d", s
, line
);
394 } else if (len
> 40) {
395 lj_strfmt_pushf(L
, "%p:%d", pt
, line
);
396 } else if (*s
== '=') {
397 lj_strfmt_pushf(L
, "%s:%d", s
+1, line
);
399 lj_strfmt_pushf(L
, "\"%s\":%d", s
, line
);
403 /* -- Public debug API ---------------------------------------------------- */
405 /* lua_getupvalue() and lua_setupvalue() are in lj_api.c. */
407 LUA_API
const char *lua_getlocal(lua_State
*L
, const lua_Debug
*ar
, int n
)
409 const char *name
= NULL
;
411 TValue
*o
= debug_localname(L
, ar
, &name
, (BCReg
)n
);
413 copyTV(L
, L
->top
, o
);
416 } else if (tvisfunc(L
->top
-1) && isluafunc(funcV(L
->top
-1))) {
417 name
= debug_varname(funcproto(funcV(L
->top
-1)), 0, (BCReg
)n
-1);
422 LUA_API
const char *lua_setlocal(lua_State
*L
, const lua_Debug
*ar
, int n
)
424 const char *name
= NULL
;
425 TValue
*o
= debug_localname(L
, ar
, &name
, (BCReg
)n
);
427 copyTV(L
, o
, L
->top
-1);
432 int lj_debug_getinfo(lua_State
*L
, const char *what
, lj_Debug
*ar
, int ext
)
434 int opt_f
= 0, opt_L
= 0;
435 TValue
*frame
= NULL
;
436 TValue
*nextframe
= NULL
;
439 TValue
*func
= L
->top
- 1;
440 if (!tvisfunc(func
)) return 0;
445 uint32_t offset
= (uint32_t)ar
->i_ci
& 0xffff;
446 uint32_t size
= (uint32_t)ar
->i_ci
>> 16;
447 lj_assertL(offset
!= 0, "bad frame offset");
448 frame
= tvref(L
->stack
) + offset
;
449 if (size
) nextframe
= frame
+ size
;
450 lj_assertL(frame
<= tvref(L
->maxstack
) &&
451 (!nextframe
|| nextframe
<= tvref(L
->maxstack
)),
452 "broken frame chain");
453 fn
= frame_func(frame
);
454 lj_assertL(fn
->c
.gct
== ~LJ_TFUNC
, "bad frame function");
456 for (; *what
; what
++) {
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
, pt
->firstline
);
464 ar
->linedefined
= (int)firstline
;
465 ar
->lastlinedefined
= (int)(firstline
+ pt
->numline
);
466 ar
->what
= (firstline
|| !pt
->numline
) ? "Lua" : "main";
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;
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
;
483 GCproto
*pt
= funcproto(fn
);
484 ar
->nparams
= pt
->numparams
;
485 ar
->isvararg
= !!(pt
->flags
& PROTO_VARARG
);
491 } else if (*what
== 'n') {
492 ar
->namewhat
= frame
? lj_debug_funcname(L
, frame
, &ar
->name
) : NULL
;
493 if (ar
->namewhat
== NULL
) {
497 } else if (*what
== 'f') {
499 } else if (*what
== 'L') {
502 return 0; /* Bad option. */
506 setfuncV(L
, L
->top
, fn
);
511 GCtab
*t
= lj_tab_new(L
, 0, 0);
512 GCproto
*pt
= funcproto(fn
);
513 const void *lineinfo
= proto_lineinfo(pt
);
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);
526 settabV(L
, L
->top
, t
);
535 LUA_API
int lua_getinfo(lua_State
*L
, const char *what
, lua_Debug
*ar
)
537 return lj_debug_getinfo(L
, what
, (lj_Debug
*)ar
, 0);
540 LUA_API
int lua_getstack(lua_State
*L
, int level
, lua_Debug
*ar
)
543 cTValue
*frame
= lj_debug_frame(L
, level
, &size
);
545 ar
->i_ci
= (size
<< 16) + (int)(frame
- tvref(L
->stack
));
548 ar
->i_ci
= level
- size
;
554 /* Put the chunkname into a buffer. */
555 static int debug_putchunkname(SBuf
*sb
, GCproto
*pt
, int pathstrip
)
557 GCstr
*name
= proto_chunkname(pt
);
558 const char *p
= strdata(name
);
559 if (pt
->firstline
== ~(BCLine
)0) {
560 lj_buf_putmem(sb
, "[builtin:", 9);
561 lj_buf_putstr(sb
, name
);
562 lj_buf_putb(sb
, ']');
565 if (*p
== '=' || *p
== '@') {
566 MSize len
= name
->len
-1;
570 for (i
= len
-1; i
>= 0; i
--)
571 if (p
[i
] == '/' || p
[i
] == '\\') {
577 lj_buf_putmem(sb
, p
, len
);
579 lj_buf_putmem(sb
, "[string]", 8);
584 /* Put a compact stack dump into a buffer. */
585 void lj_debug_dumpstack(lua_State
*L
, SBuf
*sb
, const char *fmt
, int depth
)
587 int level
= 0, dir
= 1, pathstrip
= 1;
589 if (depth
< 0) { level
= ~depth
; depth
= dir
= -1; } /* Reverse frames. */
590 while (level
!= depth
) { /* Loop through all frame. */
592 cTValue
*frame
= lj_debug_frame(L
, level
, &size
);
594 cTValue
*nextframe
= size
? frame
+size
: NULL
;
595 GCfunc
*fn
= frame_func(frame
);
596 const uint8_t *p
= (const uint8_t *)fmt
;
600 case 'p': /* Preserve full path. */
603 case 'F': case 'f': { /* Dump function name. */
605 const char *what
= lj_debug_funcname(L
, frame
, &name
);
607 if (c
== 'F' && isluafunc(fn
)) { /* Dump module:name for 'F'. */
608 GCproto
*pt
= funcproto(fn
);
609 if (pt
->firstline
!= ~(BCLine
)0) { /* Not a bytecode builtin. */
610 debug_putchunkname(sb
, pt
, pathstrip
);
611 lj_buf_putb(sb
, ':');
614 lj_buf_putmem(sb
, name
, (MSize
)strlen(name
));
616 } /* else: can't derive a name, dump module:line. */
619 case 'l': /* Dump module:line. */
621 GCproto
*pt
= funcproto(fn
);
622 if (debug_putchunkname(sb
, pt
, pathstrip
)) {
623 /* Regular Lua function. */
624 BCLine line
= c
== 'l' ? debug_frameline(L
, fn
, nextframe
) :
626 lj_buf_putb(sb
, ':');
627 lj_strfmt_putint(sb
, line
>= 0 ? line
: pt
->firstline
);
629 } else if (isffunc(fn
)) { /* Dump numbered builtins. */
630 lj_buf_putmem(sb
, "[builtin#", 9);
631 lj_strfmt_putint(sb
, fn
->c
.ffid
);
632 lj_buf_putb(sb
, ']');
633 } else { /* Dump C function address. */
634 lj_buf_putb(sb
, '@');
635 lj_strfmt_putptr(sb
, fn
->c
.f
);
638 case 'Z': /* Zap trailing separator. */
639 lastlen
= sbuflen(sb
);
646 } else if (dir
== 1) {
649 level
-= size
; /* Reverse frame order: quickly skip missing level. */
654 sb
->w
= sb
->b
+ lastlen
; /* Zap trailing separator. */
658 /* Number of frames for the leading and trailing part of a traceback. */
659 #define TRACEBACK_LEVELS1 12
660 #define TRACEBACK_LEVELS2 10
662 LUALIB_API
void luaL_traceback (lua_State
*L
, lua_State
*L1
, const char *msg
,
665 int top
= (int)(L
->top
- L
->base
);
666 int lim
= TRACEBACK_LEVELS1
;
668 if (msg
) lua_pushfstring(L
, "%s\n", msg
);
669 lua_pushliteral(L
, "stack traceback:");
670 while (lua_getstack(L1
, level
++, &ar
)) {
673 if (!lua_getstack(L1
, level
+ TRACEBACK_LEVELS2
, &ar
)) {
676 lua_pushliteral(L
, "\n\t...");
677 lua_getstack(L1
, -10, &ar
);
678 level
= ar
.i_ci
- TRACEBACK_LEVELS2
;
683 lua_getinfo(L1
, "Snlf", &ar
);
684 fn
= funcV(L1
->top
-1); L1
->top
--;
685 if (isffunc(fn
) && !*ar
.namewhat
)
686 lua_pushfstring(L
, "\n\t[builtin#%d]:", fn
->c
.ffid
);
688 lua_pushfstring(L
, "\n\t%s:", ar
.short_src
);
689 if (ar
.currentline
> 0)
690 lua_pushfstring(L
, "%d:", ar
.currentline
);
692 lua_pushfstring(L
, " in function " LUA_QS
, ar
.name
);
694 if (*ar
.what
== 'm') {
695 lua_pushliteral(L
, " in main chunk");
696 } else if (*ar
.what
== 'C') {
697 lua_pushfstring(L
, " at %p", fn
->c
.f
);
699 lua_pushfstring(L
, " in function <%s:%d>",
700 ar
.short_src
, ar
.linedefined
);
703 if ((int)(L
->top
- L
->base
) - top
>= 15)
704 lua_concat(L
, (int)(L
->top
- L
->base
) - top
);
706 lua_concat(L
, (int)(L
->top
- L
->base
) - top
);