1 /*
2 ** Debugging and introspection.
3 ** Copyright (C) 2005-2021 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_buf.h"
13 #include "lj_tab.h"
14 #include "lj_state.h"
15 #include "lj_frame.h"
16 #include "lj_bc.h"
17 #include "lj_strfmt.h"
18 #if LJ_HASJIT
19 #include "lj_jit.h"
20 #endif
21 
22 /* -- Frames -------------------------------------------------------------- */
23 
24 /* Get frame corresponding to a level. */
lj_debug_frame(lua_State * L,int level,int * size)25 cTValue *lj_debug_frame(lua_State *L, int level, int *size)
26 {
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(). */
32     if (level-- == 0) {
33       *size = (int)(nextframe - frame);
34       return frame;  /* Level found. */
35     }
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);
43     }
44   }
45   *size = level;
46   return NULL;  /* Level not found. */
47 }
48 
49 /* Invalid bytecode position. */
50 #define NO_BCPOS	(~(BCPos)0)
51 
52 /* Return bytecode position for function/frame or NO_BCPOS. */
debug_framepc(lua_State * L,GCfunc * fn,cTValue * nextframe)53 static BCPos debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe)
54 {
55   const BCIns *ins;
56   GCproto *pt;
57   BCPos pos;
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. */
61     return NO_BCPOS;
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))
65       return NO_BCPOS;
66     ins = cframe_pc(cf);  /* Only happens during error/hook handling. */
67   } else {
68     if (frame_islua(nextframe)) {
69       ins = frame_pc(nextframe);
70     } else if (frame_iscont(nextframe)) {
71       ins = frame_contpc(nextframe);
72     } else {
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;
76       for (;;) {
77 	if (cf == NULL)
78 	  return NO_BCPOS;
79 	while (cframe_nres(cf) < 0) {
80 	  if (f >= restorestack(L, -cframe_nres(cf)))
81 	    break;
82 	  cf = cframe_raw(cframe_prev(cf));
83 	  if (cf == NULL)
84 	    return NO_BCPOS;
85 	}
86 	if (f < nextframe)
87 	  break;
88 	if (frame_islua(f)) {
89 	  f = frame_prevl(f);
90 	} else {
91 	  if (frame_isc(f) || (frame_iscont(f) && frame_iscont_fficb(f)))
92 	    cf = cframe_raw(cframe_prev(cf));
93 	  f = frame_prevd(f);
94 	}
95       }
96       ins = cframe_pc(cf);
97       if (!ins) return NO_BCPOS;
98     }
99   }
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     lj_assertL(bc_isret(bc_op(ins[-1])), "return bytecode expected");
106     pos = proto_bcpos(pt, mref(T->startpc, const BCIns));
107   }
108 #endif
109   return pos;
110 }
111 
lj_debug_framepc(lua_State * L,GCfunc * fn,cTValue * nextframe)112 LJ_FUNC BCPos lj_debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe)
113 {
114   return debug_framepc(L, fn, nextframe);
115 }
116 
117 /* -- Line numbers -------------------------------------------------------- */
118 
119 /* Get line number for a bytecode position. */
lj_debug_line(GCproto * pt,BCPos pc)120 BCLine LJ_FASTCALL lj_debug_line(GCproto *pt, BCPos pc)
121 {
122   const void *lineinfo = proto_lineinfo(pt);
123   if (pc <= pt->sizebc && lineinfo) {
124     BCLine first = pt->firstline;
125     if (pc == pt->sizebc) return first + pt->numline;
126     if (pc-- == 0) return first;
127     if (pt->numline < 256)
128       return first + (BCLine)((const uint8_t *)lineinfo)[pc];
129     else if (pt->numline < 65536)
130       return first + (BCLine)((const uint16_t *)lineinfo)[pc];
131     else
132       return first + (BCLine)((const uint32_t *)lineinfo)[pc];
133   }
134   return 0;
135 }
136 
137 /* Get line number for function/frame. */
debug_frameline(lua_State * L,GCfunc * fn,cTValue * nextframe)138 static BCLine debug_frameline(lua_State *L, GCfunc *fn, cTValue *nextframe)
139 {
140   BCPos pc = debug_framepc(L, fn, nextframe);
141   if (pc != NO_BCPOS) {
142     GCproto *pt = funcproto(fn);
143     lj_assertL(pc <= pt->sizebc, "PC out of range");
144     return lj_debug_line(pt, pc);
145   }
146   return -1;
147 }
148 
149 /* -- Variable names ------------------------------------------------------ */
150 
151 /* Get name of a local variable from slot number and PC. */
debug_varname(const GCproto * pt,BCPos pc,BCReg slot)152 static const char *debug_varname(const GCproto *pt, BCPos pc, BCReg slot)
153 {
154   const char *p = (const char *)proto_varinfo(pt);
155   if (p) {
156     BCPos lastpc = 0;
157     for (;;) {
158       const char *name = p;
159       uint32_t vn = *(const uint8_t *)p;
160       BCPos startpc, endpc;
161       if (vn < VARNAME__MAX) {
162 	if (vn == VARNAME_END) break;  /* End of varinfo. */
163       } else {
164 	do { p++; } while (*(const uint8_t *)p);  /* Skip over variable name. */
165       }
166       p++;
167       lastpc = startpc = lastpc + lj_buf_ruleb128(&p);
168       if (startpc > pc) break;
169       endpc = startpc + lj_buf_ruleb128(&p);
170       if (pc < endpc && slot-- == 0) {
171 	if (vn < VARNAME__MAX) {
172 #define VARNAMESTR(name, str)	str "\0"
173 	  name = VARNAMEDEF(VARNAMESTR);
174 #undef VARNAMESTR
175 	  if (--vn) while (*name++ || --vn) ;
176 	}
177 	return name;
178       }
179     }
180   }
181   return NULL;
182 }
183 
184 /* Get name of local variable from 1-based slot number and function/frame. */
debug_localname(lua_State * L,const lua_Debug * ar,const char ** name,BCReg slot1)185 static TValue *debug_localname(lua_State *L, const lua_Debug *ar,
186 			       const char **name, BCReg slot1)
187 {
188   uint32_t offset = (uint32_t)ar->i_ci & 0xffff;
189   uint32_t size = (uint32_t)ar->i_ci >> 16;
190   TValue *frame = tvref(L->stack) + offset;
191   TValue *nextframe = size ? frame + size : NULL;
192   GCfunc *fn = frame_func(frame);
193   BCPos pc = debug_framepc(L, fn, nextframe);
194   if (!nextframe) nextframe = L->top+LJ_FR2;
195   if ((int)slot1 < 0) {  /* Negative slot number is for varargs. */
196     if (pc != NO_BCPOS) {
197       GCproto *pt = funcproto(fn);
198       if ((pt->flags & PROTO_VARARG)) {
199 	slot1 = pt->numparams + (BCReg)(-(int)slot1);
200 	if (frame_isvarg(frame)) {  /* Vararg frame has been set up? (pc!=0) */
201 	  nextframe = frame;
202 	  frame = frame_prevd(frame);
203 	}
204 	if (frame + slot1+LJ_FR2 < nextframe) {
205 	  *name = "(*vararg)";
206 	  return frame+slot1;
207 	}
208       }
209     }
210     return NULL;
211   }
212   if (pc != NO_BCPOS &&
213       (*name = debug_varname(funcproto(fn), pc, slot1-1)) != NULL)
214     ;
215   else if (slot1 > 0 && frame + slot1+LJ_FR2 < nextframe)
216     *name = "(*temporary)";
217   return frame+slot1;
218 }
219 
220 /* Get name of upvalue. */
lj_debug_uvname(GCproto * pt,uint32_t idx)221 const char *lj_debug_uvname(GCproto *pt, uint32_t idx)
222 {
223   const uint8_t *p = proto_uvinfo(pt);
224   lj_assertX(idx < pt->sizeuv, "bad upvalue index");
225   if (!p) return "";
226   if (idx) while (*p++ || --idx) ;
227   return (const char *)p;
228 }
229 
230 /* Get name and value of upvalue. */
lj_debug_uvnamev(cTValue * o,uint32_t idx,TValue ** tvp,GCobj ** op)231 const char *lj_debug_uvnamev(cTValue *o, uint32_t idx, TValue **tvp, GCobj **op)
232 {
233   if (tvisfunc(o)) {
234     GCfunc *fn = funcV(o);
235     if (isluafunc(fn)) {
236       GCproto *pt = funcproto(fn);
237       if (idx < pt->sizeuv) {
238 	GCobj *uvo = gcref(fn->l.uvptr[idx]);
239 	*tvp = uvval(&uvo->uv);
240 	*op = uvo;
241 	return lj_debug_uvname(pt, idx);
242       }
243     } else {
244       if (idx < fn->c.nupvalues) {
245 	*tvp = &fn->c.upvalue[idx];
246 	*op = obj2gco(fn);
247 	return "";
248       }
249     }
250   }
251   return NULL;
252 }
253 
254 /* Deduce name of an object from slot number and PC. */
lj_debug_slotname(GCproto * pt,const BCIns * ip,BCReg slot,const char ** name)255 const char *lj_debug_slotname(GCproto *pt, const BCIns *ip, BCReg slot,
256 			      const char **name)
257 {
258   const char *lname;
259 restart:
260   lname = debug_varname(pt, proto_bcpos(pt, ip), slot);
261   if (lname != NULL) { *name = lname; return "local"; }
262   while (--ip > proto_bc(pt)) {
263     BCIns ins = *ip;
264     BCOp op = bc_op(ins);
265     BCReg ra = bc_a(ins);
266     if (bcmode_a(op) == BCMbase) {
267       if (slot >= ra && (op != BC_KNIL || slot <= bc_d(ins)))
268 	return NULL;
269     } else if (bcmode_a(op) == BCMdst && ra == slot) {
270       switch (bc_op(ins)) {
271       case BC_MOV:
272 	if (ra == slot) { slot = bc_d(ins); goto restart; }
273 	break;
274       case BC_GGET:
275 	*name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_d(ins))));
276 	return "global";
277       case BC_TGETS:
278 	*name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_c(ins))));
279 	if (ip > proto_bc(pt)) {
280 	  BCIns insp = ip[-1];
281 	  if (bc_op(insp) == BC_MOV && bc_a(insp) == ra+1+LJ_FR2 &&
282 	      bc_d(insp) == bc_b(ins))
283 	    return "method";
284 	}
285 	return "field";
286       case BC_UGET:
287 	*name = lj_debug_uvname(pt, bc_d(ins));
288 	return "upvalue";
289       default:
290 	return NULL;
291       }
292     }
293   }
294   return NULL;
295 }
296 
297 /* Deduce function name from caller of a frame. */
lj_debug_funcname(lua_State * L,cTValue * frame,const char ** name)298 const char *lj_debug_funcname(lua_State *L, cTValue *frame, const char **name)
299 {
300   cTValue *pframe;
301   GCfunc *fn;
302   BCPos pc;
303   if (frame <= tvref(L->stack)+LJ_FR2)
304     return NULL;
305   if (frame_isvarg(frame))
306     frame = frame_prevd(frame);
307   pframe = frame_prev(frame);
308   fn = frame_func(pframe);
309   pc = debug_framepc(L, fn, frame);
310   if (pc != NO_BCPOS) {
311     GCproto *pt = funcproto(fn);
312     const BCIns *ip = &proto_bc(pt)[check_exp(pc < pt->sizebc, pc)];
313     MMS mm = bcmode_mm(bc_op(*ip));
314     if (mm == MM_call) {
315       BCReg slot = bc_a(*ip);
316       if (bc_op(*ip) == BC_ITERC) slot -= 3;
317       return lj_debug_slotname(pt, ip, slot, name);
318     } else if (mm != MM__MAX) {
319       *name = strdata(mmname_str(G(L), mm));
320       return "metamethod";
321     }
322   }
323   return NULL;
324 }
325 
326 /* -- Source code locations ----------------------------------------------- */
327 
328 /* Generate shortened source name. */
lj_debug_shortname(char * out,GCstr * str,BCLine line)329 void lj_debug_shortname(char *out, GCstr *str, BCLine line)
330 {
331   const char *src = strdata(str);
332   if (*src == '=') {
333     strncpy(out, src+1, LUA_IDSIZE);  /* Remove first char. */
334     out[LUA_IDSIZE-1] = '\0';  /* Ensures null termination. */
335   } else if (*src == '@') {  /* Output "source", or "...source". */
336     size_t len = str->len-1;
337     src++;  /* Skip the `@' */
338     if (len >= LUA_IDSIZE) {
339       src += len-(LUA_IDSIZE-4);  /* Get last part of file name. */
340       *out++ = '.'; *out++ = '.'; *out++ = '.';
341     }
342     strcpy(out, src);
343   } else {  /* Output [string "string"] or [builtin:name]. */
344     size_t len;  /* Length, up to first control char. */
345     for (len = 0; len < LUA_IDSIZE-12; len++)
346       if (((const unsigned char *)src)[len] < ' ') break;
347     strcpy(out, line == ~(BCLine)0 ? "[builtin:" : "[string \""); out += 9;
348     if (src[len] != '\0') {  /* Must truncate? */
349       if (len > LUA_IDSIZE-15) len = LUA_IDSIZE-15;
350       strncpy(out, src, len); out += len;
351       strcpy(out, "..."); out += 3;
352     } else {
353       strcpy(out, src); out += len;
354     }
355     strcpy(out, line == ~(BCLine)0 ? "]" : "\"]");
356   }
357 }
358 
359 /* Add current location of a frame to error message. */
lj_debug_addloc(lua_State * L,const char * msg,cTValue * frame,cTValue * nextframe)360 void lj_debug_addloc(lua_State *L, const char *msg,
361 		     cTValue *frame, cTValue *nextframe)
362 {
363   if (frame) {
364     GCfunc *fn = frame_func(frame);
365     if (isluafunc(fn)) {
366       BCLine line = debug_frameline(L, fn, nextframe);
367       if (line >= 0) {
368 	GCproto *pt = funcproto(fn);
369 	char buf[LUA_IDSIZE];
370 	lj_debug_shortname(buf, proto_chunkname(pt), pt->firstline);
371 	lj_strfmt_pushf(L, "%s:%d: %s", buf, line, msg);
372 	return;
373       }
374     }
375   }
376   lj_strfmt_pushf(L, "%s", msg);
377 }
378 
379 /* Push location string for a bytecode position to Lua stack. */
lj_debug_pushloc(lua_State * L,GCproto * pt,BCPos pc)380 void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc)
381 {
382   GCstr *name = proto_chunkname(pt);
383   const char *s = strdata(name);
384   MSize i, len = name->len;
385   BCLine line = lj_debug_line(pt, pc);
386   if (pt->firstline == ~(BCLine)0) {
387     lj_strfmt_pushf(L, "builtin:%s", s);
388   } else if (*s == '@') {
389     s++; len--;
390     for (i = len; i > 0; i--)
391       if (s[i] == '/' || s[i] == '\\') {
392 	s += i+1;
393 	break;
394       }
395     lj_strfmt_pushf(L, "%s:%d", s, line);
396   } else if (len > 40) {
397     lj_strfmt_pushf(L, "%p:%d", pt, line);
398   } else if (*s == '=') {
399     lj_strfmt_pushf(L, "%s:%d", s+1, line);
400   } else {
401     lj_strfmt_pushf(L, "\"%s\":%d", s, line);
402   }
403 }
404 
405 /* -- Public debug API ---------------------------------------------------- */
406 
407 /* lua_getupvalue() and lua_setupvalue() are in lj_api.c. */
408 
lua_getlocal(lua_State * L,const lua_Debug * ar,int n)409 LUA_API const char *lua_getlocal(lua_State *L, const lua_Debug *ar, int n)
410 {
411   const char *name = NULL;
412   if (ar) {
413     TValue *o = debug_localname(L, ar, &name, (BCReg)n);
414     if (name) {
415       copyTV(L, L->top, o);
416       incr_top(L);
417     }
418   } else if (tvisfunc(L->top-1) && isluafunc(funcV(L->top-1))) {
419     name = debug_varname(funcproto(funcV(L->top-1)), 0, (BCReg)n-1);
420   }
421   return name;
422 }
423 
lua_setlocal(lua_State * L,const lua_Debug * ar,int n)424 LUA_API const char *lua_setlocal(lua_State *L, const lua_Debug *ar, int n)
425 {
426   const char *name = NULL;
427   TValue *o = debug_localname(L, ar, &name, (BCReg)n);
428   if (name)
429     copyTV(L, o, L->top-1);
430   L->top--;
431   return name;
432 }
433 
lj_debug_getinfo(lua_State * L,const char * what,lj_Debug * ar,int ext)434 int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar, int ext)
435 {
436   int opt_f = 0, opt_L = 0;
437   TValue *frame = NULL;
438   TValue *nextframe = NULL;
439   GCfunc *fn;
440   if (*what == '>') {
441     TValue *func = L->top - 1;
442     if (!tvisfunc(func)) return 0;
443     fn = funcV(func);
444     L->top--;
445     what++;
446   } else {
447     uint32_t offset = (uint32_t)ar->i_ci & 0xffff;
448     uint32_t size = (uint32_t)ar->i_ci >> 16;
449     lj_assertL(offset != 0, "bad frame offset");
450     frame = tvref(L->stack) + offset;
451     if (size) nextframe = frame + size;
452     lj_assertL(frame <= tvref(L->maxstack) &&
453 	       (!nextframe || nextframe <= tvref(L->maxstack)),
454 	       "broken frame chain");
455     fn = frame_func(frame);
456     lj_assertL(fn->c.gct == ~LJ_TFUNC, "bad frame function");
457   }
458   for (; *what; what++) {
459     if (*what == 'S') {
460       if (isluafunc(fn)) {
461 	GCproto *pt = funcproto(fn);
462 	BCLine firstline = pt->firstline;
463 	GCstr *name = proto_chunkname(pt);
464 	ar->source = strdata(name);
465 	lj_debug_shortname(ar->short_src, name, pt->firstline);
466 	ar->linedefined = (int)firstline;
467 	ar->lastlinedefined = (int)(firstline + pt->numline);
468 	ar->what = (firstline || !pt->numline) ? "Lua" : "main";
469       } else {
470 	ar->source = "=[C]";
471 	ar->short_src[0] = '[';
472 	ar->short_src[1] = 'C';
473 	ar->short_src[2] = ']';
474 	ar->short_src[3] = '\0';
475 	ar->linedefined = -1;
476 	ar->lastlinedefined = -1;
477 	ar->what = "C";
478       }
479     } else if (*what == 'l') {
480       ar->currentline = frame ? debug_frameline(L, fn, nextframe) : -1;
481     } else if (*what == 'u') {
482       ar->nups = fn->c.nupvalues;
483       if (ext) {
484 	if (isluafunc(fn)) {
485 	  GCproto *pt = funcproto(fn);
486 	  ar->nparams = pt->numparams;
487 	  ar->isvararg = !!(pt->flags & PROTO_VARARG);
488 	} else {
489 	  ar->nparams = 0;
490 	  ar->isvararg = 1;
491 	}
492       }
493     } else if (*what == 'n') {
494       ar->namewhat = frame ? lj_debug_funcname(L, frame, &ar->name) : NULL;
495       if (ar->namewhat == NULL) {
496 	ar->namewhat = "";
497 	ar->name = NULL;
498       }
499     } else if (*what == 'f') {
500       opt_f = 1;
501     } else if (*what == 'L') {
502       opt_L = 1;
503     } else {
504       return 0;  /* Bad option. */
505     }
506   }
507   if (opt_f) {
508     setfuncV(L, L->top, fn);
509     incr_top(L);
510   }
511   if (opt_L) {
512     if (isluafunc(fn)) {
513       GCtab *t = lj_tab_new(L, 0, 0);
514       GCproto *pt = funcproto(fn);
515       const void *lineinfo = proto_lineinfo(pt);
516       if (lineinfo) {
517 	BCLine first = pt->firstline;
518 	int sz = pt->numline < 256 ? 1 : pt->numline < 65536 ? 2 : 4;
519 	MSize i, szl = pt->sizebc-1;
520 	for (i = 0; i < szl; i++) {
521 	  BCLine line = first +
522 	    (sz == 1 ? (BCLine)((const uint8_t *)lineinfo)[i] :
523 	     sz == 2 ? (BCLine)((const uint16_t *)lineinfo)[i] :
524 	     (BCLine)((const uint32_t *)lineinfo)[i]);
525 	  setboolV(lj_tab_setint(L, t, line), 1);
526 	}
527       }
528       settabV(L, L->top, t);
529     } else {
530       setnilV(L->top);
531     }
532     incr_top(L);
533   }
534   return 1;  /* Ok. */
535 }
536 
lua_getinfo(lua_State * L,const char * what,lua_Debug * ar)537 LUA_API int lua_getinfo(lua_State *L, const char *what, lua_Debug *ar)
538 {
539   return lj_debug_getinfo(L, what, (lj_Debug *)ar, 0);
540 }
541 
lua_getstack(lua_State * L,int level,lua_Debug * ar)542 LUA_API int lua_getstack(lua_State *L, int level, lua_Debug *ar)
543 {
544   int size;
545   cTValue *frame = lj_debug_frame(L, level, &size);
546   if (frame) {
547     ar->i_ci = (size << 16) + (int)(frame - tvref(L->stack));
548     return 1;
549   } else {
550     ar->i_ci = level - size;
551     return 0;
552   }
553 }
554 
555 #if LJ_HASPROFILE
556 /* Put the chunkname into a buffer. */
debug_putchunkname(SBuf * sb,GCproto * pt,int pathstrip)557 static int debug_putchunkname(SBuf *sb, GCproto *pt, int pathstrip)
558 {
559   GCstr *name = proto_chunkname(pt);
560   const char *p = strdata(name);
561   if (pt->firstline == ~(BCLine)0) {
562     lj_buf_putmem(sb, "[builtin:", 9);
563     lj_buf_putstr(sb, name);
564     lj_buf_putb(sb, ']');
565     return 0;
566   }
567   if (*p == '=' || *p == '@') {
568     MSize len = name->len-1;
569     p++;
570     if (pathstrip) {
571       int i;
572       for (i = len-1; i >= 0; i--)
573 	if (p[i] == '/' || p[i] == '\\') {
574 	  len -= i+1;
575 	  p = p+i+1;
576 	  break;
577 	}
578     }
579     lj_buf_putmem(sb, p, len);
580   } else {
581     lj_buf_putmem(sb, "[string]", 8);
582   }
583   return 1;
584 }
585 
586 /* Put a compact stack dump into a buffer. */
lj_debug_dumpstack(lua_State * L,SBuf * sb,const char * fmt,int depth)587 void lj_debug_dumpstack(lua_State *L, SBuf *sb, const char *fmt, int depth)
588 {
589   int level = 0, dir = 1, pathstrip = 1;
590   MSize lastlen = 0;
591   if (depth < 0) { level = ~depth; depth = dir = -1; }  /* Reverse frames. */
592   while (level != depth) {  /* Loop through all frame. */
593     int size;
594     cTValue *frame = lj_debug_frame(L, level, &size);
595     if (frame) {
596       cTValue *nextframe = size ? frame+size : NULL;
597       GCfunc *fn = frame_func(frame);
598       const uint8_t *p = (const uint8_t *)fmt;
599       int c;
600       while ((c = *p++)) {
601 	switch (c) {
602 	case 'p':  /* Preserve full path. */
603 	  pathstrip = 0;
604 	  break;
605 	case 'F': case 'f': {  /* Dump function name. */
606 	  const char *name;
607 	  const char *what = lj_debug_funcname(L, frame, &name);
608 	  if (what) {
609 	    if (c == 'F' && isluafunc(fn)) {  /* Dump module:name for 'F'. */
610 	      GCproto *pt = funcproto(fn);
611 	      if (pt->firstline != ~(BCLine)0) {  /* Not a bytecode builtin. */
612 		debug_putchunkname(sb, pt, pathstrip);
613 		lj_buf_putb(sb, ':');
614 	      }
615 	    }
616 	    lj_buf_putmem(sb, name, (MSize)strlen(name));
617 	    break;
618 	  }  /* else: can't derive a name, dump module:line. */
619 	  }
620 	  /* fallthrough */
621 	case 'l':  /* Dump module:line. */
622 	  if (isluafunc(fn)) {
623 	    GCproto *pt = funcproto(fn);
624 	    if (debug_putchunkname(sb, pt, pathstrip)) {
625 	      /* Regular Lua function. */
626 	      BCLine line = c == 'l' ? debug_frameline(L, fn, nextframe) :
627 				       pt->firstline;
628 	      lj_buf_putb(sb, ':');
629 	      lj_strfmt_putint(sb, line >= 0 ? line : pt->firstline);
630 	    }
631 	  } else if (isffunc(fn)) {  /* Dump numbered builtins. */
632 	    lj_buf_putmem(sb, "[builtin#", 9);
633 	    lj_strfmt_putint(sb, fn->c.ffid);
634 	    lj_buf_putb(sb, ']');
635 	  } else {  /* Dump C function address. */
636 	    lj_buf_putb(sb, '@');
637 	    lj_strfmt_putptr(sb, fn->c.f);
638 	  }
639 	  break;
640 	case 'Z':  /* Zap trailing separator. */
641 	  lastlen = sbuflen(sb);
642 	  break;
643 	default:
644 	  lj_buf_putb(sb, c);
645 	  break;
646 	}
647       }
648     } else if (dir == 1) {
649       break;
650     } else {
651       level -= size;  /* Reverse frame order: quickly skip missing level. */
652     }
653     level += dir;
654   }
655   if (lastlen)
656     sb->w = sb->b + lastlen;  /* Zap trailing separator. */
657 }
658 #endif
659 
660 /* Number of frames for the leading and trailing part of a traceback. */
661 #define TRACEBACK_LEVELS1	12
662 #define TRACEBACK_LEVELS2	10
663 
luaL_traceback(lua_State * L,lua_State * L1,const char * msg,int level)664 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
665 				int level)
666 {
667   int top = (int)(L->top - L->base);
668   int lim = TRACEBACK_LEVELS1;
669   lua_Debug ar;
670   if (msg) lua_pushfstring(L, "%s\n", msg);
671   lua_pushliteral(L, "stack traceback:");
672   while (lua_getstack(L1, level++, &ar)) {
673     GCfunc *fn;
674     if (level > lim) {
675       if (!lua_getstack(L1, level + TRACEBACK_LEVELS2, &ar)) {
676 	level--;
677       } else {
678 	lua_pushliteral(L, "\n\t...");
679 	lua_getstack(L1, -10, &ar);
680 	level = ar.i_ci - TRACEBACK_LEVELS2;
681       }
682       lim = 2147483647;
683       continue;
684     }
685     lua_getinfo(L1, "Snlf", &ar);
686     fn = funcV(L1->top-1); L1->top--;
687     if (isffunc(fn) && !*ar.namewhat)
688       lua_pushfstring(L, "\n\t[builtin#%d]:", fn->c.ffid);
689     else
690       lua_pushfstring(L, "\n\t%s:", ar.short_src);
691     if (ar.currentline > 0)
692       lua_pushfstring(L, "%d:", ar.currentline);
693     if (*ar.namewhat) {
694       lua_pushfstring(L, " in function " LUA_QS, ar.name);
695     } else {
696       if (*ar.what == 'm') {
697 	lua_pushliteral(L, " in main chunk");
698       } else if (*ar.what == 'C') {
699 	lua_pushfstring(L, " at %p", fn->c.f);
700       } else {
701 	lua_pushfstring(L, " in function <%s:%d>",
702 			ar.short_src, ar.linedefined);
703       }
704     }
705     if ((int)(L->top - L->base) - top >= 15)
706       lua_concat(L, (int)(L->top - L->base) - top);
707   }
708   lua_concat(L, (int)(L->top - L->base) - top);
709 }
710 
711 #ifdef LUA_USE_TRACE_LOGS
712 
713 #include "lj_dispatch.h"
714 
715 #define MAX_TRACE_EVENTS  64
716 
717 enum {
718     LJ_TRACE_EVENT_ENTER,
719     LJ_TRACE_EVENT_EXIT,
720     LJ_TRACE_EVENT_START
721 };
722 
723 typedef struct {
724     int              event;
725     unsigned         traceno;
726     unsigned         exitno;
727     int              directexit;
728     const BCIns     *ins;
729     lua_State       *thread;
730     GCfunc          *fn;
731 } lj_trace_event_record_t;
732 
733 static lj_trace_event_record_t lj_trace_events[MAX_TRACE_EVENTS];
734 
735 static int  rb_start = 0;
736 static int  rb_end = 0;
737 static int  rb_full = 0;
738 
739 static void
lj_trace_log_event(lj_trace_event_record_t * rec)740 lj_trace_log_event(lj_trace_event_record_t *rec)
741 {
742   lj_trace_events[rb_end] = *rec;
743 
744   if (rb_full) {
745     rb_end++;
746     if (rb_end == MAX_TRACE_EVENTS) {
747       rb_end = 0;
748     }
749     rb_start = rb_end;
750 
751   } else {
752     rb_end++;
753     if (rb_end == MAX_TRACE_EVENTS) {
754       rb_end = 0;
755       rb_full = MAX_TRACE_EVENTS;
756     }
757   }
758 }
759 
760 static GCfunc*
lj_debug_top_frame_fn(lua_State * L,const BCIns * pc)761 lj_debug_top_frame_fn(lua_State *L, const BCIns *pc)
762 {
763   int size;
764   cTValue *frame;
765 
766   frame = lj_debug_frame(L, 0, &size);
767   if (frame == NULL) {
768     return NULL;
769   }
770 
771   return frame_func(frame);
772 }
773 
774 LJ_FUNC void LJ_FASTCALL
lj_log_trace_start_record(lua_State * L,unsigned traceno,const BCIns * pc,GCfunc * fn)775 lj_log_trace_start_record(lua_State *L, unsigned traceno, const BCIns *pc,
776   GCfunc *fn)
777 {
778   lj_trace_event_record_t  r;
779 
780   r.event = LJ_TRACE_EVENT_START;
781   r.thread = L;
782   r.ins = pc;
783   r.traceno = traceno;
784   r.fn = fn;
785 
786   lj_trace_log_event(&r);
787 }
788 
789 LJ_FUNC void LJ_FASTCALL
lj_log_trace_entry(lua_State * L,unsigned traceno,const BCIns * pc)790 lj_log_trace_entry(lua_State *L, unsigned traceno, const BCIns *pc)
791 {
792   lj_trace_event_record_t  r;
793 
794   r.event = LJ_TRACE_EVENT_ENTER;
795   r.thread = L;
796   r.ins = pc;
797   r.traceno = traceno;
798   r.fn = lj_debug_top_frame_fn(L, pc);
799 
800   lj_trace_log_event(&r);
801 }
802 
803 static void
lj_log_trace_exit_helper(lua_State * L,int vmstate,const BCIns * pc,int direct)804 lj_log_trace_exit_helper(lua_State *L, int vmstate, const BCIns *pc, int direct)
805 {
806   if (vmstate >= 0) {
807     lj_trace_event_record_t  r;
808 
809     jit_State *J = L2J(L);
810 
811     r.event = LJ_TRACE_EVENT_EXIT;
812     r.thread = L;
813     r.ins = pc;
814     r.traceno = vmstate;
815     r.exitno = J->exitno;
816     r.directexit = direct;
817     r.fn = lj_debug_top_frame_fn(L, pc);
818 
819     lj_trace_log_event(&r);
820   }
821 }
822 
823 LJ_FUNC void LJ_FASTCALL
lj_log_trace_normal_exit(lua_State * L,int vmstate,const BCIns * pc)824 lj_log_trace_normal_exit(lua_State *L, int vmstate, const BCIns *pc)
825 {
826   lj_log_trace_exit_helper(L, vmstate, pc, 0);
827 }
828 
829 LJ_FUNC void LJ_FASTCALL
lj_log_trace_direct_exit(lua_State * L,int vmstate,const BCIns * pc)830 lj_log_trace_direct_exit(lua_State *L, int vmstate, const BCIns *pc)
831 {
832   lj_log_trace_exit_helper(L, vmstate, pc, 1);
833 }
834 
835 #endif  /* LUA_USE_TRACE_LOGS */
836