1/*	$NetBSD$	*/
2
3/*
4** Id: ldebug.c,v 2.29.1.6 2008/05/08 16:56:26 roberto Exp
5** Debug Interface
6** See Copyright Notice in lua.h
7*/
8
9
10#include <stdarg.h>
11#include <stddef.h>
12#include <string.h>
13
14
15#define ldebug_c
16#define LUA_CORE
17
18#include "lua.h"
19
20#include "lapi.h"
21#include "lcode.h"
22#include "ldebug.h"
23#include "ldo.h"
24#include "lfunc.h"
25#include "lobject.h"
26#include "lopcodes.h"
27#include "lstate.h"
28#include "lstring.h"
29#include "ltable.h"
30#include "ltm.h"
31#include "lvm.h"
32
33
34
35static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name);
36
37
38static int currentpc (lua_State *L, CallInfo *ci) {
39  if (!isLua(ci)) return -1;  /* function is not a Lua function? */
40  if (ci == L->ci)
41    ci->savedpc = L->savedpc;
42  return pcRel(ci->savedpc, ci_func(ci)->l.p);
43}
44
45
46static int currentline (lua_State *L, CallInfo *ci) {
47  int pc = currentpc(L, ci);
48  if (pc < 0)
49    return -1;  /* only active lua functions have current-line information */
50  else
51    return getline(ci_func(ci)->l.p, pc);
52}
53
54
55/*
56** this function can be called asynchronous (e.g. during a signal)
57*/
58LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
59  if (func == NULL || mask == 0) {  /* turn off hooks? */
60    mask = 0;
61    func = NULL;
62  }
63  L->hook = func;
64  L->basehookcount = count;
65  resethookcount(L);
66  L->hookmask = cast_byte(mask);
67  return 1;
68}
69
70
71LUA_API lua_Hook lua_gethook (lua_State *L) {
72  return L->hook;
73}
74
75
76LUA_API int lua_gethookmask (lua_State *L) {
77  return L->hookmask;
78}
79
80
81LUA_API int lua_gethookcount (lua_State *L) {
82  return L->basehookcount;
83}
84
85
86LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
87  int status;
88  CallInfo *ci;
89  lua_lock(L);
90  for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) {
91    level--;
92    if (f_isLua(ci))  /* Lua function? */
93      level -= ci->tailcalls;  /* skip lost tail calls */
94  }
95  if (level == 0 && ci > L->base_ci) {  /* level found? */
96    status = 1;
97    ar->i_ci = cast_int(ci - L->base_ci);
98  }
99  else if (level < 0) {  /* level is of a lost tail call? */
100    status = 1;
101    ar->i_ci = 0;
102  }
103  else status = 0;  /* no such level */
104  lua_unlock(L);
105  return status;
106}
107
108
109static Proto *getluaproto (CallInfo *ci) {
110  return (isLua(ci) ? ci_func(ci)->l.p : NULL);
111}
112
113
114static const char *findlocal (lua_State *L, CallInfo *ci, int n) {
115  const char *name;
116  Proto *fp = getluaproto(ci);
117  if (fp && (name = luaF_getlocalname(fp, n, currentpc(L, ci))) != NULL)
118    return name;  /* is a local variable in a Lua function */
119  else {
120    StkId limit = (ci == L->ci) ? L->top : (ci+1)->func;
121    if (limit - ci->base >= n && n > 0)  /* is 'n' inside 'ci' stack? */
122      return "(*temporary)";
123    else
124      return NULL;
125  }
126}
127
128
129LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
130  CallInfo *ci = L->base_ci + ar->i_ci;
131  const char *name = findlocal(L, ci, n);
132  lua_lock(L);
133  if (name)
134      luaA_pushobject(L, ci->base + (n - 1));
135  lua_unlock(L);
136  return name;
137}
138
139
140LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
141  CallInfo *ci = L->base_ci + ar->i_ci;
142  const char *name = findlocal(L, ci, n);
143  lua_lock(L);
144  if (name)
145      setobjs2s(L, ci->base + (n - 1), L->top - 1);
146  L->top--;  /* pop value */
147  lua_unlock(L);
148  return name;
149}
150
151
152static void funcinfo (lua_Debug *ar, Closure *cl) {
153  if (cl->c.isC) {
154    ar->source = "=[C]";
155    ar->linedefined = -1;
156    ar->lastlinedefined = -1;
157    ar->what = "C";
158  }
159  else {
160    ar->source = getstr(cl->l.p->source);
161    ar->linedefined = cl->l.p->linedefined;
162    ar->lastlinedefined = cl->l.p->lastlinedefined;
163    ar->what = (ar->linedefined == 0) ? "main" : "Lua";
164  }
165  luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
166}
167
168
169static void info_tailcall (lua_Debug *ar) {
170  ar->name = ar->namewhat = "";
171  ar->what = "tail";
172  ar->lastlinedefined = ar->linedefined = ar->currentline = -1;
173  ar->source = "=(tail call)";
174  luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
175  ar->nups = 0;
176}
177
178
179static void collectvalidlines (lua_State *L, Closure *f) {
180  if (f == NULL || f->c.isC) {
181    setnilvalue(L->top);
182  }
183  else {
184    Table *t = luaH_new(L, 0, 0);
185    int *lineinfo = f->l.p->lineinfo;
186    int i;
187    for (i=0; i<f->l.p->sizelineinfo; i++)
188      setbvalue(luaH_setnum(L, t, lineinfo[i]), 1);
189    sethvalue(L, L->top, t);
190  }
191  incr_top(L);
192}
193
194
195static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
196                    Closure *f, CallInfo *ci) {
197  int status = 1;
198  if (f == NULL) {
199    info_tailcall(ar);
200    return status;
201  }
202  for (; *what; what++) {
203    switch (*what) {
204      case 'S': {
205        funcinfo(ar, f);
206        break;
207      }
208      case 'l': {
209        ar->currentline = (ci) ? currentline(L, ci) : -1;
210        break;
211      }
212      case 'u': {
213        ar->nups = f->c.nupvalues;
214        break;
215      }
216      case 'n': {
217        ar->namewhat = (ci) ? getfuncname(L, ci, &ar->name) : NULL;
218        if (ar->namewhat == NULL) {
219          ar->namewhat = "";  /* not found */
220          ar->name = NULL;
221        }
222        break;
223      }
224      case 'L':
225      case 'f':  /* handled by lua_getinfo */
226        break;
227      default: status = 0;  /* invalid option */
228    }
229  }
230  return status;
231}
232
233
234LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
235  int status;
236  Closure *f = NULL;
237  CallInfo *ci = NULL;
238  lua_lock(L);
239  if (*what == '>') {
240    StkId func = L->top - 1;
241    luai_apicheck(L, ttisfunction(func));
242    what++;  /* skip the '>' */
243    f = clvalue(func);
244    L->top--;  /* pop function */
245  }
246  else if (ar->i_ci != 0) {  /* no tail call? */
247    ci = L->base_ci + ar->i_ci;
248    lua_assert(ttisfunction(ci->func));
249    f = clvalue(ci->func);
250  }
251  status = auxgetinfo(L, what, ar, f, ci);
252  if (strchr(what, 'f')) {
253    if (f == NULL) setnilvalue(L->top);
254    else setclvalue(L, L->top, f);
255    incr_top(L);
256  }
257  if (strchr(what, 'L'))
258    collectvalidlines(L, f);
259  lua_unlock(L);
260  return status;
261}
262
263
264/*
265** {======================================================
266** Symbolic Execution and code checker
267** =======================================================
268*/
269
270#define check(x)		if (!(x)) return 0;
271
272#define checkjump(pt,pc)	check(0 <= pc && pc < pt->sizecode)
273
274#define checkreg(pt,reg)	check((reg) < (pt)->maxstacksize)
275
276
277
278static int precheck (const Proto *pt) {
279  check(pt->maxstacksize <= MAXSTACK);
280  check(pt->numparams+(pt->is_vararg & VARARG_HASARG) <= pt->maxstacksize);
281  check(!(pt->is_vararg & VARARG_NEEDSARG) ||
282              (pt->is_vararg & VARARG_HASARG));
283  check(pt->sizeupvalues <= pt->nups);
284  check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0);
285  check(pt->sizecode > 0 && GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN);
286  return 1;
287}
288
289
290#define checkopenop(pt,pc)	luaG_checkopenop((pt)->code[(pc)+1])
291
292int luaG_checkopenop (Instruction i) {
293  switch (GET_OPCODE(i)) {
294    case OP_CALL:
295    case OP_TAILCALL:
296    case OP_RETURN:
297    case OP_SETLIST: {
298      check(GETARG_B(i) == 0);
299      return 1;
300    }
301    default: return 0;  /* invalid instruction after an open call */
302  }
303}
304
305
306static int checkArgMode (const Proto *pt, int r, enum OpArgMask mode) {
307  switch (mode) {
308    case OpArgN: check(r == 0); break;
309    case OpArgU: break;
310    case OpArgR: checkreg(pt, r); break;
311    case OpArgK:
312      check(ISK(r) ? INDEXK(r) < pt->sizek : r < pt->maxstacksize);
313      break;
314  }
315  return 1;
316}
317
318
319static Instruction symbexec (const Proto *pt, int lastpc, int reg) {
320  int pc;
321  int last;  /* stores position of last instruction that changed `reg' */
322  last = pt->sizecode-1;  /* points to final return (a `neutral' instruction) */
323  check(precheck(pt));
324  for (pc = 0; pc < lastpc; pc++) {
325    Instruction i = pt->code[pc];
326    OpCode op = GET_OPCODE(i);
327    int a = GETARG_A(i);
328    int b = 0;
329    int c = 0;
330    check(op < NUM_OPCODES);
331    checkreg(pt, a);
332    switch (getOpMode(op)) {
333      case iABC: {
334        b = GETARG_B(i);
335        c = GETARG_C(i);
336        check(checkArgMode(pt, b, getBMode(op)));
337        check(checkArgMode(pt, c, getCMode(op)));
338        break;
339      }
340      case iABx: {
341        b = GETARG_Bx(i);
342        if (getBMode(op) == OpArgK) check(b < pt->sizek);
343        break;
344      }
345      case iAsBx: {
346        b = GETARG_sBx(i);
347        if (getBMode(op) == OpArgR) {
348          int dest = pc+1+b;
349          check(0 <= dest && dest < pt->sizecode);
350          if (dest > 0) {
351            int j;
352            /* check that it does not jump to a setlist count; this
353               is tricky, because the count from a previous setlist may
354               have the same value of an invalid setlist; so, we must
355               go all the way back to the first of them (if any) */
356            for (j = 0; j < dest; j++) {
357              Instruction d = pt->code[dest-1-j];
358              if (!(GET_OPCODE(d) == OP_SETLIST && GETARG_C(d) == 0)) break;
359            }
360            /* if 'j' is even, previous value is not a setlist (even if
361               it looks like one) */
362            check((j&1) == 0);
363          }
364        }
365        break;
366      }
367    }
368    if (testAMode(op)) {
369      if (a == reg) last = pc;  /* change register `a' */
370    }
371    if (testTMode(op)) {
372      check(pc+2 < pt->sizecode);  /* check skip */
373      check(GET_OPCODE(pt->code[pc+1]) == OP_JMP);
374    }
375    switch (op) {
376      case OP_LOADBOOL: {
377        if (c == 1) {  /* does it jump? */
378          check(pc+2 < pt->sizecode);  /* check its jump */
379          check(GET_OPCODE(pt->code[pc+1]) != OP_SETLIST ||
380                GETARG_C(pt->code[pc+1]) != 0);
381        }
382        break;
383      }
384      case OP_LOADNIL: {
385        if (a <= reg && reg <= b)
386          last = pc;  /* set registers from `a' to `b' */
387        break;
388      }
389      case OP_GETUPVAL:
390      case OP_SETUPVAL: {
391        check(b < pt->nups);
392        break;
393      }
394      case OP_GETGLOBAL:
395      case OP_SETGLOBAL: {
396        check(ttisstring(&pt->k[b]));
397        break;
398      }
399      case OP_SELF: {
400        checkreg(pt, a+1);
401        if (reg == a+1) last = pc;
402        break;
403      }
404      case OP_CONCAT: {
405        check(b < c);  /* at least two operands */
406        break;
407      }
408      case OP_TFORLOOP: {
409        check(c >= 1);  /* at least one result (control variable) */
410        checkreg(pt, a+2+c);  /* space for results */
411        if (reg >= a+2) last = pc;  /* affect all regs above its base */
412        break;
413      }
414      case OP_FORLOOP:
415      case OP_FORPREP:
416        checkreg(pt, a+3);
417        /* go through */
418      case OP_JMP: {
419        int dest = pc+1+b;
420        /* not full check and jump is forward and do not skip `lastpc'? */
421        if (reg != NO_REG && pc < dest && dest <= lastpc)
422          pc += b;  /* do the jump */
423        break;
424      }
425      case OP_CALL:
426      case OP_TAILCALL: {
427        if (b != 0) {
428          checkreg(pt, a+b-1);
429        }
430        c--;  /* c = num. returns */
431        if (c == LUA_MULTRET) {
432          check(checkopenop(pt, pc));
433        }
434        else if (c != 0)
435          checkreg(pt, a+c-1);
436        if (reg >= a) last = pc;  /* affect all registers above base */
437        break;
438      }
439      case OP_RETURN: {
440        b--;  /* b = num. returns */
441        if (b > 0) checkreg(pt, a+b-1);
442        break;
443      }
444      case OP_SETLIST: {
445        if (b > 0) checkreg(pt, a + b);
446        if (c == 0) {
447          pc++;
448          check(pc < pt->sizecode - 1);
449        }
450        break;
451      }
452      case OP_CLOSURE: {
453        int nup, j;
454        check(b < pt->sizep);
455        nup = pt->p[b]->nups;
456        check(pc + nup < pt->sizecode);
457        for (j = 1; j <= nup; j++) {
458          OpCode op1 = GET_OPCODE(pt->code[pc + j]);
459          check(op1 == OP_GETUPVAL || op1 == OP_MOVE);
460        }
461        if (reg != NO_REG)  /* tracing? */
462          pc += nup;  /* do not 'execute' these pseudo-instructions */
463        break;
464      }
465      case OP_VARARG: {
466        check((pt->is_vararg & VARARG_ISVARARG) &&
467             !(pt->is_vararg & VARARG_NEEDSARG));
468        b--;
469        if (b == LUA_MULTRET) check(checkopenop(pt, pc));
470        checkreg(pt, a+b-1);
471        break;
472      }
473      default: break;
474    }
475  }
476  return pt->code[last];
477}
478
479#undef check
480#undef checkjump
481#undef checkreg
482
483/* }====================================================== */
484
485
486int luaG_checkcode (const Proto *pt) {
487  return (symbexec(pt, pt->sizecode, NO_REG) != 0);
488}
489
490
491static const char *kname (Proto *p, int c) {
492  if (ISK(c) && ttisstring(&p->k[INDEXK(c)]))
493    return svalue(&p->k[INDEXK(c)]);
494  else
495    return "?";
496}
497
498
499static const char *getobjname (lua_State *L, CallInfo *ci, int stackpos,
500                               const char **name) {
501  if (isLua(ci)) {  /* a Lua function? */
502    Proto *p = ci_func(ci)->l.p;
503    int pc = currentpc(L, ci);
504    Instruction i;
505    *name = luaF_getlocalname(p, stackpos+1, pc);
506    if (*name)  /* is a local? */
507      return "local";
508    i = symbexec(p, pc, stackpos);  /* try symbolic execution */
509    lua_assert(pc != -1);
510    switch (GET_OPCODE(i)) {
511      case OP_GETGLOBAL: {
512        int g = GETARG_Bx(i);  /* global index */
513        lua_assert(ttisstring(&p->k[g]));
514        *name = svalue(&p->k[g]);
515        return "global";
516      }
517      case OP_MOVE: {
518        int a = GETARG_A(i);
519        int b = GETARG_B(i);  /* move from `b' to `a' */
520        if (b < a)
521          return getobjname(L, ci, b, name);  /* get name for `b' */
522        break;
523      }
524      case OP_GETTABLE: {
525        int k = GETARG_C(i);  /* key index */
526        *name = kname(p, k);
527        return "field";
528      }
529      case OP_GETUPVAL: {
530        int u = GETARG_B(i);  /* upvalue index */
531        *name = p->upvalues ? getstr(p->upvalues[u]) : "?";
532        return "upvalue";
533      }
534      case OP_SELF: {
535        int k = GETARG_C(i);  /* key index */
536        *name = kname(p, k);
537        return "method";
538      }
539      default: break;
540    }
541  }
542  return NULL;  /* no useful name found */
543}
544
545
546static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
547  Instruction i;
548  if ((isLua(ci) && ci->tailcalls > 0) || !isLua(ci - 1))
549    return NULL;  /* calling function is not Lua (or is unknown) */
550  ci--;  /* calling function */
551  i = ci_func(ci)->l.p->code[currentpc(L, ci)];
552  if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL ||
553      GET_OPCODE(i) == OP_TFORLOOP)
554    return getobjname(L, ci, GETARG_A(i), name);
555  else
556    return NULL;  /* no useful name can be found */
557}
558
559
560/* only ANSI way to check whether a pointer points to an array */
561static int isinstack (CallInfo *ci, const TValue *o) {
562  StkId p;
563  for (p = ci->base; p < ci->top; p++)
564    if (o == p) return 1;
565  return 0;
566}
567
568
569void luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
570  const char *name = NULL;
571  const char *t = luaT_typenames[ttype(o)];
572  const char *kind = (isinstack(L->ci, o)) ?
573                         getobjname(L, L->ci, cast_int(o - L->base), &name) :
574                         NULL;
575  if (kind)
576    luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",
577                op, kind, name, t);
578  else
579    luaG_runerror(L, "attempt to %s a %s value", op, t);
580}
581
582
583void luaG_concaterror (lua_State *L, StkId p1, StkId p2) {
584  if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;
585  lua_assert(!ttisstring(p1) && !ttisnumber(p1));
586  luaG_typeerror(L, p1, "concatenate");
587}
588
589
590void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
591  TValue temp;
592  if (luaV_tonumber(p1, &temp) == NULL)
593    p2 = p1;  /* first operand is wrong */
594  luaG_typeerror(L, p2, "perform arithmetic on");
595}
596
597
598int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
599  const char *t1 = luaT_typenames[ttype(p1)];
600  const char *t2 = luaT_typenames[ttype(p2)];
601  if (t1[2] == t2[2])
602    luaG_runerror(L, "attempt to compare two %s values", t1);
603  else
604    luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
605  return 0;
606}
607
608
609static void addinfo (lua_State *L, const char *msg) {
610  CallInfo *ci = L->ci;
611  if (isLua(ci)) {  /* is Lua code? */
612    char buff[LUA_IDSIZE];  /* add file:line information */
613    int line = currentline(L, ci);
614    luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE);
615    luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
616  }
617}
618
619
620void luaG_errormsg (lua_State *L) {
621  if (L->errfunc != 0) {  /* is there an error handling function? */
622    StkId errfunc = restorestack(L, L->errfunc);
623    if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
624    setobjs2s(L, L->top, L->top - 1);  /* move argument */
625    setobjs2s(L, L->top - 1, errfunc);  /* push function */
626    incr_top(L);
627    luaD_call(L, L->top - 2, 1);  /* call it */
628  }
629  luaD_throw(L, LUA_ERRRUN);
630}
631
632
633void luaG_runerror (lua_State *L, const char *fmt, ...) {
634  va_list argp;
635  va_start(argp, fmt);
636  addinfo(L, luaO_pushvfstring(L, fmt, argp));
637  va_end(argp);
638  luaG_errormsg(L);
639}
640
641