forked from openresty/openresty-gdb-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
luajit21.py
4020 lines (3255 loc) · 108 KB
/
luajit21.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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import gdb
import gdbutils
import ngxlua
import string
import re
import time
typ = gdbutils.typ
null = gdbutils.null
newval = gdbutils.newval
ptr2int = gdbutils.ptr2int
err = gdbutils.err
out = gdbutils.out
warn = gdbutils.warn
if sys.version_info[0] >= 3: # Python 3K
global xrange
xrange = range
def LJ_TNIL():
return ~newval("unsigned int", 0)
def LJ_TFALSE():
return ~newval("unsigned int", 1)
def LJ_TTRUE():
return ~newval("unsigned int", 2)
def LJ_TLIGHTUD():
return ~newval("unsigned int", 3)
def LJ_TSTR():
return ~newval("unsigned int", 4)
def LJ_TUPVAL():
return ~newval("unsigned int", 5)
def LJ_TTHREAD():
return ~newval("unsigned int", 6)
def LJ_TPROTO():
return ~newval("unsigned int", 7)
def LJ_TFUNC():
return ~newval("unsigned int", 8)
def LJ_TTRACE():
return ~newval("unsigned int", 9)
def LJ_TCDATA():
return ~newval("unsigned int", 10)
def LJ_TTAB():
return ~newval("unsigned int", 11)
def LJ_TUDATA():
return ~newval("unsigned int", 12)
def LJ_TNUMX():
return ~newval("unsigned int", 13)
def LJ_TISNUM():
return newval("unsigned int", 0xfffeffff)
def LJ_TISGCV():
return newval("unsigned int", 1 + ~4)
BC_RETM = 73
BC_RET = 74
BC_RET0 = 75
BC_RET1 = 76
FRAME_LUA = 0
FRAME_C = 1
FRAME_CONT = 2
FRAME_VARG = 3
FRAME_TYPE = 3
FRAME_P = 4
FRAME_TYPEP = FRAME_TYPE | FRAME_P
CFRAME_RESUME = 1
CFRAME_UNWIND_FF = 2
CFRAME_RAWMASK = ~(CFRAME_RESUME|CFRAME_UNWIND_FF)
CFRAME_OFS_L = 416
CFRAME_OFS_PC = 7*4 # for x86_64 (non-windows)
cfunc_cache = {}
LJ_VMST_INTERP = 0
LJ_VMST_C = 1
LJ_VMST_GC = 2
LJ_VMST_EXIT = 3
LJ_VMST_RECORD = 4
LJ_VMST_OPT = 5
LJ_VMST_ASM = 6
LJ_VMST__MAX = 7
vmstates = ['Interpreted', 'C code (from interpreted Lua code)', \
'Garbage collector', 'Trace exit handler', \
'Trace recorder', 'Optimizer', 'Assembler']
NO_BCPOS = ~0
FF_LUA = 0
FF_C = 1
GCROOT_MAX = 38
def get_global_L():
gL, _ = gdb.lookup_symbol("globalL")
if gL:
return gL.value()
cycle = gdb.lookup_global_symbol("ngx_cycle")
if cycle:
cycle = cycle.value()
gL = ngxlua.ngx_lua_get_main_lua_vm(cycle)
if gL:
return gL
raise gdb.GdbError("No global L located (tried globalL and ngx_cycle)")
def get_cur_L():
mL = get_global_L()
#out("mL type: %s\n" % str(mL.type))
#out("null type: %s\n" % str(null().type))
if mL == null():
return mL
try:
return gcref(G(mL)['cur_L'])['th'].address
except:
return mL
def gcval(o):
return gcref(o['gcr'])
def tabV(o):
return gcval(o)['tab'].address
def cframe_pc(cf):
#print("CFRAME!!")
return mref((cf.cast(typ("char*")) + CFRAME_OFS_PC).cast(typ("MRef*")).dereference(), \
"BCIns")
def cframe_L(cf):
return gcref((cf.cast(typ("char*")) + CFRAME_OFS_L) \
.cast(typ("GCRef*")).dereference())['th'].address
def frame_ftsz(tv):
return tv['fr']['tp']['ftsz']
def frame_type(f):
return (frame_ftsz(f) & FRAME_TYPE)
def frame_islua(f):
return frame_type(f) == FRAME_LUA
def frame_typep(f):
return (frame_ftsz(f) & FRAME_TYPEP)
def frame_isvarg(f):
return frame_typep(f) == FRAME_VARG
def frame_iscont(f):
return frame_typep(f) == FRAME_CONT
def sizeof(typ):
return gdb.parse_and_eval("sizeof(" + typ + ")")
def gcref(r):
return r['gcptr32'].cast(typ("uintptr_t")).cast(typ("GCobj*"))
def gcrefp(r, t):
#((t *)(void *)(uintptr_t)(r).gcptr32)
return r['gcptr32'].cast(typ(t + "*"))
def frame_gc(frame):
return gcref(frame['fr']['func'])
def obj2gco(v):
return v.cast(typ("GCobj*"))
def mref(r, t):
return r['ptr32'].cast(typ("uintptr_t")).cast(typ(t + "*"))
def frame_pc(f):
return mref(f['fr']['tp']['pcr'], "BCIns")
def frame_contpc(f):
return frame_pc(f - 1)
def bc_a(i):
return newval("BCReg", (i >> 8) & 0xff)
def frame_prevl(f):
return f - (1 + bc_a(frame_pc(f)[-1]))
def frame_sized(f):
return (frame_ftsz(f) & ~FRAME_TYPEP)
def frame_prevd(f):
#print "f = %x, sized = %x" % (ptr2int(f.cast(typ("char*"))), frame_sized(f))
return (f.cast(typ("char*")) - frame_sized(f)).cast(typ("TValue*"))
def frame_prev(f):
if frame_islua(f):
return frame_prevl(f)
else:
return frame_prevd(f)
def tvref(r):
return mref(r, "TValue")
def lj_debug_frame(L, base, level, bot):
frame = base - 1
nextframe = frame
while frame > bot:
#print "checking level %d\n" % level
if frame_gc(frame) == obj2gco(L):
level += 1
if level == 0:
return (frame, nextframe - frame)
level -= 1
nextframe = frame
if frame_islua(frame):
frame = frame_prevl(frame)
else:
if frame_isvarg(frame):
level += 1
frame = frame_prevd(frame)
return (null(), level)
def frame_func(f):
return frame_gc(f)['fn'].address
def isluafunc(fn):
return fn['c']['ffid'] == FF_LUA
def isffunc(fn):
return fn['c']['ffid'] > FF_C
def funcproto(fn):
return (mref(fn['l']['pc'], "char") - typ("GCproto").sizeof) \
.cast(typ("GCproto*"))
def proto_bc(pt):
return (pt.cast(typ("char*")) + typ("GCproto").sizeof).cast(typ("BCIns*"))
def proto_bcpos(pt, pc):
return (pc - proto_bc(pt)).cast(typ("BCPos"))
def proto_lineinfo(pt):
return mref(pt['lineinfo'], "void")
def lj_debug_line(pt, pc):
lineinfo = proto_lineinfo(pt)
if pc <= pt['sizebc'] and lineinfo:
first = pt['firstline']
if pc == pt['sizebc']:
return first + pt['numline']
if pc == 0:
return first
pc -= 1
if pt['numline'] < 256:
return first + lineinfo.cast(typ("uint8_t*"))[pc].cast(typ("BCLine"))
elif pt['numline'] < 65536:
return first + lineinfo.cast(typ("uint16_t*"))[pc].cast(typ("BCLine"))
else:
return first + lineinfo.cast(typ("uint32_t*"))[pc].cast(typ("BCLine"))
#print "Nothing: ", str(lineinfo)
return 0
def debug_framepc(L, T, fn, pt, nextframe):
if not isluafunc(fn):
return NO_BCPOS
if not nextframe:
cf = cframe_raw(L['cframe'])
#print("cf 0x%x" % ptr2int(cf))
if not cf or cframe_pc(cf) == cframe_L(cf):
return NO_BCPOS
ins = cframe_pc(cf)
#print("cframe pc: [0x%x]" % ptr2int(ins))
else:
if frame_islua(nextframe):
#print("frame pc")
ins = frame_pc(nextframe)
elif frame_iscont(nextframe):
#print("frame contpc")
ins = frame_contpc(nextframe)
else:
warn("Lua function below errfunc/gc/hook not supported yet")
return NO_BCPOS
pos = proto_bcpos(pt, ins) - 1
if pos > pt['sizebc']:
T = ((ins - 1).cast(typ("char*")) - \
typ("GCtrace")['startins'].bitpos / 8).cast(typ("GCtrace*"))
#print("T: %d" % int(T['traceno']))
try:
pos = proto_bcpos(pt, mref(T['startpc'], "BCIns"))
except:
return NO_BCPOS
return pos
def debug_frameline(L, T, fn, pt, nextframe):
pc = debug_framepc(L, T, fn, pt, nextframe)
if pc != NO_BCPOS:
pt = funcproto(fn)
return lj_debug_line(pt, pc)
#print("pc == %d" % pc)
return -1
def strref(r):
return gcref(r)['str'].address
def tabref(r):
return gcref(r)['tab'].address
def proto_chunkname(pt):
return strref(pt['chunkname'])
def strdata(s):
return (s + 1).cast(typ("char*"))
def G(L):
return mref(L['glref'], "global_State")
def cframe_raw(cf):
return (cf.cast(typ("intptr_t")) & CFRAME_RAWMASK).cast(typ("void*"))
def proto_varinfo(pt):
return mref(pt['varinfo'], 'uint8_t')
VARNAME_END = 0
VARNAME__MAX = 7
def lj_buf_ruleb128(p):
v = p.dereference().cast(typ("uint32_t"))
p += 1
if v >= 0x80:
sh = 0
v = v & 0x7f
while True:
sh += 7
v = v | ((p.dereference() & 0x7f) << sh)
if p.dereference() < 0x80:
p += 1
break
p += 1
return v, p
builtin_variable_names = [ \
"(for index)", \
"(for limit)", \
"(for step)", \
"(for generator)", \
"(for state)", \
"(for control)"]
def debug_varname(pt, pc, slot):
p = proto_varinfo(pt).cast(typ("char*"))
if p:
lastpc = 0
while True:
name = p
vn = p.cast(typ("uint8_t*")).dereference().cast(typ("uint32_t"))
if vn < VARNAME__MAX:
if vn == VARNAME_END:
break
else:
while True:
p += 1
if p.cast(typ("uint8_t*")).dereference() == 0:
break
p += 1
v, p = lj_buf_ruleb128(p)
startpc = lastpc + v
lastpc = startpc
if startpc > pc:
break
v, p = lj_buf_ruleb128(p)
endpc = startpc + v
if pc < endpc and slot == 0:
if vn < VARNAME__MAX:
out("\tlocal \"%s\"\n" % builtin_variable_names[int(vn - 1)])
else:
out("\tlocal \"%s\":\n" % name.string('iso-8859-6', 'ignore'))
return True
slot = slot - 1
return False
def lj_debug_dumpstack(L, T, depth, base, full):
global cfunc_cache
level = 0
dir = 1
if depth < 0:
level = ~depth
depth = dir = -1
bot = tvref(L['stack'])
while level != depth:
#print "checking level: %d" % level
bt = ""
frame, size = lj_debug_frame(L, base, level, bot)
if frame:
nextframe = (frame + size) if size else null()
fn = frame_func(frame)
#print "type(fn) == %s" % fn.type
if not fn:
return
pt = None
if isluafunc(fn):
pt = funcproto(fn)
line = debug_frameline(L, T, fn, pt, nextframe)
#print("line: %d\n" % line)
if line <= 0:
#print str(pt.dereference)
line = int(pt['firstline'])
name = proto_chunkname(pt)
if not name:
return ""
path = lstr2str(name)
bt += "%s:%d\n" % (path, line)
elif isffunc(fn):
bt += "builtin#%d\n" % int(fn['c']['ffid'])
else:
cfunc = fn['c']['f']
key = str(cfunc)
if key in cfunc_cache:
sym = cfunc_cache[key]
else:
sym = "C:%s\n" % cfunc
m = re.search('<.*?(\w+)*.*?>', cfunc.__str__())
if m:
sym = "C:%s\n" % m.group(1)
else:
sym = "C:%s\n" % key
cfunc_cache[key] = sym
bt += sym
#print "bt: " + sym
out(bt)
if full:
if not pt:
pt = funcproto(fn)
pc = debug_framepc(L, T, fn, pt, nextframe)
if pc != NO_BCPOS:
nf = nextframe
if not nf:
nf = L['top']
for slot in xrange(1, int(nf - frame)):
tv = frame + slot
if debug_varname(pt, pc, slot - 1):
dump_tvalue(tv)
elif dir == 1:
break
else:
level -= size
level += dir
return bt
def G2GG(gl):
#print(type(typ("GG_State")['g'].bitpos))
diff = gl.cast(typ("char*")) - int(typ("GG_State")['g'].bitpos / 8)
return diff.cast(typ("GG_State*"))
def G2J(gl):
return G2GG(gl)['J'].address
def traceref(J, n):
return gcref(J['trace'][n]).cast(typ("GCtrace*"))
class lbt(gdb.Command):
"""This command dumps out the current Lua-land backtrace in the lua_State specified. Only LuaJIT 2.1 is supported.
Usage: lbt [L]
lbt full [L]"""
def __init__ (self):
super (lbt, self).__init__("lbt", gdb.COMMAND_USER)
def invoke (self, args, from_tty):
argv = gdb.string_to_argv(args)
if len(argv) > 2:
raise gdb.GdbError("Usage: lbt [full] [L]")
full = False
if len(argv) > 0 and argv[0] == "full":
full = True
if len(argv) == 2:
L = gdbutils.parse_ptr(argv[1], "lua_State*")
if not L or str(L) == "void":
raise gdb.GdbError("L empty")
else:
L = get_cur_L()
else:
if len(argv) == 1:
L = gdbutils.parse_ptr(argv[0], "lua_State*")
if not L or str(L) == "void":
raise gdb.GdbError("L empty")
else:
L = get_cur_L()
#print "g: ", hex(int(L['glref']['ptr32']))
if L == null():
raise gdb.GdbError("L is NULL")
g = G(L)
vmstate = int(g['vmstate'])
#print "vmstate = %d" % vmstate
if vmstate >= 0:
#print "compiled code"
traceno = vmstate
J = G2J(g)
T = traceref(J, traceno)
base = tvref(g['jit_base'])
if not base:
try:
base = tvref(g['saved_jit_base'])
except:
pass
if not base:
raise gdb.GdbError("jit base is NULL (trace #%d)" % int(T['traceno']))
bt = lj_debug_dumpstack(L, T, 30, base, full)
else:
if vmstate == ~LJ_VMST_EXIT:
base = tvref(g['jit_base'])
if base:
bt = lj_debug_dumpstack(L, 0, 30, base, full)
else:
base = L['base']
bt = lj_debug_dumpstack(L, 0, 30, base, full)
else:
if vmstate == ~LJ_VMST_INTERP and not L['cframe']:
out("No Lua code running.\n")
return
if vmstate == ~LJ_VMST_INTERP or \
vmstate == ~LJ_VMST_C or \
vmstate == ~LJ_VMST_GC:
if vmstate == ~LJ_VMST_INTERP:
#out("Fetching edx...")
base = gdb.parse_and_eval("$edx").cast(typ("TValue*"))
else:
base = L['base']
bt = lj_debug_dumpstack(L, 0, 30, base, full)
else:
out("No Lua code running.\n")
return
lbt()
class lvmst(gdb.Command):
"""This command prints out the current LuaJIT VM state in the lua_State specified.
Usage: lvmst [L]"""
def __init__ (self):
super (lvmst, self).__init__("lvmst", gdb.COMMAND_USER)
def invoke (self, args, from_tty):
argv = gdb.string_to_argv(args)
if len(argv) > 1:
raise gdb.GdbError("Usage: lvmst [L]")
if len(argv) == 1:
L = gdbutils.parse_ptr(argv[0], "lua_State*")
if not L or str(L) == "void":
raise gdb.GdbError("L empty")
else:
L = get_cur_L()
#print "g: ", hex(int(L['glref']['ptr32']))
g = G(L)
vmstate = int(g['vmstate'])
if vmstate >= 0:
out("Compiled Lua code (trace #%d)\n" % vmstate)
elif ~vmstate >= LJ_VMST__MAX:
raise gdb.GdbError("Invalid VM state: ", ~vmstate)
elif ~vmstate == LJ_VMST_GC:
out("current VM state: Garbage collector (")
if tvref(g['jit_base']):
out("from compiled Lua code)\n")
else:
out("from interpreter)\n")
else:
#print "vmstate = %d" % vmstate
out("current VM state: %s\n" % vmstates[~vmstate])
lvmst()
class lmainL(gdb.Command):
"""This command prints out the main Lua thread's state
Usage: lmainL"""
def __init__ (self):
super (lmainL, self).__init__("lmainL", gdb.COMMAND_USER)
def invoke (self, args, from_tty):
argv = gdb.string_to_argv(args)
if len(argv) != 0:
raise gdb.GdbError("Usage: lmainL")
L = get_global_L()
out("(lua_State*)0x%x\n" % ptr2int(L))
lmainL()
class lcurL(gdb.Command):
"""This command prints out the current running Lua thread's state
Usage: lcurL"""
def __init__ (self):
super (lcurL, self).__init__("lcurL", gdb.COMMAND_USER)
def invoke (self, args, from_tty):
argv = gdb.string_to_argv(args)
if len(argv) != 0:
raise gdb.GdbError("Usage: lcurL")
L = get_cur_L()
out("(lua_State*)0x%x\n" % ptr2int(L))
lcurL()
class lglobtab(gdb.Command):
"""This command prints out the global environment table.
Usage: lglobtab [L]"""
def __init__ (self):
super (lglobtab, self).__init__("lglobtab", gdb.COMMAND_USER)
def invoke (self, args, from_tty):
argv = gdb.string_to_argv(args)
if len(argv) > 1:
raise gdb.GdbError("Usage: lglobtab [L]")
if len(argv) == 1:
L = gdbutils.parse_ptr(argv[0], "lua_State*")
if not L or str(L) == "void":
raise gdb.GdbError("L empty")
else:
L = get_cur_L()
#print "g: ", hex(int(L['glref']['ptr32']))
out("(GCtab*)0x%x\n" % ptr2int(tabref(L['env'])))
lglobtab()
def noderef(r):
return mref(r, "Node")
def itype(o):
return o['it']
def tvisnil(o):
return itype(o) == LJ_TNIL()
def tvisfunc(o):
return itype(o) == LJ_TFUNC()
def tvistrue(o):
return itype(o) == LJ_TTRUE()
def tvisfalse(o):
return itype(o) == LJ_TFALSE()
def tvisstr(o):
return itype(o) == LJ_TSTR()
def tvisnumber(o):
return itype(o) <= LJ_TISNUM()
def tvisgcv(o):
return (itype(o) - LJ_TISGCV()) > (LJ_TNUMX() - LJ_TISGCV())
def tvisint(o):
return itype(o) == LJ_TISNUM()
def strV(o):
return gcval(o)['str'].address
def lstr2str(gcs):
kstr = strdata(gcs)
if not kstr:
return ""
return kstr.string('iso-8859-6', 'ignore', int(gcs['len']))
def lj_tab_getstr(t, k):
klen = len(k)
hmask = int(t['hmask'])
node = noderef(t['node'])
for i in xrange(hmask + 1):
nn = node[i]
val = nn['val'].address
if not tvisnil(val):
key = nn['key'].address
if tvisstr(key):
gcs = strV(key)
#print "Found a string key with len %d" % int(gcs['len'])
if gcs['len'] == klen:
s = lstr2str(gcs)
if s == k:
return val
return None
class ltabgets(gdb.Command):
"""This command prints out the specified field in the specified Lua table
Usage: ltabgets tab field"""
def __init__ (self):
super (ltabgets, self).__init__("ltabgets", gdb.COMMAND_USER)
def invoke (self, args, from_tty):
argv = gdb.string_to_argv(args)
if len(argv) != 2:
raise gdb.GdbError("Usage: ltabgets tab field")
m = re.match('0x[0-9a-fA-F]+', argv[0])
if m:
val = gdb.Value(int(argv[0], 16)).cast(typ("TValue*"))
else:
val = gdb.parse_and_eval(argv[0])
if not val:
raise gdb.GdbError("table argument empty")
return
typstr = str(val.type)
if typstr == "GCtab *":
tab = val
else:
tab = tabV(val)
key = argv[1]
tv = lj_tab_getstr(tab, key)
if tv:
out("(TValue*)%#x\n" % ptr2int(tv))
dump_tvalue(tv)
else:
raise gdb.GdbError("Key \"%s\" not found." % key)
#print "g: ", hex(int(L['glref']['ptr32']))
ltabgets()
def ltype(tv, t=None):
if not t:
t = tv['it']
#print "t = %d, lightud: %d" % (t, LJ_TLIGHTUD())
if t == LJ_TNIL():
return "nil"
if t == LJ_TSTR():
return "string"
if t == LJ_TFALSE():
return "false"
if t == LJ_TTRUE():
return "true"
if t == LJ_TLIGHTUD():
return "lightuserdata"
if t == LJ_TTHREAD():
return "thread"
if t == LJ_TUPVAL():
return "upvalue"
if t == LJ_TPROTO():
return "proto"
if t == LJ_TFUNC():
return "function"
if t == LJ_TTRACE():
return "trace"
if t == LJ_TCDATA():
return "cdata"
if t == LJ_TTAB():
return "table"
if t == LJ_TUDATA():
return "userdata"
if t == LJ_TNUMX():
return "number"
if t.cast(typ("int32_t")) >> 15 == -2:
return "lightuserdata"
return "number"
def tvisudata(o):
return itype(o) == LJ_TUDATA()
def udataV(o):
return gcval(o)['ud'].address
UDTYPE_USERDATA = 0
UDTYPE_IO_FILE = 1
UDTYPE_FFI_CLIB = 2
UDTYPE__MAX = 3
udata_types = ['userdata', 'io file', 'ffi clib']
def uddata(u):
return (u + 1).cast(typ("void*"))
def tviscdata(o):
return itype(o) == LJ_TCDATA()
def ctype_ctsG(g):
return mref(g['ctype_state'], 'CTState')
def ctype_cts(L):
return ctype_ctsG(G(L))
def cdataV(o):
return gcval(o)['cd'].address
def ctype_get(cts, id):
return cts['tab'][id].address
CTSHIFT_NUM = 28
CT_HASSIZE = 5
CT_ATTRIB = 8
CTMASK_CID = 0x0000ffff
def ctype_type(info):
return info >> CTSHIFT_NUM
ctype_names = [ 'num', 'struct', 'ptr', 'array', \
'void', 'enum', 'func', 'typedef', 'attribute', 'field', \
'bitfield', 'constant value', 'extern', 'keyworkd']
def cdataptr(cd):
return (cd + 1).cast(typ("void*"))
def tvislightud(o):
t = itype(o)
if t == LJ_TLIGHTUD():
return True
if t.cast(typ("int32_t")) >> 15 == -2:
return True
return False
def intV(o):
return o['i'].cast(typ("int32_t"))
def noderef(r):
return mref(r, "Node")
def dump_table(t):
narr = int(t['asize'])
nhmask = int(t['hmask'])
out("table (GCtab*)%#x (narr=%d, nrec=%d):\n" % (ptr2int(t), narr, nhmask))
arr = tvref(t['array'])
for i in xrange(narr):
v = arr[i].address
if not tvisnil(v):
out("\t[%d] =\n" % i)
dump_tvalue(v)
node = noderef(t['node'])
for i in xrange(nhmask+1):
nn = node[i]
k = nn['key']
v = nn['val'].address
if not tvisnil(v):
out("\tkey:\n")
dump_tvalue(k)
out("\tvalue:\n")
dump_tvalue(v)
def dump_udata(ud, data=False):
t = ud['udtype']
out("\t\tudata type: %s\n" % udata_types[int(t)])
out("\t\t payload len: %d\n" % int(ud['len']))
out("\t\t payload ptr: 0x%x\n" % ptr2int(ud + 1))
if int(t) == UDTYPE_FFI_CLIB:
cl = uddata(ud).cast(typ("CLibrary*"))
out("\t\t CLibrary handle: (void*)0x%x\n" % \
ptr2int(cl['handle']))
out("\t\t CLibrary cache: (GCtab*)0x%x\n" \
% ptr2int(cl['cache']))
if data and int(t) == UDTYPE_USERDATA:
len = int(ud['len'])
p = uddata(ud).cast(typ("char *"))
printlen = min(len, 48)
out("\t\t payload header: \"")
for i in range(printlen):
#if i in range(32, 126):
c = p[i]
if c >= 32 and c <= 126 : #in range(32, 126):
out("%c" % c)
else:
out(".")
if printlen < len:
out(" ...")
out("\"\n")
def dump_tvalue(o, deep=False):
if tvisudata(o):
dump_udata(udataV(o))
elif tvisstr(o):
gcs = strV(o)
try:
out("\t\tstring: \"%s\" (len %d)\n" % (lstr2str(gcs), \
int(gcs['len'])))
except:
pass
elif tviscdata(o):
mL = get_global_L()
cts = ctype_cts(mL)
cd = cdataV(o)
ptr = cdataptr(cd)
out("\t\ttype cdata\n")
out("\t\t\tcdata object: (GCcdata*)0x%x\n" % ptr2int(cd))
out("\t\t\tcdata value pointer: (void*)0x%x\n" % ptr2int(ptr))
d = ctype_get(cts, cd['ctypeid'])
out("\t\t\tctype object: (CType*)0x%x\n" % ptr2int(d))
out("\t\t\tctype size: %d byte(s)\n" % int(d['size']))
t = int(ctype_type(d['info']))
#print "ctype type %d\n" % t
if ctype_names[t]:
out("\t\t\tctype type: %s\n" % ctype_names[t])
else:
err("\t\t\tunknown ctype type: %d\n" % t)
s = strref(d['name'])
if s:
out("\t\t\t\tctype element name: %s\n" % lstr2str(s))
elif tvislightud(o):
out("\t\tlight user data: (void*)0x%x\n" % ptr2int(gcrefp(o['gcr'], 'void')))
return
elif tvisint(o):
out("\t\tint %d\n" % int(intV(o)))
elif tvisnumber(o):
out("\t\tnumber %.14g\n" % float(o['n']))
elif tvisnil(o):
out("\t\tnil\n")
elif tvistrue(o):
out("\t\ttrue\n")