FFI: Fix code generation for replay of sunk float fields.
[luajit-2.0.git] / src / lj_debug.c
blob4f4c4bb15a00acf1912464687ffd61ec9d141e01
1 /*
2 ** Debugging and introspection.
3 ** Copyright (C) 2005-2012 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 #if LJ_HASJIT
18 #include "lj_jit.h"
19 #endif
21 /* -- Frames -------------------------------------------------------------- */
23 /* Get frame corresponding to a level. */
24 cTValue *lj_debug_frame(lua_State *L, int level, int *size)
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. */
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);
44 *size = level;
45 return NULL; /* Level not found. */
48 /* Invalid bytecode position. */
49 #define NO_BCPOS (~(BCPos)0)
51 /* Return bytecode position for function/frame or NO_BCPOS. */
52 static BCPos debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe)
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 if (cf == NULL)
75 return NO_BCPOS;
76 while (f > nextframe) {
77 if (frame_islua(f)) {
78 f = frame_prevl(f);
79 } else {
80 if (frame_isc(f))
81 cf = cframe_raw(cframe_prev(cf));
82 f = frame_prevd(f);
85 if (cframe_prev(cf))
86 cf = cframe_raw(cframe_prev(cf));
87 ins = cframe_pc(cf);
90 pt = funcproto(fn);
91 pos = proto_bcpos(pt, ins) - 1;
92 #if LJ_HASJIT
93 if (pos > pt->sizebc) { /* Undo the effects of lj_trace_exit for JLOOP. */
94 GCtrace *T = (GCtrace *)((char *)(ins-1) - offsetof(GCtrace, startins));
95 lua_assert(bc_isret(bc_op(ins[-1])));
96 pos = proto_bcpos(pt, mref(T->startpc, const BCIns));
98 #endif
99 return pos;
102 /* -- Line numbers -------------------------------------------------------- */
104 /* Get line number for a bytecode position. */
105 BCLine LJ_FASTCALL lj_debug_line(GCproto *pt, BCPos pc)
107 const void *lineinfo = proto_lineinfo(pt);
108 if (pc <= pt->sizebc && lineinfo) {
109 BCLine first = pt->firstline;
110 if (pc == pt->sizebc) return first + pt->numline;
111 if (pc-- == 0) return first;
112 if (pt->numline < 256)
113 return first + (BCLine)((const uint8_t *)lineinfo)[pc];
114 else if (pt->numline < 65536)
115 return first + (BCLine)((const uint16_t *)lineinfo)[pc];
116 else
117 return first + (BCLine)((const uint32_t *)lineinfo)[pc];
119 return 0;
122 /* Get line number for function/frame. */
123 static BCLine debug_frameline(lua_State *L, GCfunc *fn, cTValue *nextframe)
125 BCPos pc = debug_framepc(L, fn, nextframe);
126 if (pc != NO_BCPOS) {
127 GCproto *pt = funcproto(fn);
128 lua_assert(pc <= pt->sizebc);
129 return lj_debug_line(pt, pc);
131 return -1;
134 /* -- Variable names ------------------------------------------------------ */
136 /* Read ULEB128 value. */
137 static uint32_t debug_read_uleb128(const uint8_t **pp)
139 const uint8_t *p = *pp;
140 uint32_t v = *p++;
141 if (LJ_UNLIKELY(v >= 0x80)) {
142 int sh = 0;
143 v &= 0x7f;
144 do { v |= ((*p & 0x7f) << (sh += 7)); } while (*p++ >= 0x80);
146 *pp = p;
147 return v;
150 /* Get name of a local variable from slot number and PC. */
151 static const char *debug_varname(const GCproto *pt, BCPos pc, BCReg slot)
153 const uint8_t *p = proto_varinfo(pt);
154 if (p) {
155 BCPos lastpc = 0;
156 for (;;) {
157 const char *name = (const char *)p;
158 uint32_t vn = *p++;
159 BCPos startpc, endpc;
160 if (vn < VARNAME__MAX) {
161 if (vn == VARNAME_END) break; /* End of varinfo. */
162 } else {
163 while (*p++) ; /* Skip over variable name string. */
165 lastpc = startpc = lastpc + debug_read_uleb128(&p);
166 if (startpc > pc) break;
167 endpc = startpc + debug_read_uleb128(&p);
168 if (pc < endpc && slot-- == 0) {
169 if (vn < VARNAME__MAX) {
170 #define VARNAMESTR(name, str) str "\0"
171 name = VARNAMEDEF(VARNAMESTR);
172 #undef VARNAMESTR
173 if (--vn) while (*name++ || --vn) ;
175 return name;
179 return NULL;
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;
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) */
199 nextframe = frame;
200 frame = frame_prevd(frame);
202 if (frame + slot1 < nextframe) {
203 *name = "(*vararg)";
204 return frame+slot1;
208 return NULL;
210 if (pc != NO_BCPOS &&
211 (*name = debug_varname(funcproto(fn), pc, slot1-1)) != NULL)
213 else if (slot1 > 0 && frame + slot1 < nextframe)
214 *name = "(*temporary)";
215 return frame+slot1;
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 lua_assert(idx < pt->sizeuv);
223 if (!p) return "";
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)
231 if (tvisfunc(o)) {
232 GCfunc *fn = funcV(o);
233 if (isluafunc(fn)) {
234 GCproto *pt = funcproto(fn);
235 if (idx < pt->sizeuv) {
236 *tvp = uvval(&gcref(fn->l.uvptr[idx])->uv);
237 return lj_debug_uvname(pt, idx);
239 } else {
240 if (idx < fn->c.nupvalues) {
241 *tvp = &fn->c.upvalue[idx];
242 return "";
246 return NULL;
249 /* Deduce name of an object from slot number and PC. */
250 const char *lj_debug_slotname(GCproto *pt, const BCIns *ip, BCReg slot,
251 const char **name)
253 const char *lname;
254 restart:
255 lname = debug_varname(pt, proto_bcpos(pt, ip), slot);
256 if (lname != NULL) { *name = lname; return "local"; }
257 while (--ip > proto_bc(pt)) {
258 BCIns ins = *ip;
259 BCOp op = bc_op(ins);
260 BCReg ra = bc_a(ins);
261 if (bcmode_a(op) == BCMbase) {
262 if (slot >= ra && (op != BC_KNIL || slot <= bc_d(ins)))
263 return NULL;
264 } else if (bcmode_a(op) == BCMdst && ra == slot) {
265 switch (bc_op(ins)) {
266 case BC_MOV:
267 if (ra == slot) { slot = bc_d(ins); goto restart; }
268 break;
269 case BC_GGET:
270 *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_d(ins))));
271 return "global";
272 case BC_TGETS:
273 *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_c(ins))));
274 if (ip > proto_bc(pt)) {
275 BCIns insp = ip[-1];
276 if (bc_op(insp) == BC_MOV && bc_a(insp) == ra+1 &&
277 bc_d(insp) == bc_b(ins))
278 return "method";
280 return "field";
281 case BC_UGET:
282 *name = lj_debug_uvname(pt, bc_d(ins));
283 return "upvalue";
284 default:
285 return NULL;
289 return NULL;
292 /* Deduce function name from caller of a frame. */
293 const char *lj_debug_funcname(lua_State *L, TValue *frame, const char **name)
295 TValue *pframe;
296 GCfunc *fn;
297 BCPos pc;
298 if (frame <= tvref(L->stack))
299 return NULL;
300 if (frame_isvarg(frame))
301 frame = frame_prevd(frame);
302 pframe = frame_prev(frame);
303 fn = frame_func(pframe);
304 pc = debug_framepc(L, fn, frame);
305 if (pc != NO_BCPOS) {
306 GCproto *pt = funcproto(fn);
307 const BCIns *ip = &proto_bc(pt)[check_exp(pc < pt->sizebc, pc)];
308 MMS mm = bcmode_mm(bc_op(*ip));
309 if (mm == MM_call) {
310 BCReg slot = bc_a(*ip);
311 if (bc_op(*ip) == BC_ITERC) slot -= 3;
312 return lj_debug_slotname(pt, ip, slot, name);
313 } else if (mm != MM__MAX) {
314 *name = strdata(mmname_str(G(L), mm));
315 return "metamethod";
318 return NULL;
321 /* -- Source code locations ----------------------------------------------- */
323 /* Generate shortened source name. */
324 void lj_debug_shortname(char *out, GCstr *str)
326 const char *src = strdata(str);
327 if (*src == '=') {
328 strncpy(out, src+1, LUA_IDSIZE); /* Remove first char. */
329 out[LUA_IDSIZE-1] = '\0'; /* Ensures null termination. */
330 } else if (*src == '@') { /* Output "source", or "...source". */
331 size_t len = str->len-1;
332 src++; /* Skip the `@' */
333 if (len >= LUA_IDSIZE) {
334 src += len-(LUA_IDSIZE-4); /* Get last part of file name. */
335 *out++ = '.'; *out++ = '.'; *out++ = '.';
337 strcpy(out, src);
338 } else { /* Output [string "string"]. */
339 size_t len; /* Length, up to first control char. */
340 for (len = 0; len < LUA_IDSIZE-12; len++)
341 if (((const unsigned char *)src)[len] < ' ') break;
342 strcpy(out, "[string \""); out += 9;
343 if (src[len] != '\0') { /* Must truncate? */
344 if (len > LUA_IDSIZE-15) len = LUA_IDSIZE-15;
345 strncpy(out, src, len); out += len;
346 strcpy(out, "..."); out += 3;
347 } else {
348 strcpy(out, src); out += len;
350 strcpy(out, "\"]");
354 /* Add current location of a frame to error message. */
355 void lj_debug_addloc(lua_State *L, const char *msg,
356 cTValue *frame, cTValue *nextframe)
358 if (frame) {
359 GCfunc *fn = frame_func(frame);
360 if (isluafunc(fn)) {
361 BCLine line = debug_frameline(L, fn, nextframe);
362 if (line >= 0) {
363 char buf[LUA_IDSIZE];
364 lj_debug_shortname(buf, proto_chunkname(funcproto(fn)));
365 lj_str_pushf(L, "%s:%d: %s", buf, line, msg);
366 return;
370 lj_str_pushf(L, "%s", msg);
373 /* Push location string for a bytecode position to Lua stack. */
374 void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc)
376 GCstr *name = proto_chunkname(pt);
377 const char *s = strdata(name);
378 MSize i, len = name->len;
379 BCLine line = lj_debug_line(pt, pc);
380 if (*s == '@') {
381 s++; len--;
382 for (i = len; i > 0; i--)
383 if (s[i] == '/' || s[i] == '\\') {
384 s += i+1;
385 break;
387 lj_str_pushf(L, "%s:%d", s, line);
388 } else if (len > 40) {
389 lj_str_pushf(L, "%p:%d", pt, line);
390 } else if (*s == '=') {
391 lj_str_pushf(L, "%s:%d", s+1, line);
392 } else {
393 lj_str_pushf(L, "\"%s\":%d", s, line);
397 /* -- Public debug API ---------------------------------------------------- */
399 /* lua_getupvalue() and lua_setupvalue() are in lj_api.c. */
401 LUA_API const char *lua_getlocal(lua_State *L, const lua_Debug *ar, int n)
403 const char *name = NULL;
404 if (ar) {
405 TValue *o = debug_localname(L, ar, &name, (BCReg)n);
406 if (name) {
407 copyTV(L, L->top, o);
408 incr_top(L);
410 } else if (tvisfunc(L->top-1) && isluafunc(funcV(L->top-1))) {
411 name = debug_varname(funcproto(funcV(L->top-1)), 0, (BCReg)n-1);
413 return name;
416 LUA_API const char *lua_setlocal(lua_State *L, const lua_Debug *ar, int n)
418 const char *name = NULL;
419 TValue *o = debug_localname(L, ar, &name, (BCReg)n);
420 if (name)
421 copyTV(L, o, L->top-1);
422 L->top--;
423 return name;
426 int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar, int ext)
428 int opt_f = 0, opt_L = 0;
429 TValue *frame = NULL;
430 TValue *nextframe = NULL;
431 GCfunc *fn;
432 if (*what == '>') {
433 TValue *func = L->top - 1;
434 api_check(L, tvisfunc(func));
435 fn = funcV(func);
436 L->top--;
437 what++;
438 } else {
439 uint32_t offset = (uint32_t)ar->i_ci & 0xffff;
440 uint32_t size = (uint32_t)ar->i_ci >> 16;
441 lua_assert(offset != 0);
442 frame = tvref(L->stack) + offset;
443 if (size) nextframe = frame + size;
444 lua_assert(frame <= tvref(L->maxstack) &&
445 (!nextframe || nextframe <= tvref(L->maxstack)));
446 fn = frame_func(frame);
447 lua_assert(fn->c.gct == ~LJ_TFUNC);
449 for (; *what; what++) {
450 if (*what == 'S') {
451 if (isluafunc(fn)) {
452 GCproto *pt = funcproto(fn);
453 BCLine firstline = pt->firstline;
454 GCstr *name = proto_chunkname(pt);
455 ar->source = strdata(name);
456 lj_debug_shortname(ar->short_src, name);
457 ar->linedefined = (int)firstline;
458 ar->lastlinedefined = (int)(firstline + pt->numline);
459 ar->what = firstline ? "Lua" : "main";
460 } else {
461 ar->source = "=[C]";
462 ar->short_src[0] = '[';
463 ar->short_src[1] = 'C';
464 ar->short_src[2] = ']';
465 ar->short_src[3] = '\0';
466 ar->linedefined = -1;
467 ar->lastlinedefined = -1;
468 ar->what = "C";
470 } else if (*what == 'l') {
471 ar->currentline = frame ? debug_frameline(L, fn, nextframe) : -1;
472 } else if (*what == 'u') {
473 ar->nups = fn->c.nupvalues;
474 if (ext) {
475 if (isluafunc(fn)) {
476 GCproto *pt = funcproto(fn);
477 ar->nparams = pt->numparams;
478 ar->isvararg = !!(pt->flags & PROTO_VARARG);
479 } else {
480 ar->nparams = 0;
481 ar->isvararg = 1;
484 } else if (*what == 'n') {
485 ar->namewhat = frame ? lj_debug_funcname(L, frame, &ar->name) : NULL;
486 if (ar->namewhat == NULL) {
487 ar->namewhat = "";
488 ar->name = NULL;
490 } else if (*what == 'f') {
491 opt_f = 1;
492 } else if (*what == 'L') {
493 opt_L = 1;
494 } else {
495 return 0; /* Bad option. */
498 if (opt_f) {
499 setfuncV(L, L->top, fn);
500 incr_top(L);
502 if (opt_L) {
503 if (isluafunc(fn)) {
504 GCtab *t = lj_tab_new(L, 0, 0);
505 GCproto *pt = funcproto(fn);
506 const void *lineinfo = proto_lineinfo(pt);
507 if (lineinfo) {
508 BCLine first = pt->firstline;
509 int sz = pt->numline < 256 ? 1 : pt->numline < 65536 ? 2 : 4;
510 MSize i, szl = pt->sizebc-1;
511 for (i = 0; i < szl; i++) {
512 BCLine line = first +
513 (sz == 1 ? (BCLine)((const uint8_t *)lineinfo)[i] :
514 sz == 2 ? (BCLine)((const uint16_t *)lineinfo)[i] :
515 (BCLine)((const uint32_t *)lineinfo)[i]);
516 setboolV(lj_tab_setint(L, t, line), 1);
519 settabV(L, L->top, t);
520 } else {
521 setnilV(L->top);
523 incr_top(L);
525 return 1; /* Ok. */
528 LUA_API int lua_getinfo(lua_State *L, const char *what, lua_Debug *ar)
530 return lj_debug_getinfo(L, what, (lj_Debug *)ar, 0);
533 LUA_API int lua_getstack(lua_State *L, int level, lua_Debug *ar)
535 int size;
536 cTValue *frame = lj_debug_frame(L, level, &size);
537 if (frame) {
538 ar->i_ci = (size << 16) + (int)(frame - tvref(L->stack));
539 return 1;
540 } else {
541 ar->i_ci = level - size;
542 return 0;
546 /* Number of frames for the leading and trailing part of a traceback. */
547 #define TRACEBACK_LEVELS1 12
548 #define TRACEBACK_LEVELS2 10
550 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
551 int level)
553 int top = (int)(L->top - L->base);
554 int lim = TRACEBACK_LEVELS1;
555 lua_Debug ar;
556 if (msg) lua_pushfstring(L, "%s\n", msg);
557 lua_pushliteral(L, "stack traceback:");
558 while (lua_getstack(L1, level++, &ar)) {
559 GCfunc *fn;
560 if (level > lim) {
561 if (!lua_getstack(L1, level + TRACEBACK_LEVELS2, &ar)) {
562 level--;
563 } else {
564 lua_pushliteral(L, "\n\t...");
565 lua_getstack(L1, -10, &ar);
566 level = ar.i_ci - TRACEBACK_LEVELS2;
568 lim = 2147483647;
569 continue;
571 lua_getinfo(L1, "Snlf", &ar);
572 fn = funcV(L1->top-1); L1->top--;
573 if (isffunc(fn) && !*ar.namewhat)
574 lua_pushfstring(L, "\n\t[builtin#%d]:", fn->c.ffid);
575 else
576 lua_pushfstring(L, "\n\t%s:", ar.short_src);
577 if (ar.currentline > 0)
578 lua_pushfstring(L, "%d:", ar.currentline);
579 if (*ar.namewhat) {
580 lua_pushfstring(L, " in function " LUA_QS, ar.name);
581 } else {
582 if (*ar.what == 'm') {
583 lua_pushliteral(L, " in main chunk");
584 } else if (*ar.what == 'C') {
585 lua_pushfstring(L, " at %p", fn->c.f);
586 } else {
587 lua_pushfstring(L, " in function <%s:%d>",
588 ar.short_src, ar.linedefined);
591 if ((int)(L->top - L->base) - top >= 15)
592 lua_concat(L, (int)(L->top - L->base) - top);
594 lua_concat(L, (int)(L->top - L->base) - top);