forked from xjdrew/lua-gdb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lua-gdb-python2.py
704 lines (566 loc) · 18.9 KB
/
lua-gdb-python2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
from __future__ import print_function
import re
import sys
import gdb
import traceback
print("Loading Lua Runtime support.", file=sys.stderr)
print("python: "+sys.version)
#http://python3porting.com/differences.html
if sys.version > '3':
xrange = range
# allow to manually reload while developing
objfile = gdb.current_objfile() or gdb.objfiles()[0]
objfile.pretty_printers = []
# gdb.Value to specific type tt
def cast_to_type_pointer(o, tt):
t = gdb.lookup_type(tt)
return o.cast(t.pointer())
# basic types
LUA_TNIL =0
LUA_TBOOLEAN =1
LUA_TLIGHTUSERDATA =2
LUA_TNUMBER =3
LUA_TSTRING =4
LUA_TTABLE =5
LUA_TFUNCTION =6
LUA_TUSERDATA =7
LUA_TTHREAD =8
def makevariant(t, v): return t | (v << 4)
def ctb(t): return t | (1 << 6)
LUA_VFALSE = makevariant(LUA_TBOOLEAN, 0)
LUA_VTRUE = makevariant(LUA_TBOOLEAN, 1)
# test type
def checktype(o, t): return o['tt_']&0x0f == t
def checktag(o, t): return o['tt_'] == t
# input GCObject*
def cast_u(o,type_str):
return cast_to_type_pointer(o,type_str)
# <TValue> -> <int>
def ivalue(o): return o['value_']['i']
# <TValue> -> <float>
def fltvalue(o): return o['value_']['n']
# <TValue> -> <lightuserdata>
def pvalue(o): return o['value_']['p']
# <TValue> -> <TString>
def tsvalue(o): return cast_u(o['value_']['gc'],'TString')
# <TValue> -> <LClosure>
def clLvalue(o): return cast_u(o['value_']['gc'],'LClosure')
# <TValue> -> <CClosure>
def clCvalue(o): return cast_u(o['value_']['gc'],'CClosure')
# <TValue> -> <lua_CFunction>
def fvalue(o): return o['value_']['f']
# <TValue> -> <Table>
def hvalue(o): return cast_u(o['value_']['gc'],'Table')
# <TValue> -> <boolean>
def bvalue(o): return checktype(o, LUA_VTRUE)
# <TValue> -> <lua_State>
def thvalue(o): return cast_u(o['value_']['gc'],'lua_State')
LUA_VNUMINT = makevariant(LUA_TNUMBER, 0)
LUA_VNUMFLT = makevariant(LUA_TNUMBER, 1)
def ttisnumber(o): return checktype(o, LUA_TNUMBER)
def ttisfloat(o): return checktag(o, LUA_VNUMFLT)
def ttisinteger(o): return checktag(o, LUA_VNUMINT)
def ttisnil(o): return checktype(o, LUA_TNIL)
def ttisboolean(o): return checktype(o, LUA_TBOOLEAN)
LUA_VLIGHTUSERDATA = makevariant(LUA_TLIGHTUSERDATA, 0)
LUA_VUSERDATA = makevariant(LUA_TUSERDATA, 0)
def ttislightuserdata(o): return checktag(o, LUA_VLIGHTUSERDATA)
def ttisfulluserdata(o): return checktag(o, ctb(LUA_VUSERDATA))
LUA_VSHRSTR = makevariant(LUA_TSTRING, 0)
LUA_VLNGSTR = makevariant(LUA_TSTRING, 1)
def ttisstring(o): return checktype(o, LUA_TSTRING)
def ttisshrstring(o): return checktype(o, ctb(LUA_VSHRSTR))
def ttislngstring(o): return checktype(o, ctb(LUA_VLNGSTR))
LUA_VTABLE = makevariant(LUA_TTABLE, 0)
def ttistable(o): return checktag(o, ctb(LUA_VTABLE))
LUA_VLCL = makevariant(LUA_TFUNCTION, 0)
LUA_VLCF = makevariant(LUA_TFUNCTION, 1)
LUA_VCCL = makevariant(LUA_TFUNCTION, 2)
def ttisfunction(o): return checktype(o, LUA_TFUNCTION)
def ttisclosure(o): return o['tt_'] & 0x1f == LUA_VLCL
def ttisCclosure(o): return checktag(o, ctb(LUA_VCCL))
def ttisLclosure(o): return checktag(o, ctb(LUA_VLCL))
def ttislcf(o): return checktag(o, LUA_VLCF)
LUA_VTHREAD = makevariant(LUA_TTHREAD, 0)
def ttisthread(o): return checktag(o, ctb(LUA_VTHREAD))
# gdb.Value to string
def value_to_string(val):
s = str(val.dereference())
if len(s) > 1 and s[0] == '"' and s[-1] == '"':
return s[1:-1]
return s
def cast_luaState(o):
return cast_to_type_pointer(o, "struct lua_State")
#
# Value wrappers
#
# StackValue to TValue
def s2v(stk): return cast_u(stk,'TValue')
# struct lua_TValue
class TValueValue:
"Wrapper for TValue value."
def __init__(self, val):
self.val = val
def upvars(self):
if ttisCclosure(self.val):
f = clCvalue(self.val)
for i in xrange(f['nupvalues']):
yield "(%d)" % (i+1), cast_to_type_pointer(f['upvalue'], "TValue") + i
elif ttisLclosure(self.val):
f = clLvalue(self.val)
proto = f['p']
for i in xrange(int(proto['sizeupvalues'])):
uv = cast_to_type_pointer(f['upvals'][i], "struct UpVal")
value = cast_u(uv['v'],'TValue')
name = (proto['upvalues'] + i)['name']
if name:
yield value_to_string(name), value
else:
yield "(no name)", value
# struct CallInfo
class CallInfoValue:
"Wrapper for CallInfo value."
CIST_C = 1<<1
CIST_TAIL = 1<<5
CIST_FIN = 1<<7
def __init__(self, L, ci):
self.L = L
self.ci = ci
self.name = None
self.namewhat = None
if self.is_lua():
proto = clLvalue(s2v(self.ci['func']))['p']
self.proto = proto
if not proto['source']:
self.source = "?"
else:
self.source = proto['source'].dereference()
self.linedefined = proto['linedefined']
self.lastlinedefined = proto['lastlinedefined']
if self.linedefined == 0:
self.what = "main"
else:
self.what = "Lua"
self.currentpc = (self.ci['u']['l']['savedpc'] - proto['code']) - 1
self.currentline = self.getfuncline(proto, self.currentpc)
else:
self.source = "[C]"
self.linedefined = -1
self.lastlinedefined = -1
self.what = "C"
self.currentline = -1
if self.is_fin():
self.name = "__gc"
self.namewhat = "metamethod"
def getfuncline(self, proto, pc):
"""
ldebug.c luaG_getfuncline
"""
if not proto['lineinfo']:
return -1
def getbaseline(proto, pc):
if proto['sizeabslineinfo'] == 0 or pc < proto['abslineinfo'][0]['pc']:
return -1, proto['linedefined']
if pc >= proto['abslineinfo'][proto['sizeabslineinfo']-1]['pc']:
i = proto['sizeabslineinfo']-1
else:
j = proto['sizeabslineinfo']-1
i = 0
while i < j - 1:
m = (j + i) / 2
if pc >= proto['abslineinfo'][m]['pc']:
i = m
else:
j = m
return proto['abslineinfo'][i]['pc'], proto['abslineinfo'][i]['line']
basepc, baseline = getbaseline(proto, pc)
while basepc < pc:
basepc+=1
baseline += proto['lineinfo'][basepc]
return baseline
@property
def funcname(self):
if self.what == "main":
return "main chunk"
if self.namewhat:
return "%s '%s'" % (self.namewhat, self.name)
func = s2v(self.ci['func'])
if ttislcf(func):
return "%s" % fvalue(func)
if ttisCclosure(func):
return "%s" % clCvalue(func)['f']
return '?'
def is_lua(self):
return not (self.ci['callstatus'] & CallInfoValue.CIST_C)
def is_tailcall(self):
return self.ci['callstatus'] & CallInfoValue.CIST_TAIL
def is_fin(self):
return self.ci['callstatus'] & CallInfoValue.CIST_FIN
# stack frame information
def frame_info(self):
return '%s:%d: in %s' % (self.source, self.currentline, self.funcname)
# luastack:
# vararg(1)
# ...
# vararg(nextraargs) <- ci->u.l.nextraargs nextra vararg
# callee <- ci->func
# arg(1)
# ...
# arg(n)
# local(1)
# ...
# local(n)
@property
def stack_base(self):
return cast_u(self.ci['func'],'TValue') + 1
@property
def stack_top(self):
if self.ci == self.L['ci']:
return self.L['top']
else:
nextcv = CallInfoValue(self.L, self.ci['next'])
return nextcv.stack_base - 1
def getlocalname(self, n):
if not self.is_lua():
return None
proto = self.proto
currentpc = self.currentpc
i = 0
while i< proto['sizelocvars']:
locvar = proto['locvars'] + i
if locvar['startpc'] <= currentpc and currentpc < locvar['endpc']:
n = n - 1
if n == 0:
return value_to_string(locvar['varname'])
i = i + 1
return None
def upvars(self):
tv = TValueValue(s2v(self.ci['func']))
return tv.upvars()
def varargs(self):
if not self.is_lua():
return
if self.proto['is_vararg'] != 1:
return
nextra = self.ci['u']['l']['nextraargs']
for i in xrange(nextra):
yield "(*vararg)", s2v(self.ci['func'] - (i+1))
def locvars(self):
base = self.stack_base
limit = self.stack_top
i = 1
while True:
name = self.getlocalname(i)
if not name:
if (limit - base) >= i:
if self.is_lua():
name = "(temporary)"
else:
name = "(C temporary)"
else:
return
yield name, s2v(base + i - 1)
i = i + 1
#
# Pretty Printers
#
def tvaluestring(value):
if ttisnil(value): # nil
return "nil"
elif ttisboolean(value): # boolean
if bvalue(value) > 0:
return "True"
else:
return "False"
elif ttisnumber(value): # number
if ttisfloat(value):
return fltvalue(value)
elif ttisinteger(value):
return ivalue(value)
elif ttisstring(value): # string
return tsvalue(value)
elif ttistable(value): # table
return hvalue(value)
elif ttisfunction(value):
if ttisLclosure(value): # lua closure
return clLvalue(value)
elif ttislcf(value): # light C function
return fvalue(value)
elif ttisCclosure(value): # 2 C closure
return clCvalue(value)
elif ttisfulluserdata(value):
return "Userdata"
elif ttislightuserdata(value): # lightuserdata
return "<lightuserdata 0x%x>" % int(pvalue(value))
elif ttisthread(value):
return thvalue(value)
assert False, value['tt_']
class TValuePrinter:
"Pretty print lua value."
pattern = re.compile(r'^(struct TValue)|(TValue)$')
def __init__(self, val):
self.val = val
def to_string(self):
return tvaluestring(self.val)
def display_hint(self):
return "string"
class TStringPrinter:
"Pretty print lua string."
pattern = re.compile(r'^(struct TString)|(TString)$')
def __init__(self, val):
self.val = val
def display_hint(self):
return "string"
def to_string(self):
s = self.val["contents"]
return s.cast(gdb.lookup_type('char').pointer())
class TablePrinter:
"Pretty print lua table."
pattern = re.compile(r'^(struct Table)|(Table)$')
marked = None
def __init__(self, val):
self.val = val
def display_hint(self):
return "map"
def to_string(self):
return "<table 0x%x>" % int(self.val.address)
def children(self):
setMarked = False
if TablePrinter.marked == None:
TablePrinter.marked = {}
setMarked = True
address = int(self.val.address)
if address in TablePrinter.marked:
return TablePrinter.marked[address]
TablePrinter.marked[address] = self.to_string()
# array part
sizearray = self.realasize()
i = 0
result = []
while i < sizearray:
val = self.val['array'][i]
if ttisnil(val):
i = i + 1
continue
result.append((str(2*i), i))
result.append((str(2*i + 1), val))
i = i + 1
# hash part
j = 0
last = 1 << self.val['lsizenode']
while j < last:
node = self.val['node'][j]
j = j + 1
value = node['i_val']
if ttisnil(value):
continue
fakeTValue = {
"tt_": node['u']['key_tt'],
"value_": node['u']['key_val']
}
result.append(str(2*i + 2*j), tvaluestring(fakeTValue))
result.append(str(2*i + 2*j + 1), value)
if setMarked:
TablePrinter.marked = None
return result
def realasize(self):
def isrealasize(self): return (self.val['flags'] & (1<<7)) == 0
def ispow2(x): return (((x) & ((x) - 1)) == 0)
if (isrealasize(self) or ispow2(self.val['alimit'])):
return self.val['alimit']
else:
size = self.val['alimit']
size |= (size >> 1)
size |= (size >> 2)
size |= (size >> 4)
size |= (size >> 8)
size |= (size >> 16)
size += 1
return size
class LClosurePrinter:
"Pretty print lua closure."
pattern = re.compile(r'^(struct LClosure)|(LClosure)$')
def __init__(self, val):
self.val = val
def display_hint(self):
return "map"
def to_string(self):
return "<lclosure 0x%x>" % int(self.val.address)
def children(self):
p = self.val['p']
result = []
result.append("1", "file")
result.append("2", p['source'].dereference())
result.append("3", "linestart")
result.append("4", p['linedefined'])
result.append("5", "lineend")
result.append("6", p['lastlinedefined'])
result.append("7", "nupvalues")
result.append("8", self.val['nupvalues'])
return result
class CClosurePrinter:
"Pretty print lua closure."
pattern = re.compile(r'^(struct CClosure)|(CClosure)$')
def __init__(self, val):
self.val = val
def display_hint(self):
return "map"
def to_string(self):
return "<cclosure 0x%x>" % int(self.val.address)
def children(self):
result = []
result.append("1", "nupvalues")
result.append("2", self.val['nupvalues'])
return result
class LuaStatePrinter:
"Pretty print lua_State."
pattern = re.compile(r'^struct lua_State$')
def __init__(self, val):
self.val = val
def display_hint(self):
return "map"
def to_string(self):
return "<coroutine 0x%x>" % int(self.val.address)
def children(self):
cv = CallInfoValue(self.val, self.val['ci'])
result = []
result.append( "1", "source")
result.append( "2", "%s:%d" % (cv.source, cv.currentline))
result.append( "3", "func")
result.append( "4", cv.funcname)
return result
#
# Register all the *Printer classes above.
#
def makematcher(klass):
def matcher(val):
try:
if klass.pattern.match(str(val.type)):
return klass(val)
except Exception:
pass
return matcher
objfile.pretty_printers.extend([makematcher(var) for var in vars().values() if hasattr(var, 'pattern')])
class LuaStackCmd(gdb.Command):
"""luastack [L]
Prints values on the Lua C stack. Without arguments, uses the current value of "L"
as the lua_State*. You can provide an alternate lua_State as the first argument."""
def __init__(self):
gdb.Command.__init__(self, "luastack", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
def invoke(self, args, _from_tty):
try:
argv = gdb.string_to_argv(args)
if len(argv) > 0:
L = cast_luaState(gdb.parse_and_eval(argv[0]))
else:
L = gdb.parse_and_eval("L")
stack = L['top']['p'] - 1
i = 0
while stack > L['stack']['p']:
print("haha",i)
print("#%d\t%s\t%s" % (i, str(stack), stack['tbclist']))
stack = stack - 1
i = i + 1
except Exception as e:
traceback.print_exc()
class LuaTracebackCmd(gdb.Command):
"""luabacktrace [L]
Dumps Lua execution stack, as debug.traceback() does. Without
arguments, uses the current value of "L" as the
lua_State*. You can provide an alternate lua_State as the
first argument.
"""
def __init__(self):
gdb.Command.__init__(self, "luatraceback", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
def invoke(self, args, _from_tty):
argv = gdb.string_to_argv(args)
if len(argv) > 0:
L = cast_luaState(gdb.parse_and_eval(argv[0]))
else:
L = gdb.parse_and_eval("L")
ci = L['ci']
print("stack traceback:")
while ci != L['base_ci'].address:
cv = CallInfoValue(L, ci)
print('\t%s' % (cv.frame_info()))
if cv.is_tailcall():
print('\t(...tail calls...)')
ci = ci['previous']
thread_status_tbl = {
0:"running",
1:"dead",
2:"suspended",
3:"normal"
}
class LuaCoroutinesCmd(gdb.Command):
"""luacoroutines [L]
List all coroutines. Without arguments, uses the current value of "L" as the
lua_State*. You can provide an alternate lua_State as the
first argument.
"""
def __init__(self):
gdb.Command.__init__(self, "luacoroutines", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
def invoke(self, args, _from_tty):
argv = gdb.string_to_argv(args)
if len(argv) > 0:
L = cast_luaState(gdb.parse_and_eval(argv[0]))
else:
L = gdb.parse_and_eval("L")
# global_State
lG = L['l_G']
# mainthread
print("mainthread", lG['mainthread'])
obj = lG['allgc']
while obj:
if obj['tt'] == 8:
th = cast_u(obj,"lua_State")
print("thread", th, thread_status_tbl[int(th['status'])])
obj = obj['next']
def dereference(v):
t = v.type
print(t,t.code==gdb.TYPE_CODE_PTR)
if t.code == gdb.TYPE_CODE_PTR:
return v.dereference()
return str(v)
class LuaGetLocalCmd(gdb.Command):
"""luagetlocal [L [f]]
Print all local variables of the function at level 'f' of the stack 'thread'.
With no arguments, Dump all local variable of the current funtion in the stack of 'L';
"""
def __init__(self):
gdb.Command.__init__(self, "luagetlocal", gdb.COMMAND_STACK, gdb.COMPLETE_NONE)
def invoke(self, args, _from_tty):
try:
argv = gdb.string_to_argv(args)
if len(argv) > 0:
L = cast_luaState(gdb.parse_and_eval(argv[0]))
else:
L = gdb.parse_and_eval("L")
if len(argv) > 1:
arg2 = gdb.parse_and_eval(argv[1])
else:
arg2 = gdb.parse_and_eval("0")
level = arg2
ci = L['ci']
while level > 0:
ci = ci['previous']
if ci == L['base_ci'].address:
break
level = level - 1
if level != 0:
print("No function at level %d" % arg2)
return
cv = CallInfoValue(L, ci)
print("call info: %s" % cv.frame_info())
for name, var in cv.upvars():
print("\tupval %s = %s" % (name, var.dereference()))
for name, var in cv.varargs():
print("\t..... %s = %s" % (name, var.dereference()))
for name, var in cv.locvars():
print("\tlocal %s = %s" % (name, var.dereference()))
except Exception as e:
traceback.print_exc()
LuaStackCmd()
LuaTracebackCmd()
LuaCoroutinesCmd()
LuaGetLocalCmd()