ldebug.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. /*
  2. ** $Id: ldebug.c $
  3. ** Debug Interface
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define ldebug_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <stdarg.h>
  10. #include <stddef.h>
  11. #include <string.h>
  12. #include "lua.h"
  13. #include "lapi.h"
  14. #include "lcode.h"
  15. #include "ldebug.h"
  16. #include "ldo.h"
  17. #include "lfunc.h"
  18. #include "lobject.h"
  19. #include "lopcodes.h"
  20. #include "lstate.h"
  21. #include "lstring.h"
  22. #include "ltable.h"
  23. #include "ltm.h"
  24. #include "lvm.h"
  25. #define LuaClosure(f) ((f) != NULL && (f)->c.tt == LUA_VLCL)
  26. static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
  27. const char **name);
  28. static int currentpc (CallInfo *ci) {
  29. lua_assert(isLua(ci));
  30. return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
  31. }
  32. /*
  33. ** Get a "base line" to find the line corresponding to an instruction.
  34. ** Base lines are regularly placed at MAXIWTHABS intervals, so usually
  35. ** an integer division gets the right place. When the source file has
  36. ** large sequences of empty/comment lines, it may need extra entries,
  37. ** so the original estimate needs a correction.
  38. ** If the original estimate is -1, the initial 'if' ensures that the
  39. ** 'while' will run at least once.
  40. ** The assertion that the estimate is a lower bound for the correct base
  41. ** is valid as long as the debug info has been generated with the same
  42. ** value for MAXIWTHABS or smaller. (Previous releases use a little
  43. ** smaller value.)
  44. */
  45. static int getbaseline (const Proto *f, int pc, int *basepc) {
  46. if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) {
  47. *basepc = -1; /* start from the beginning */
  48. return f->linedefined;
  49. }
  50. else {
  51. int i = pc / MAXIWTHABS - 1; /* get an estimate */
  52. /* estimate must be a lower bound of the correct base */
  53. lua_assert(i < 0 ||
  54. (i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc));
  55. while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc)
  56. i++; /* low estimate; adjust it */
  57. *basepc = f->abslineinfo[i].pc;
  58. return f->abslineinfo[i].line;
  59. }
  60. }
  61. /*
  62. ** Get the line corresponding to instruction 'pc' in function 'f';
  63. ** first gets a base line and from there does the increments until
  64. ** the desired instruction.
  65. */
  66. int luaG_getfuncline (const Proto *f, int pc) {
  67. if (f->lineinfo == NULL) /* no debug information? */
  68. return -1;
  69. else {
  70. int basepc;
  71. int baseline = getbaseline(f, pc, &basepc);
  72. while (basepc++ < pc) { /* walk until given instruction */
  73. lua_assert(f->lineinfo[basepc] != ABSLINEINFO);
  74. baseline += f->lineinfo[basepc]; /* correct line */
  75. }
  76. return baseline;
  77. }
  78. }
  79. static int getcurrentline (CallInfo *ci) {
  80. return luaG_getfuncline(ci_func(ci)->p, currentpc(ci));
  81. }
  82. /*
  83. ** Set 'trap' for all active Lua frames.
  84. ** This function can be called during a signal, under "reasonable"
  85. ** assumptions. A new 'ci' is completely linked in the list before it
  86. ** becomes part of the "active" list, and we assume that pointers are
  87. ** atomic; see comment in next function.
  88. ** (A compiler doing interprocedural optimizations could, theoretically,
  89. ** reorder memory writes in such a way that the list could be
  90. ** temporarily broken while inserting a new element. We simply assume it
  91. ** has no good reasons to do that.)
  92. */
  93. static void settraps (CallInfo *ci) {
  94. for (; ci != NULL; ci = ci->previous)
  95. if (isLua(ci))
  96. ci->u.l.trap = 1;
  97. }
  98. /*
  99. ** This function can be called during a signal, under "reasonable"
  100. ** assumptions.
  101. ** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount')
  102. ** are for debug only, and it is no problem if they get arbitrary
  103. ** values (causes at most one wrong hook call). 'hookmask' is an atomic
  104. ** value. We assume that pointers are atomic too (e.g., gcc ensures that
  105. ** for all platforms where it runs). Moreover, 'hook' is always checked
  106. ** before being called (see 'luaD_hook').
  107. */
  108. LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
  109. if (func == NULL || mask == 0) { /* turn off hooks? */
  110. mask = 0;
  111. func = NULL;
  112. }
  113. L->hook = func;
  114. L->basehookcount = count;
  115. resethookcount(L);
  116. L->hookmask = cast_byte(mask);
  117. if (mask)
  118. settraps(L->ci); /* to trace inside 'luaV_execute' */
  119. }
  120. LUA_API lua_Hook lua_gethook (lua_State *L) {
  121. return L->hook;
  122. }
  123. LUA_API int lua_gethookmask (lua_State *L) {
  124. return L->hookmask;
  125. }
  126. LUA_API int lua_gethookcount (lua_State *L) {
  127. return L->basehookcount;
  128. }
  129. LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
  130. int status;
  131. CallInfo *ci;
  132. if (level < 0) return 0; /* invalid (negative) level */
  133. lua_lock(L);
  134. for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)
  135. level--;
  136. if (level == 0 && ci != &L->base_ci) { /* level found? */
  137. status = 1;
  138. ar->i_ci = ci;
  139. }
  140. else status = 0; /* no such level */
  141. lua_unlock(L);
  142. return status;
  143. }
  144. static const char *upvalname (const Proto *p, int uv) {
  145. TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
  146. if (s == NULL) return "?";
  147. else return getstr(s);
  148. }
  149. static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
  150. if (clLvalue(s2v(ci->func.p))->p->flag & PF_ISVARARG) {
  151. int nextra = ci->u.l.nextraargs;
  152. if (n >= -nextra) { /* 'n' is negative */
  153. *pos = ci->func.p - nextra - (n + 1);
  154. return "(vararg)"; /* generic name for any vararg */
  155. }
  156. }
  157. return NULL; /* no such vararg */
  158. }
  159. const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) {
  160. StkId base = ci->func.p + 1;
  161. const char *name = NULL;
  162. if (isLua(ci)) {
  163. if (n < 0) /* access to vararg values? */
  164. return findvararg(ci, n, pos);
  165. else
  166. name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
  167. }
  168. if (name == NULL) { /* no 'standard' name? */
  169. StkId limit = (ci == L->ci) ? L->top.p : ci->next->func.p;
  170. if (limit - base >= n && n > 0) { /* is 'n' inside 'ci' stack? */
  171. /* generic name for any valid slot */
  172. name = isLua(ci) ? "(temporary)" : "(C temporary)";
  173. }
  174. else
  175. return NULL; /* no name */
  176. }
  177. if (pos)
  178. *pos = base + (n - 1);
  179. return name;
  180. }
  181. LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
  182. const char *name;
  183. lua_lock(L);
  184. if (ar == NULL) { /* information about non-active function? */
  185. if (!isLfunction(s2v(L->top.p - 1))) /* not a Lua function? */
  186. name = NULL;
  187. else /* consider live variables at function start (parameters) */
  188. name = luaF_getlocalname(clLvalue(s2v(L->top.p - 1))->p, n, 0);
  189. }
  190. else { /* active function; get information through 'ar' */
  191. StkId pos = NULL; /* to avoid warnings */
  192. name = luaG_findlocal(L, ar->i_ci, n, &pos);
  193. if (name) {
  194. setobjs2s(L, L->top.p, pos);
  195. api_incr_top(L);
  196. }
  197. }
  198. lua_unlock(L);
  199. return name;
  200. }
  201. LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
  202. StkId pos = NULL; /* to avoid warnings */
  203. const char *name;
  204. lua_lock(L);
  205. name = luaG_findlocal(L, ar->i_ci, n, &pos);
  206. if (name) {
  207. api_checkpop(L, 1);
  208. setobjs2s(L, pos, L->top.p - 1);
  209. L->top.p--; /* pop value */
  210. }
  211. lua_unlock(L);
  212. return name;
  213. }
  214. static void funcinfo (lua_Debug *ar, Closure *cl) {
  215. if (!LuaClosure(cl)) {
  216. ar->source = "=[C]";
  217. ar->srclen = LL("=[C]");
  218. ar->linedefined = -1;
  219. ar->lastlinedefined = -1;
  220. ar->what = "C";
  221. }
  222. else {
  223. const Proto *p = cl->l.p;
  224. if (p->source) {
  225. ar->source = getlstr(p->source, ar->srclen);
  226. }
  227. else {
  228. ar->source = "=?";
  229. ar->srclen = LL("=?");
  230. }
  231. ar->linedefined = p->linedefined;
  232. ar->lastlinedefined = p->lastlinedefined;
  233. ar->what = (ar->linedefined == 0) ? "main" : "Lua";
  234. }
  235. luaO_chunkid(ar->short_src, ar->source, ar->srclen);
  236. }
  237. static int nextline (const Proto *p, int currentline, int pc) {
  238. if (p->lineinfo[pc] != ABSLINEINFO)
  239. return currentline + p->lineinfo[pc];
  240. else
  241. return luaG_getfuncline(p, pc);
  242. }
  243. static void collectvalidlines (lua_State *L, Closure *f) {
  244. if (!LuaClosure(f)) {
  245. setnilvalue(s2v(L->top.p));
  246. api_incr_top(L);
  247. }
  248. else {
  249. const Proto *p = f->l.p;
  250. int currentline = p->linedefined;
  251. Table *t = luaH_new(L); /* new table to store active lines */
  252. sethvalue2s(L, L->top.p, t); /* push it on stack */
  253. api_incr_top(L);
  254. if (p->lineinfo != NULL) { /* proto with debug information? */
  255. int i;
  256. TValue v;
  257. setbtvalue(&v); /* boolean 'true' to be the value of all indices */
  258. if (!(p->flag & PF_ISVARARG)) /* regular function? */
  259. i = 0; /* consider all instructions */
  260. else { /* vararg function */
  261. lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP);
  262. currentline = nextline(p, currentline, 0);
  263. i = 1; /* skip first instruction (OP_VARARGPREP) */
  264. }
  265. for (; i < p->sizelineinfo; i++) { /* for each instruction */
  266. currentline = nextline(p, currentline, i); /* get its line */
  267. luaH_setint(L, t, currentline, &v); /* table[line] = true */
  268. }
  269. }
  270. }
  271. }
  272. static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
  273. /* calling function is a known function? */
  274. if (ci != NULL && !(ci->callstatus & CIST_TAIL))
  275. return funcnamefromcall(L, ci->previous, name);
  276. else return NULL; /* no way to find a name */
  277. }
  278. static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
  279. Closure *f, CallInfo *ci) {
  280. int status = 1;
  281. for (; *what; what++) {
  282. switch (*what) {
  283. case 'S': {
  284. funcinfo(ar, f);
  285. break;
  286. }
  287. case 'l': {
  288. ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1;
  289. break;
  290. }
  291. case 'u': {
  292. ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
  293. if (!LuaClosure(f)) {
  294. ar->isvararg = 1;
  295. ar->nparams = 0;
  296. }
  297. else {
  298. ar->isvararg = (f->l.p->flag & PF_ISVARARG) ? 1 : 0;
  299. ar->nparams = f->l.p->numparams;
  300. }
  301. break;
  302. }
  303. case 't': {
  304. if (ci != NULL) {
  305. ar->istailcall = !!(ci->callstatus & CIST_TAIL);
  306. ar->extraargs =
  307. cast_uchar((ci->callstatus & MAX_CCMT) >> CIST_CCMT);
  308. }
  309. else {
  310. ar->istailcall = 0;
  311. ar->extraargs = 0;
  312. }
  313. break;
  314. }
  315. case 'n': {
  316. ar->namewhat = getfuncname(L, ci, &ar->name);
  317. if (ar->namewhat == NULL) {
  318. ar->namewhat = ""; /* not found */
  319. ar->name = NULL;
  320. }
  321. break;
  322. }
  323. case 'r': {
  324. if (ci == NULL || !(ci->callstatus & CIST_HOOKED))
  325. ar->ftransfer = ar->ntransfer = 0;
  326. else {
  327. ar->ftransfer = L->transferinfo.ftransfer;
  328. ar->ntransfer = L->transferinfo.ntransfer;
  329. }
  330. break;
  331. }
  332. case 'L':
  333. case 'f': /* handled by lua_getinfo */
  334. break;
  335. default: status = 0; /* invalid option */
  336. }
  337. }
  338. return status;
  339. }
  340. LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
  341. int status;
  342. Closure *cl;
  343. CallInfo *ci;
  344. TValue *func;
  345. lua_lock(L);
  346. if (*what == '>') {
  347. ci = NULL;
  348. func = s2v(L->top.p - 1);
  349. api_check(L, ttisfunction(func), "function expected");
  350. what++; /* skip the '>' */
  351. L->top.p--; /* pop function */
  352. }
  353. else {
  354. ci = ar->i_ci;
  355. func = s2v(ci->func.p);
  356. lua_assert(ttisfunction(func));
  357. }
  358. cl = ttisclosure(func) ? clvalue(func) : NULL;
  359. status = auxgetinfo(L, what, ar, cl, ci);
  360. if (strchr(what, 'f')) {
  361. setobj2s(L, L->top.p, func);
  362. api_incr_top(L);
  363. }
  364. if (strchr(what, 'L'))
  365. collectvalidlines(L, cl);
  366. lua_unlock(L);
  367. return status;
  368. }
  369. /*
  370. ** {======================================================
  371. ** Symbolic Execution
  372. ** =======================================================
  373. */
  374. static int filterpc (int pc, int jmptarget) {
  375. if (pc < jmptarget) /* is code conditional (inside a jump)? */
  376. return -1; /* cannot know who sets that register */
  377. else return pc; /* current position sets that register */
  378. }
  379. /*
  380. ** Try to find last instruction before 'lastpc' that modified register 'reg'.
  381. */
  382. static int findsetreg (const Proto *p, int lastpc, int reg) {
  383. int pc;
  384. int setreg = -1; /* keep last instruction that changed 'reg' */
  385. int jmptarget = 0; /* any code before this address is conditional */
  386. if (testMMMode(GET_OPCODE(p->code[lastpc])))
  387. lastpc--; /* previous instruction was not actually executed */
  388. for (pc = 0; pc < lastpc; pc++) {
  389. Instruction i = p->code[pc];
  390. OpCode op = GET_OPCODE(i);
  391. int a = GETARG_A(i);
  392. int change; /* true if current instruction changed 'reg' */
  393. switch (op) {
  394. case OP_LOADNIL: { /* set registers from 'a' to 'a+b' */
  395. int b = GETARG_B(i);
  396. change = (a <= reg && reg <= a + b);
  397. break;
  398. }
  399. case OP_TFORCALL: { /* affect all regs above its base */
  400. change = (reg >= a + 2);
  401. break;
  402. }
  403. case OP_CALL:
  404. case OP_TAILCALL: { /* affect all registers above base */
  405. change = (reg >= a);
  406. break;
  407. }
  408. case OP_JMP: { /* doesn't change registers, but changes 'jmptarget' */
  409. int b = GETARG_sJ(i);
  410. int dest = pc + 1 + b;
  411. /* jump does not skip 'lastpc' and is larger than current one? */
  412. if (dest <= lastpc && dest > jmptarget)
  413. jmptarget = dest; /* update 'jmptarget' */
  414. change = 0;
  415. break;
  416. }
  417. default: /* any instruction that sets A */
  418. change = (testAMode(op) && reg == a);
  419. break;
  420. }
  421. if (change)
  422. setreg = filterpc(pc, jmptarget);
  423. }
  424. return setreg;
  425. }
  426. /*
  427. ** Find a "name" for the constant 'c'.
  428. */
  429. static const char *kname (const Proto *p, int index, const char **name) {
  430. TValue *kvalue = &p->k[index];
  431. if (ttisstring(kvalue)) {
  432. *name = getstr(tsvalue(kvalue));
  433. return "constant";
  434. }
  435. else {
  436. *name = "?";
  437. return NULL;
  438. }
  439. }
  440. static const char *basicgetobjname (const Proto *p, int *ppc, int reg,
  441. const char **name) {
  442. int pc = *ppc;
  443. *name = luaF_getlocalname(p, reg + 1, pc);
  444. if (*name) /* is a local? */
  445. return "local";
  446. /* else try symbolic execution */
  447. *ppc = pc = findsetreg(p, pc, reg);
  448. if (pc != -1) { /* could find instruction? */
  449. Instruction i = p->code[pc];
  450. OpCode op = GET_OPCODE(i);
  451. switch (op) {
  452. case OP_MOVE: {
  453. int b = GETARG_B(i); /* move from 'b' to 'a' */
  454. if (b < GETARG_A(i))
  455. return basicgetobjname(p, ppc, b, name); /* get name for 'b' */
  456. break;
  457. }
  458. case OP_GETUPVAL: {
  459. *name = upvalname(p, GETARG_B(i));
  460. return "upvalue";
  461. }
  462. case OP_LOADK: return kname(p, GETARG_Bx(i), name);
  463. case OP_LOADKX: return kname(p, GETARG_Ax(p->code[pc + 1]), name);
  464. default: break;
  465. }
  466. }
  467. return NULL; /* could not find reasonable name */
  468. }
  469. /*
  470. ** Find a "name" for the register 'c'.
  471. */
  472. static void rname (const Proto *p, int pc, int c, const char **name) {
  473. const char *what = basicgetobjname(p, &pc, c, name); /* search for 'c' */
  474. if (!(what && *what == 'c')) /* did not find a constant name? */
  475. *name = "?";
  476. }
  477. /*
  478. ** Check whether table being indexed by instruction 'i' is the
  479. ** environment '_ENV'
  480. */
  481. static const char *isEnv (const Proto *p, int pc, Instruction i, int isup) {
  482. int t = GETARG_B(i); /* table index */
  483. const char *name; /* name of indexed variable */
  484. if (isup) /* is 't' an upvalue? */
  485. name = upvalname(p, t);
  486. else /* 't' is a register */
  487. basicgetobjname(p, &pc, t, &name);
  488. return (name && strcmp(name, LUA_ENV) == 0) ? "global" : "field";
  489. }
  490. /*
  491. ** Extend 'basicgetobjname' to handle table accesses
  492. */
  493. static const char *getobjname (const Proto *p, int lastpc, int reg,
  494. const char **name) {
  495. const char *kind = basicgetobjname(p, &lastpc, reg, name);
  496. if (kind != NULL)
  497. return kind;
  498. else if (lastpc != -1) { /* could find instruction? */
  499. Instruction i = p->code[lastpc];
  500. OpCode op = GET_OPCODE(i);
  501. switch (op) {
  502. case OP_GETTABUP: {
  503. int k = GETARG_C(i); /* key index */
  504. kname(p, k, name);
  505. return isEnv(p, lastpc, i, 1);
  506. }
  507. case OP_GETTABLE: {
  508. int k = GETARG_C(i); /* key index */
  509. rname(p, lastpc, k, name);
  510. return isEnv(p, lastpc, i, 0);
  511. }
  512. case OP_GETI: {
  513. *name = "integer index";
  514. return "field";
  515. }
  516. case OP_GETFIELD: {
  517. int k = GETARG_C(i); /* key index */
  518. kname(p, k, name);
  519. return isEnv(p, lastpc, i, 0);
  520. }
  521. case OP_SELF: {
  522. int k = GETARG_C(i); /* key index */
  523. kname(p, k, name);
  524. return "method";
  525. }
  526. default: break; /* go through to return NULL */
  527. }
  528. }
  529. return NULL; /* could not find reasonable name */
  530. }
  531. /*
  532. ** Try to find a name for a function based on the code that called it.
  533. ** (Only works when function was called by a Lua function.)
  534. ** Returns what the name is (e.g., "for iterator", "method",
  535. ** "metamethod") and sets '*name' to point to the name.
  536. */
  537. static const char *funcnamefromcode (lua_State *L, const Proto *p,
  538. int pc, const char **name) {
  539. TMS tm = (TMS)0; /* (initial value avoids warnings) */
  540. Instruction i = p->code[pc]; /* calling instruction */
  541. switch (GET_OPCODE(i)) {
  542. case OP_CALL:
  543. case OP_TAILCALL:
  544. return getobjname(p, pc, GETARG_A(i), name); /* get function name */
  545. case OP_TFORCALL: { /* for iterator */
  546. *name = "for iterator";
  547. return "for iterator";
  548. }
  549. /* other instructions can do calls through metamethods */
  550. case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
  551. case OP_GETI: case OP_GETFIELD:
  552. tm = TM_INDEX;
  553. break;
  554. case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD:
  555. tm = TM_NEWINDEX;
  556. break;
  557. case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
  558. tm = cast(TMS, GETARG_C(i));
  559. break;
  560. }
  561. case OP_UNM: tm = TM_UNM; break;
  562. case OP_BNOT: tm = TM_BNOT; break;
  563. case OP_LEN: tm = TM_LEN; break;
  564. case OP_CONCAT: tm = TM_CONCAT; break;
  565. case OP_EQ: tm = TM_EQ; break;
  566. /* no cases for OP_EQI and OP_EQK, as they don't call metamethods */
  567. case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break;
  568. case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break;
  569. case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break;
  570. default:
  571. return NULL; /* cannot find a reasonable name */
  572. }
  573. *name = getshrstr(G(L)->tmname[tm]) + 2;
  574. return "metamethod";
  575. }
  576. /*
  577. ** Try to find a name for a function based on how it was called.
  578. */
  579. static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
  580. const char **name) {
  581. if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
  582. *name = "?";
  583. return "hook";
  584. }
  585. else if (ci->callstatus & CIST_FIN) { /* was it called as a finalizer? */
  586. *name = "__gc";
  587. return "metamethod"; /* report it as such */
  588. }
  589. else if (isLua(ci))
  590. return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name);
  591. else
  592. return NULL;
  593. }
  594. /* }====================================================== */
  595. /*
  596. ** Check whether pointer 'o' points to some value in the stack frame of
  597. ** the current function and, if so, returns its index. Because 'o' may
  598. ** not point to a value in this stack, we cannot compare it with the
  599. ** region boundaries (undefined behavior in ISO C).
  600. */
  601. static int instack (CallInfo *ci, const TValue *o) {
  602. int pos;
  603. StkId base = ci->func.p + 1;
  604. for (pos = 0; base + pos < ci->top.p; pos++) {
  605. if (o == s2v(base + pos))
  606. return pos;
  607. }
  608. return -1; /* not found */
  609. }
  610. /*
  611. ** Checks whether value 'o' came from an upvalue. (That can only happen
  612. ** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
  613. ** upvalues.)
  614. */
  615. static const char *getupvalname (CallInfo *ci, const TValue *o,
  616. const char **name) {
  617. LClosure *c = ci_func(ci);
  618. int i;
  619. for (i = 0; i < c->nupvalues; i++) {
  620. if (c->upvals[i]->v.p == o) {
  621. *name = upvalname(c->p, i);
  622. return "upvalue";
  623. }
  624. }
  625. return NULL;
  626. }
  627. static const char *formatvarinfo (lua_State *L, const char *kind,
  628. const char *name) {
  629. if (kind == NULL)
  630. return ""; /* no information */
  631. else
  632. return luaO_pushfstring(L, " (%s '%s')", kind, name);
  633. }
  634. /*
  635. ** Build a string with a "description" for the value 'o', such as
  636. ** "variable 'x'" or "upvalue 'y'".
  637. */
  638. static const char *varinfo (lua_State *L, const TValue *o) {
  639. CallInfo *ci = L->ci;
  640. const char *name = NULL; /* to avoid warnings */
  641. const char *kind = NULL;
  642. if (isLua(ci)) {
  643. kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
  644. if (!kind) { /* not an upvalue? */
  645. int reg = instack(ci, o); /* try a register */
  646. if (reg >= 0) /* is 'o' a register? */
  647. kind = getobjname(ci_func(ci)->p, currentpc(ci), reg, &name);
  648. }
  649. }
  650. return formatvarinfo(L, kind, name);
  651. }
  652. /*
  653. ** Raise a type error
  654. */
  655. static l_noret typeerror (lua_State *L, const TValue *o, const char *op,
  656. const char *extra) {
  657. const char *t = luaT_objtypename(L, o);
  658. luaG_runerror(L, "attempt to %s a %s value%s", op, t, extra);
  659. }
  660. /*
  661. ** Raise a type error with "standard" information about the faulty
  662. ** object 'o' (using 'varinfo').
  663. */
  664. l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
  665. typeerror(L, o, op, varinfo(L, o));
  666. }
  667. /*
  668. ** Raise an error for calling a non-callable object. Try to find a name
  669. ** for the object based on how it was called ('funcnamefromcall'); if it
  670. ** cannot get a name there, try 'varinfo'.
  671. */
  672. l_noret luaG_callerror (lua_State *L, const TValue *o) {
  673. CallInfo *ci = L->ci;
  674. const char *name = NULL; /* to avoid warnings */
  675. const char *kind = funcnamefromcall(L, ci, &name);
  676. const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o);
  677. typeerror(L, o, "call", extra);
  678. }
  679. l_noret luaG_forerror (lua_State *L, const TValue *o, const char *what) {
  680. luaG_runerror(L, "bad 'for' %s (number expected, got %s)",
  681. what, luaT_objtypename(L, o));
  682. }
  683. l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
  684. if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
  685. luaG_typeerror(L, p1, "concatenate");
  686. }
  687. l_noret luaG_opinterror (lua_State *L, const TValue *p1,
  688. const TValue *p2, const char *msg) {
  689. if (!ttisnumber(p1)) /* first operand is wrong? */
  690. p2 = p1; /* now second is wrong */
  691. luaG_typeerror(L, p2, msg);
  692. }
  693. /*
  694. ** Error when both values are convertible to numbers, but not to integers
  695. */
  696. l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
  697. lua_Integer temp;
  698. if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I))
  699. p2 = p1;
  700. luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
  701. }
  702. l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
  703. const char *t1 = luaT_objtypename(L, p1);
  704. const char *t2 = luaT_objtypename(L, p2);
  705. if (strcmp(t1, t2) == 0)
  706. luaG_runerror(L, "attempt to compare two %s values", t1);
  707. else
  708. luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
  709. }
  710. /* add src:line information to 'msg' */
  711. const char *luaG_addinfo (lua_State *L, const char *msg, TString *src,
  712. int line) {
  713. char buff[LUA_IDSIZE];
  714. if (src) {
  715. size_t idlen;
  716. const char *id = getlstr(src, idlen);
  717. luaO_chunkid(buff, id, idlen);
  718. }
  719. else { /* no source available; use "?" instead */
  720. buff[0] = '?'; buff[1] = '\0';
  721. }
  722. return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
  723. }
  724. l_noret luaG_errormsg (lua_State *L) {
  725. if (L->errfunc != 0) { /* is there an error handling function? */
  726. StkId errfunc = restorestack(L, L->errfunc);
  727. lua_assert(ttisfunction(s2v(errfunc)));
  728. setobjs2s(L, L->top.p, L->top.p - 1); /* move argument */
  729. setobjs2s(L, L->top.p - 1, errfunc); /* push function */
  730. L->top.p++; /* assume EXTRA_STACK */
  731. luaD_callnoyield(L, L->top.p - 2, 1); /* call it */
  732. }
  733. luaD_throw(L, LUA_ERRRUN);
  734. }
  735. l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
  736. CallInfo *ci = L->ci;
  737. const char *msg;
  738. va_list argp;
  739. luaC_checkGC(L); /* error message uses memory */
  740. va_start(argp, fmt);
  741. msg = luaO_pushvfstring(L, fmt, argp); /* format message */
  742. va_end(argp);
  743. if (msg == NULL) /* no memory to format message? */
  744. luaD_throw(L, LUA_ERRMEM);
  745. else if (isLua(ci)) { /* Lua function? */
  746. /* add source:line information */
  747. luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
  748. setobjs2s(L, L->top.p - 2, L->top.p - 1); /* remove 'msg' */
  749. L->top.p--;
  750. }
  751. luaG_errormsg(L);
  752. }
  753. /*
  754. ** Check whether new instruction 'newpc' is in a different line from
  755. ** previous instruction 'oldpc'. More often than not, 'newpc' is only
  756. ** one or a few instructions after 'oldpc' (it must be after, see
  757. ** caller), so try to avoid calling 'luaG_getfuncline'. If they are
  758. ** too far apart, there is a good chance of a ABSLINEINFO in the way,
  759. ** so it goes directly to 'luaG_getfuncline'.
  760. */
  761. static int changedline (const Proto *p, int oldpc, int newpc) {
  762. if (p->lineinfo == NULL) /* no debug information? */
  763. return 0;
  764. if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */
  765. int delta = 0; /* line difference */
  766. int pc = oldpc;
  767. for (;;) {
  768. int lineinfo = p->lineinfo[++pc];
  769. if (lineinfo == ABSLINEINFO)
  770. break; /* cannot compute delta; fall through */
  771. delta += lineinfo;
  772. if (pc == newpc)
  773. return (delta != 0); /* delta computed successfully */
  774. }
  775. }
  776. /* either instructions are too far apart or there is an absolute line
  777. info in the way; compute line difference explicitly */
  778. return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc));
  779. }
  780. /*
  781. ** Traces Lua calls. If code is running the first instruction of a function,
  782. ** and function is not vararg, and it is not coming from an yield,
  783. ** calls 'luaD_hookcall'. (Vararg functions will call 'luaD_hookcall'
  784. ** after adjusting its variable arguments; otherwise, they could call
  785. ** a line/count hook before the call hook. Functions coming from
  786. ** an yield already called 'luaD_hookcall' before yielding.)
  787. */
  788. int luaG_tracecall (lua_State *L) {
  789. CallInfo *ci = L->ci;
  790. Proto *p = ci_func(ci)->p;
  791. ci->u.l.trap = 1; /* ensure hooks will be checked */
  792. if (ci->u.l.savedpc == p->code) { /* first instruction (not resuming)? */
  793. if (p->flag & PF_ISVARARG)
  794. return 0; /* hooks will start at VARARGPREP instruction */
  795. else if (!(ci->callstatus & CIST_HOOKYIELD)) /* not yielded? */
  796. luaD_hookcall(L, ci); /* check 'call' hook */
  797. }
  798. return 1; /* keep 'trap' on */
  799. }
  800. /*
  801. ** Traces the execution of a Lua function. Called before the execution
  802. ** of each opcode, when debug is on. 'L->oldpc' stores the last
  803. ** instruction traced, to detect line changes. When entering a new
  804. ** function, 'npci' will be zero and will test as a new line whatever
  805. ** the value of 'oldpc'. Some exceptional conditions may return to
  806. ** a function without setting 'oldpc'. In that case, 'oldpc' may be
  807. ** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc'
  808. ** at most causes an extra call to a line hook.)
  809. ** This function is not "Protected" when called, so it should correct
  810. ** 'L->top.p' before calling anything that can run the GC.
  811. */
  812. int luaG_traceexec (lua_State *L, const Instruction *pc) {
  813. CallInfo *ci = L->ci;
  814. lu_byte mask = cast_byte(L->hookmask);
  815. const Proto *p = ci_func(ci)->p;
  816. int counthook;
  817. if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */
  818. ci->u.l.trap = 0; /* don't need to stop again */
  819. return 0; /* turn off 'trap' */
  820. }
  821. pc++; /* reference is always next instruction */
  822. ci->u.l.savedpc = pc; /* save 'pc' */
  823. counthook = (mask & LUA_MASKCOUNT) && (--L->hookcount == 0);
  824. if (counthook)
  825. resethookcount(L); /* reset count */
  826. else if (!(mask & LUA_MASKLINE))
  827. return 1; /* no line hook and count != 0; nothing to be done now */
  828. if (ci->callstatus & CIST_HOOKYIELD) { /* hook yielded last time? */
  829. ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
  830. return 1; /* do not call hook again (VM yielded, so it did not move) */
  831. }
  832. if (!luaP_isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */
  833. L->top.p = ci->top.p; /* correct top */
  834. if (counthook)
  835. luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */
  836. if (mask & LUA_MASKLINE) {
  837. /* 'L->oldpc' may be invalid; use zero in this case */
  838. int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0;
  839. int npci = pcRel(pc, p);
  840. if (npci <= oldpc || /* call hook when jump back (loop), */
  841. changedline(p, oldpc, npci)) { /* or when enter new line */
  842. int newline = luaG_getfuncline(p, npci);
  843. luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */
  844. }
  845. L->oldpc = npci; /* 'pc' of last call to line hook */
  846. }
  847. if (L->status == LUA_YIELD) { /* did hook yield? */
  848. if (counthook)
  849. L->hookcount = 1; /* undo decrement to zero */
  850. ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */
  851. luaD_throw(L, LUA_YIELD);
  852. }
  853. return 1; /* keep 'trap' on */
  854. }