Coverage Report

Created: 2025-07-18 06:59

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