-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprd_multidecomp_ida.py
More file actions
3422 lines (2942 loc) · 151 KB
/
prd_multidecomp_ida.py
File metadata and controls
3422 lines (2942 loc) · 151 KB
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 os
import subprocess
import IPython
import argparse
import tempfile
import re
import shutil
import time
import random
import copy
import pickle
# path to idat binary
IDA_DEFAULT_PATH=os.environ['HOME']+"/seclab_ida/ida/idat"
if os.environ['IDA_BASE_DIR']:
IDA_PATH=os.environ['IDA_BASE_DIR']+"/idat"
else:
IDA_PATH=IDA_DEFAULT_PATH
# path to defs.h
DEFS_PATH=os.path.dirname(os.path.realpath(__file__))+"/refs/defs.h"
# sometimes localization tools use stdio, so let's make sure that if any symbol from this library gets remapped to avoid collision
CSTDIO_FUNCS=[
'clearerr', 'fclose', 'fdopen', 'feof', 'ferror', 'fflush', 'fgetc', 'fgetpos', 'fgets',
'fileno', 'fopen', 'fprintf', 'fpurge', 'fputc', 'fputs', 'fread', 'freopen', 'fscanf', 'fseek',
'fsetpos', 'ftell', 'fwrite', 'getc', 'getchar', 'gets', 'getw', 'mktemp', 'perror', 'printf',
'putc', 'putchar', 'puts', 'putw', 'remove', 'rewind', 'scanf', 'setbuf', 'setbuffer', 'setlinebuf',
'setvbuf', 'sprintf', 'sscanf', 'strerror', 'sys_errlist', 'sys_nerr', 'tempnam', 'tmpfile', 'tmpnam',
'ungetc', 'vfprintf', 'vfscanf', 'vprintf', 'vscanf', 'vsprintf', 'vsscanf'
]
CSTDIO_DATASYMS=[
'stderr','stdout','stdin'
]
VALIST_FUNCS=[
'printf','fprintf','sprintf','scanf','sscanf','fscanf'
]
VALIST_TRANSFORM={x:f"v{x}" for x in VALIST_FUNCS}
GLIBC_XFORM_PREFIX="x__"
STUB_PREFIX="z__"
# not sure if all these are problematic types
# these are types that included with "stdio.h"=>types.h
CHDR_TYPES=[
'gid_t', 'uid_t', 'pid_t',
'id_t', 'blkcnt_t', 'blksize_t', 'caddr_t', 'clock_t',
'clockid_t', 'daddr_t', 'fsblkcnt_t', 'fsfilcnt_t', 'mode_t',
'key_t', 'ino_t', 'nlink_t',
'timer_t', 'suseconds_t', 'useconds_t', 'dev_t',
'time_t', 'off_t', 'loff_t', 'off64_t', 'socklen_t', '__va_list', 'ssize_t',
'uint_t', 'uint', 'u_char', 'u_short', 'u_int', 'u_long', 'u_int32_t', 'u_int16_t',
'u_int8_t', 'u_int64_t', 'ptrdiff_t', 'size_t', 'wchar_t', 'mode_t'
]
# '__mode_t', '__ino_t', '__key_t', '__nlink_t', '__timer_t', '__suseconds_t', '__useconds_t', '__clockid_t',
#'__gid_t', '__uid_t', '__pid_t', '__id_t',
TYPES_REQUIRING_STDIO=['FILE']
DIETLIBC_TYPES=[
'uint32_t','int32_t','uint8_t','int8_t','uint16_t','int16_t','bool'
]
STD_HEADER_TYPES=TYPES_REQUIRING_STDIO+CHDR_TYPES+DIETLIBC_TYPES
"""
# i know these are problematic types
CHDR_TYPES=[
'time_t', 'off_t', 'mode_t'
]
"""
CHECK_DEF_start="#if (!defined(_SYS_TYPES_H) && !defined(_STDDEF_H)) \n"+\
"#define DONT_USE_LOCAL\n#endif\n"
_DEF_start="#ifndef DONT_USE_LOCAL"
_DEF_end="#endif"
# stub markers for processing
IDA_STUB_START = "// Function declarations"
IDA_DATA_START = "// Data declarations"
IDA_DECOMP_START = "//----- ("
IDA_SECTION_END = "//-----"
IDA_WEAK_LABEL = "; weak"
IDA_FUNC_WEAK_LABEL = "// weak"
TYPEDEF_START = "============================== START =============================="
TYPEDEF_END = "============================== END =============================="
# tags for primitives for replacement
DEBUG=False
def dprint(*args,**kwargs):
if DEBUG:
print(*args,**kwargs)
def get_primitives():
basic_types=["float","double","long double","void"]
basic_bintypes=["int","char","short","short int","long","long long","long int"]
for x in basic_bintypes:
basic_types.extend([f"{a}{x}" for a in ["", "unsigned ", "signed "]])
return basic_types
PRIMITIVES = get_primitives()
#["int", "long", "short", "char", "void", "double", "float", "long",
# "unsigned int", "unsigned long", "unsigned short", "unsigned char", "void", "long double"]
SYSTEM_TYPES=PRIMITIVES+STD_HEADER_TYPES
def get_array_size(x):
return len(re.findall("\[\d*\]",x))
def get_basetype_info(field):
# maybe this is a function prototype where there's only the type for each param
# making this the default
xtype=field.strip()
# else, let's split on spaces as long as it's not the pointer corner case for function prototype
if ':' in xtype:
x=xtype.rsplit(':',1)[0].strip()
xtype=x
xtype=re.sub(r"\b(volatile|const)\b","",xtype).strip()
ptr=xtype.endswith(' *')
postfix=""
if ptr:
x=xtype.rsplit(' ',1)
xtype,postfix=x[0],x[1]
if ((xtype not in PRIMITIVES) and (' ' in xtype)):
x=xtype.rsplit(' ',1)
xtype=x[0].strip()
xname=x[1].strip()
return xtype+postfix
def cleanup_basetype(ptyp):
ptyp_=ptyp.strip()
while ptyp_.endswith('*') or ptyp_.endswith('('):
ptyp_=ptyp_[:-1].rstrip()
if ptyp_.startswith('const '):
ptyp_=ptyp_[len('const '):]
elif ptyp_.startswith('struct '):
ptyp_=ptyp_[len('struct '):]
elif ptyp_.startswith('union '):
ptyp_=ptyp_[len('union '):]
return ptyp_.strip()
def update_dependencies(orig_set:set,new_set:set):
x=orig_set | new_set
new_dependencies=False if x == orig_set else True
return new_dependencies, x
def writepickle(pkl_file,data):
if not os.path.exists(os.path.dirname(pkl_file)):
os.makedirs(os.path.dirname(pkl_file))
f=open(pkl_file,'wb')
if data is not None:
pickle.dump(data,f)
f.close()
def readpickle(pkl_file):
f=open(pkl_file,'rb')
return pickle.load(f)
def get_function_name(line):
x=line.split(";")[0].split("(")[0].strip().rsplit()[-1]
while x.startswith("*"):
x=x[1:]
return x
def is_function_ptr(line):
#x=re.match("\s*\*?(\((\s*\*)+\s*\w+\)|\w+)\((.*)\)",line)
# return type (*fn_name) fn_name (params) params
# 1 3 4 5 6
line=line.strip()
x=re.match("(\S+(\s+[^(]+)*\s*\**)\s*(\(\*\s*([^(]+)\))\s*(\((.*)\))$",line)
is_fnptr=False
rettype,fnptr_name,params,fn_no_params=(None,None,None,None)
if x:
is_fnptr=True
rettype=x.group(1)
fnptr_name=x.group(4)
params=x.group(6)
fn_no_params=f"{x.group(1)} {x.group(3)}"
else:
# return type *fn fn fn_p
# 1 3 4 5
y=re.match("(\S+(\s+[^(]+)*\s*\**)\s*(\(\*\s*\(\*\s*([^()]+)\)(.*)\)\))\s*(\((void)\))$",line)
if y:
is_fnptr=True
rettype=y.group(1)
fnptr_name=y.group(4)
params=y.group(5)
fn_no_params=f"{y.group(1)} {y.group(3)}"
return is_fnptr,rettype,fnptr_name,params,fn_no_params
def strip_binary(binary,out=None):
import subprocess
b_out=out
if not out:
b_out=f"{binary}.strip"
x=subprocess.run(f"cp {binary} {b_out}",shell=True)
if x.returncode!=0:
print(f"[WARNING!] Failed to create {b_out} from binary source.\nSkipping stripping of symbols")
b_out=binary
else:
x=subprocess.run(f"/usr/bin/strip --strip-all {b_out}",shell=True)
if x.returncode!=0:
print(f"[WARNING!] Failed to strip symbols from {b_out}!")
print(f"Reverting to original binary")
b_out=binary
return b_out
class IDAWrapper:
def __init__(self, typedefScriptPath):
self.typedefScriptPath = typedefScriptPath
# get initial decompiled output of ida hexrays
def decompile_func(self, binary_path, func:str, decompdir:str):
outname = "/tmp/"+func.strip()+f"{int(random.getrandbits(16))}"
decompf=f"{decompdir}/{func.strip()}.c"
#for func_name in func_list:
# funcs += func_name.strip() + ":"
#funcs = funcs[:-1] #trim dangling ':'
# ida run command
functionLines = ""
if not os.path.exists(decompf) or (os.stat(decompf).st_size==0):
ida_command = [IDA_PATH, "-Ohexrays:-nosave:"+outname+":"+func, "-A", binary_path]
print("Running: ", " ".join(ida_command),flush=True)
subprocess.run(ida_command)
if not os.path.exists(outname+".c"):
print(" !!! ERROR DECOMPILING FILE", outname+".c")
return ""
with open(f"{outname}.c", "r") as decompFile:
functionLines = decompFile.read()
decompFile.close()
shutil.copyfile(f"{outname}.c",decompf)
os.remove(f"{outname}.c")
print("[COMPLETED] Running: ", " ".join(ida_command))
else:
with open(decompf, "r") as decompFile:
functionLines = decompFile.read()
decompFile.close()
return functionLines
# get initial decompiled output of ida hexrays
def decompile(self, binary_path, func_list:list):
if len(func_list) <= 0:
print("Empty List of Functions!!")
return ""
outname = "/tmp/"+func_list[0].strip()
funcs = ""
for func_name in func_list:
funcs += func_name.strip() + ":"
funcs = funcs[:-1] #trim dangling ':'
# ida run command
ida_command = [IDA_PATH, "-Ohexrays:-nosave:"+outname+":"+funcs, "-A", binary_path]
print("Running: ", " ".join(ida_command))
subprocess.run(ida_command)
functionLines = ""
if not os.path.exists(outname+".c"):
print(" !!! ERROR DECOMPILING FILE", outname+".c")
return ""
with open(outname+".c", "r") as decompFile:
functionLines = decompFile.read()
decompFile.close()
os.remove(outname+".c")
return functionLines
# # given a decompiled ida string, find all func calls in that string
# get all typedef mappings
def get_typedef_mappings(self, binary_path,output,use_new_features=False):
typedefMap = dict()
typedef_f=f"{output}/typedefs.h"
typedefs=None
if not os.path.exists(typedef_f) or (os.stat(typedef_f).st_size==0):
ida_command = [IDA_PATH, '-B', '-S'+"\""+self.typedefScriptPath+"\"", "-A", binary_path]
tmpName = ""
# getting rid of tempfile since I'm saving the original typedef info to a file anyway
#with tempfile.NamedTemporaryFile(mode="r", dir="/tmp", prefix="prd-ida-",delete=True) as tmpFile:
with open(typedef_f,"w") as tmpFile:
print("RUNNING: ", " ".join(ida_command),flush=True)
env = os.environ
env['IDALOG'] = os.path.realpath(typedef_f)
sp = subprocess.run(ida_command, env=env)
tmpFile.close()
with open(typedef_f,"r") as tmpFile:
typedefs = tmpFile.read()
tmpFile.close()
structDump = ""
latch = False
for line in typedefs.splitlines():
if TYPEDEF_START in line:
latch = True
elif TYPEDEF_END in line:
latch = False
elif latch:
if "/*" in line and "*/" in line:
structDump += "\n"
continue
if line.startswith("#define") and use_new_features:
structDump += "\n"
structDump += line
print("FINISHED RUNNING",flush=True)
return structDump
class CodeCleaner:
def __init__(self):
self.weakFuncs = []
def getTypeAndLabel(self, header, fn_ptr=False):
array,hType,hLabel=(None,None,None)
if ")" in header and "((aligned(" not in header and "()" not in header and not fn_ptr:
array = header.rsplit(")", maxsplit=1)
hType = array[0].strip()+")"
elif fn_ptr:
hType = "void *"
func_ptr_name=re.match("(\w+\s+)+\(\s*\*+\s*(\w+)\)",header)
if func_ptr_name:
dprint("DEBUG : getTypeAndLabel {} => {}".format(header,func_ptr_name.group(2)))
return hType,func_ptr_name.group(2)
func_ptr_name=re.match("(\w+\s+)+\*\s*\(\s*\*+\s*(\w+)\)",header)
if func_ptr_name:
dprint("DEBUG : getTypeAndLabel {} => {}".format(header,func_ptr_name.group(2)))
return hType,func_ptr_name.group(2)
else:
dprint("FAILURE : getTypeAndLabel {} ".format(header))
assert(False)
else:
array = header.rsplit(maxsplit=1)
hType = array[0].strip()
if len(array) > 1:
hLabel = array[1].strip()
else:
hLabel = ""
hLabel = hLabel.strip("()")
while hLabel.startswith("*"):
hType = hType + " *"
hLabel = hLabel[1:]
if "__stdcall" in hType:
hType = hType.replace("__stdcall", "")
hLabel = hLabel.strip(";")
return hType, hLabel
def is_basic_typedef(self, line):
if not line.startswith("typedef"):
return False
if line.startswith("typedef struct"):
return False
if line.startswith("typedef union"):
return False
if "(" in line or "{" in line:
return False
return True
def get_type_label(self,argTypeRaw):
argType = self.get_typebase(argTypeRaw)
argTypeArray = argType.strip().rsplit(maxsplit=1)
if len(argTypeArray) > 1:
argTypeLabel = argTypeArray[-1]
else:
argTypeLabel = argTypeArray[0]
return argTypeLabel
def check_func_prototype(self,input_):
return re.match("((struct\s+)?\w+)\s+\*?(\((\s*\*)+\s*\w+\)|\w+)\((.*)\)",input_)
def is_function_prototype(self,argType):
func=self.check_func_prototype(argType)
types=[]
ret=False
if func:
dprint("Function: "+argType)
types.append(self.get_type_label(func.group(1)))
x=re.split(r',',func.group(4))
for t in x:
types.append(self.get_type_label(t))
ret=True
return ret,types
def get_typebase(self, argType):
argType = argType.strip()
while argType.endswith("*") or argType.startswith("*"):
argType= argType.strip("*")
argType = argType.strip()
return argType
def get_struct_args(self, argString):
argString = argString.strip()
args = argString.split(";")
argList = []
for arg in args:
arg = arg.split(":")[0]
arg = arg.strip()
if arg:
argType, argName = self.getTypeAndLabel(arg)
argList.append((argType, argName, arg))
return argList
# seperate each ordinal, filter out cases, establish bindings
def typedef_firstpass(self, structDump):
dprint(" > RUNNING FIRSTPASS")
lineDump = ""
for line in structDump.splitlines():
if "{" not in line and "}" not in line:
if line.count(";") > 1:
line = line.strip()
line = line.replace(";", ";\n")
lineDump += line+"\n"
return lineDump
def typedef_remove_errata(self,structDump):
lineDump=""
for line in structDump.splitlines():
if "Elf" in line:
continue #skip
elif line.startswith("decls:"):
continue
elif len(line.strip())==0:
continue
lineDump += line+"\n"
return lineDump
def typedef_secondpass(self, structDump):
dprint(" > RUNNING SECOND PASS")
lineDump = ""
typedefMap = {}
structMap = {}
substituteMap = {}
for line in structDump.splitlines():
if "Elf" in line:
continue #skip
if line.startswith("typedef"):
elements = line.strip()[8:] #strip typedef + space
array = elements.split("(", maxsplit=1)
orig = ""
if len(array) > 1:
orig = array[0].strip()
newVal = "("+array[1].strip().strip(";")
else:
array = array[0].rsplit(maxsplit=1)
orig = array[0].strip()
newVal = array[1].strip().strip(";")
dprint(" << read line ", line)
typedefMap[orig] = (newVal, line)
elif line.startswith("struct ") or line.startswith("union "):
elements = line.strip().split(maxsplit=1)
header = elements[0].strip()
array = elements[1].split("{", maxsplit=1)
structDec = header+" "+array[0].strip()
structName = structDec.rsplit(maxsplit=1)[1]
dprint(" << read struct [%s] == %s" % (structName, structDec))
structMap[structName] = structDec
if structDec not in typedefMap.keys():
typedefMap[structDec] = (structName, line)
for line in structDump.splitlines():
if "Elf" in line:
continue #skip
if line.strip():
dprint(" !! Processing line ", line)
done = set()
for origName, typedefTuple in typedefMap.items():
if not line.startswith("typedef "+origName) and \
("{" in line or "(" in line): # found struct defines
# substitute typedefs with their original value
# this is so we can move the struct to before the typedefs themselves
if "{" in line:
argLine = "{"+line.split("{", maxsplit=1)[1]
else:
argLine = "("+line.split("(", maxsplit=1)[1]
newVal = typedefTuple[0]
dprint(" - Check for use of %s, originally [%s]" % (newVal, origName))
typedefLine = typedefTuple[1]
escapedNewVal = re.escape(newVal)
matches = re.findall("[\\(\\{\\)\\}\\;\\,][\s]*"+escapedNewVal+"[\\(\\{\\)\\}\\;\\,\s]+", argLine)
for match in matches:
if origName in structMap.keys():
origName = structMap[origName]
if origName not in done:
newLine = match.replace(newVal, origName)
line = line.replace(match, newLine)
if matches:
dprint(" Associating %s with %s" % (typedefLine, line))
done.add(origName)
# substituteMap[typedefLine] = line
# break
lineDump += line+"\n"
return lineDump
def typedef_lastpass(self, structDump):
definitions = ""
for line in structDump.splitlines():
defLine = ""
if line.startswith("typedef"):
defLine = line
elif line.startswith("union"):
array = line.split("{")
name = array[0].split()[1].strip()
elems = array[1].strip().strip(";")
defLine = "typedef " + array[0] + "{" + elems + " " + name + ";\n"
elif line.startswith("enum"):
array = line.split("{")
header = array[0].split(":")[0].strip()
name = header.split()[1].strip()
enums = array[1]
enumLine = header + "{" + enums
typeDefLine = "typedef " + header + " " + name + ";"
defLine = enumLine + "\n" + typeDefLine
elif line.startswith("struct"):
line = line.strip(";") # prune out ending semicolon
header = line.split("{")[0].strip()
typeName = header.rsplit(maxsplit=1)[1].strip() # get name, drop struct prefixes
matches = re.findall("[\\(\\{\\;][\s]*"+typeName+" ", line)
for match in matches:
newLine = match.replace(typeName, header)
line = line.replace(match, newLine)
defLine = "typedef "+line+" "+typeName+";"
definitions += defLine+"\n"
return definitions
def process_one_defline(self, definitions, line, waitingStructs, defined, forward_declared, typeDefMap):
dprint(" CHECKING: ", line)
rearranged = False
resolved = True
defline = line.strip(";") # prune out ending semicolon
# get rid of attributes, we don't care
defline,num = re.subn(r"__attribute__\(\(\w+(\(\w+\))?\)\)",r"",defline)
argString = ""
typedef_decl=False
if "{" in line or "(" in line:
array = defline.split("{")
header = array[0].strip()
f = header.rsplit(maxsplit=1)
struct_or_union = f[0].strip() # get struct_or_union
typeName = f[1].strip() # get name, drop struct prefixes
if line.startswith("typedef struct") or line.startswith("typedef union") :
body = array[1].strip()
argString = body.split("}")[0]
typedef_decl=True
else:
array = defline.split(")", maxsplit=1)
header = array[0].split("(")[1].strip()
typeName = header
body = array[1].strip()
args = body.split(")", maxsplit=1)[0].strip().strip("(")
argsArray = args.split(",")
argsArray.append("")
argString = " dummy;".join(argsArray)
elif line.startswith("typedef "):
array = defline.rsplit(maxsplit=1)
header = array[0]
simpleType = header.split(maxsplit=1)[1] #trim typedef
argString = simpleType+" dummy" # add dummy
typeName = array[1]
typeDefMap[self.get_typebase(typeName)] = simpleType
typeName = self.get_typebase(typeName)
if typeName in defined:
dprint(" - Already Processed!")
return definitions, rearranged
if argString:
args = self.get_struct_args(argString)
for argTypeRaw, argName, argOrig in args:
isfunc,type_labels = self.is_function_prototype(argTypeRaw)
if not isfunc:
argType = self.get_typebase(argTypeRaw)
argTypeArray = argType.strip().rsplit(maxsplit=1)
if len(argTypeArray) > 1:
type_labels = [ argTypeArray[-1] ]
else:
type_labels = [ argTypeArray[0] ]
for argTypeLabel in type_labels:
if argTypeLabel == typeName:
continue # skip self references
if argTypeLabel not in PRIMITIVES and argTypeLabel not in defined:
if not(argTypeLabel in forward_declared and \
(not self.is_basic_typedef(line))): # move non-struct non-union typedefs
if argTypeLabel not in waitingStructs.keys():
waitingStructs[argTypeLabel] = []
waitingStructs[argTypeLabel].append((line, argTypeLabel, argTypeRaw))
rearranged = True
resolved = False
dprint(" --> unresolved type", argTypeLabel)
dprint(" ", forward_declared, (argTypeLabel in forward_declared))
dprint(" %s || %s" % (line, argTypeRaw))
# dprint(" defined: ", defined)
if resolved:
dprint(" !! DEFINED", typeName)
defined.append(typeName)
definitions += line+"\n"
if typeName in waitingStructs.keys():
dprint(" !--> RESOLVING: ", typeName)
lines = waitingStructs[typeName]
waitingStructs.pop(typeName)
for line, argTypeLabel, argTypeRaw in lines:
dprint(" - Recursive process", typeName)
definitions, child_rearranged = self.process_one_defline(definitions, line, waitingStructs, defined, forward_declared, typeDefMap)
if not resolved or child_rearranged:
rearranged = True
dprint(" - RESOLVED!", typeName)
else:
rearranged = True
return definitions, rearranged
def recursive_dep_check(self, typeDefMap, waitingStructs, key):
if key in waitingStructs.keys():
return True
elif key in typeDefMap.keys():
newKey = typeDefMap[key]
dprint(" ## Recursing", key, "->", newKey)
return self.recursive_dep_check(typeDefMap, waitingStructs, newKey)
return False
def resolve_defs(self, structDump):
definitions = ""
defined= []
forward_declared = []
waitingStructs = {}
typeDefMap = {}
rearranged = False
for line in structDump.splitlines():
if line.startswith("typedef"):
definitions, child_rearranged = self.process_one_defline(definitions, line, waitingStructs, defined, forward_declared, typeDefMap)
if child_rearranged:
rearranged = True
elif line.startswith("struct"):
# forward declaration
typeName = line.strip().strip(";").rsplit(maxsplit=1)[1];
dprint(" !! FORWARD DECLARATION - STRUCT", typeName)
definitions += "struct "+typeName+";\n"
forward_declared.append(typeName)
elif line.startswith("union"):
# forward declaration
typeName = line.strip().strip(";").rsplit(maxsplit=1)[1];
dprint(" !! FORWARD DECLARATION - UNION", typeName)
forward_declared.append(typeName)
definitions += "union "+typeName+";\n"
else:
definitions += line+"\n"
remainingLines = []
potentialPlaceholders = set()
rejectedPlaceholders = set()
for needed, lines in waitingStructs.items():
for line, argTypeLabel, argTypeRaw in lines:
if line not in remainingLines:
remainingLines.append(line)
if not self.is_basic_typedef(line):
array = line.split("{")
header = array[0].strip()
f=header.rsplit(maxsplit=1) # get name, drop struct prefixes
struct_or_union = f[0].strip() # get name, drop struct prefixes
typeName = f[1].strip() # get name, drop struct prefixes
dprint("EVALUTING [%s] as Placeholder!" % typeName)
dprint(" ==", argTypeRaw)
dprint(" == ", (self.recursive_dep_check(typeDefMap, waitingStructs, typeName)))
dprint(" ==", (typeName not in rejectedPlaceholders))
if self.recursive_dep_check(typeDefMap, waitingStructs, typeName) and typeName not in rejectedPlaceholders:
if "union" in struct_or_union:
potentialPlaceholders.add("union "+typeName)
else:
potentialPlaceholders.add(typeName)
# if any of the waitingStructs use the needed placeholder without a pointer, reject this placeholder
if "*" not in argTypeRaw:
dprint("removing ", argTypeLabel, "as placeholder. argTypeLabel", argTypeLabel)
dprint(" line: ", line)
if argTypeLabel in potentialPlaceholders:
potentialPlaceholders.remove(argTypeLabel)
rejectedPlaceholders.add(argTypeLabel)
for placeholder in potentialPlaceholders:
# create placeholder forward declaration
if placeholder not in forward_declared:
if "union" in placeholder:
dprint("Adding Placeholder ", placeholder)
definitions += placeholder+";\n"
else:
dprint("Adding Placeholder Struct ", placeholder)
definitions += "struct "+placeholder+";\n"
for line in remainingLines:
definitions += line+"\n"
rearranged = True
return definitions, rearranged
def rearrange_typedefs(self, structDump):
MAXTRIES = len(structDump.splitlines())
rearranged = True
definitions = structDump
tries = 0
while tries < MAXTRIES and rearranged:
passCount = " Reordering typedefs [Pass %d] " % (tries+1)
print(("-"*5) + passCount + ("-"*5))
definitions, rearranged = self.resolve_defs(definitions)
tries += 1
print(("-"*10) + " Rearranged: " + str(rearranged) + " " + ("-"*10))
if tries >= MAXTRIES:
print(" !! ERROR !! Unable to resolve typedef order")
return definitions
def resolve_type_order(self, structDump,output):
typedef_f=f"{output}/resolved-typedefs.h"
rectype_f=f"{output}/recovered-types.txt"
recovered_types=None
needs_stdio=False
if os.path.exists(typedef_f):
with open(typedef_f,'r') as typedefh:
structDump=typedefh.read()
typedefh.close()
with open(rectype_f,'r') as rtypefh:
r=[x.strip() for x in rtypefh.readlines()]
needs_stdio=True if r[0]=="True" else False
recovered_types=r[1:]
rtypefh.close()
else:
structDump = self.typedef_firstpass(structDump)
structDump = self.typedef_remove_errata(structDump)
structDump,recovered_types,needs_stdio = self.typedef_resolution(structDump)
with open(typedef_f,"w") as typedfh:
typedfh.write(structDump)
typedfh.close()
with open(rectype_f,"w") as rtypefh:
rtypefh.write(f"{needs_stdio}\n")
rtypefh.write("\n".join(recovered_types))
rtypefh.close()
return structDump,recovered_types,needs_stdio
def update_params_for_typeclass(self,line,forward_decls,enum_decls):
isfnptr,fnrettype,fnptrname,fnptrparams,fnptr_no_params=is_function_ptr(line)
fwddecls_used=list()
enumdecls_used=list()
if isfnptr:
bt=cleanup_basetype(fnrettype)
if forward_decls.get(bt,None) is not None:
fnptr_no_params="struct "+fnptr_no_params
params_=[fnptrparams.strip()]
if ',' in fnptrparams:
params_=fnptrparams.strip().split(',') # parans should have been removed
if len(params_)>0 or not (len(params_)==1 and params_[0].strip()==""):
for i,p in enumerate(params_):
p=p.strip()
bt=get_basetype_info(p)
xt=cleanup_basetype(bt)
xlu=forward_decls.get(xt,None)
xlu_enum=enum_decls.get(xt,None)
if xlu is not None:
if xt not in fwddecls_used:
fwddecls_used.append(xt)
if not p.startswith('const '):
params_[i]=f"struct {p}"
else:
params_[i]=f"const struct {p[len('const '):]}"
elif xlu_enum is not None:
if xt not in enumdecls_used:
enumdecls_used.append(xt)
if not p.startswith('const '):
params_[i]=f"enum {p}"
else:
params_[i]=f"const enum {p[len('const '):]}"
new_params=",".join(params_)
return True,new_params,fnptr_no_params,fwddecls_used,enumdecls_used
return False,None,None,fwddecls_used,enumdecls_used
def typedef_resolution(self,structDump):
type_lines=structDump.splitlines()
DEFINED=set()
# default dict for each defined type/construct
# once all 'reqs' types are defined, then satisfied=True and we can write out the line to file
type_info={
'storage':None,
'defalloc':None,
'deftype':None,
'base_type':None,
'defname':None,
'reqs':None,
'line':None,
}
simple_types=list()
collective_types=list()
fnptr_types=list()
aliased_types=dict()
forward_decls=dict()
enum_decls=dict()
pound_defines=dict()
fwd_decl_types=set()
enum_types=set()
define_later=set()
pnddef=list()
appearance_order=list()
# this maps all types to any dependent declaration
type_to_dependencies=dict()
define_=re.compile(r"^#define\s+(\w+)\s+(.*$)")
fwd_=re.compile(r"^\s*(struct|union)\s+(\S+)\s*;\s*$")
enum_=re.compile(r"^\s*(enum)\s+(\S+)\s*:\s*(\S+)(\{(.*)\})\s*;\s*$")
simple=re.compile(r"^\s*typedef\s+((const\s+|struct\s+|union\s+)?((long\s+|short\s+|unsigned\s+|signed\s+)*\S+)\s+\*?)(\S+.*)\s*;\s*$")
struct_union=re.compile(r"^\s*((struct|union)(\s+__attribute__\(\(.*\)\))?)\s+(\S+)\s*(\{\s*(.*)\s*\}\s*);\s*$")
typ_st_un=re.compile(r"^\s*typedef\s+(struct|union)\s+(\S+)\s*(\{\s*(.*)\s*\}\s*)(\S+)\s*;\s*$")
typ_fnptr=re.compile(r"^\s*typedef\s+((([^(\s]+\s+)+([^(\s]+\s+)*(\*+)?)(\(\s*\*\s*([^(]+)\))\s*(\((.*)\)))\s*;\s*$")
# ORIG: typ_fnptr=re.compile(r"^\s*typedef\s+((\S+(\s+[^(]+)*\s*\**)\s+(\(\s*\*\s*([^(]+)\))\s*(\((.*)\)))\s*;\s*$")
# TESTING:typ_fnptr=re.compile(r"^\s*typedef\s+((\S+(\s+[^(]+)*(\s*\*)*)\s+(\(\s*\*\s*([^(]+)\))\s*(\((.*)\)))\s*;\s*$")
# WORKS: typ_fnptr=re.compile(r"^\s*typedef\s+((\S+(\s+[^(]+)*\s*\**)\s*(\(\s*\*\s*([^(]+)\))\s*(\((.*)\)))\s*;\s*$")
#typedef const sqlite3_io_methods_0 *(*finder_type)(const char *, unixFile_0 *);
#typ_fnptr=re.compile(r"^\s*typedef\s+(((const\s+|unsigned\s+|signed\s+)?(long\s+|short\s+)?(\s+[^(]+)*\s*\**)\s+(\(\s*\*\s*([^(]+)\))\s*(\((.*)\))))\s*;\s*$")
pnddef_re=None
for t in type_lines:
_ltype=None
t=t.strip()
t=re.sub("\s\s"," ",t)
is_define=re.match(define_,t)
if not is_define and pnddef_re:
# if a #define is being used at all, let's substitute it for the actual value before moving on
m=pnddef_re.search(t)
cnt=0
while m:
pval=m.group(1).strip()
newval=re.match(define_,pound_defines[pval]).group(2).strip()
t=re.sub(r"\b"+pval+r"\b",newval,t)
m=pnddef_re.search(t)
cnt+=1
if cnt>0:
dprint(f"!!! UPDATED LINE : {t}",flush=True)
is_forward_decl = re.match(fwd_,t)
# need 1 2 4
is_enum = re.match(enum_,t)
# deftype alias
# GROUP 1 5
is_simple_typedef = simple.match(t)
# stype name fields
# GROUP 2 4 6
is_struct_or_union = re.match(struct_union,t)
# GROUP 1 2 4 5 (name)
is_typedef_struct_or_union = re.match(typ_st_un,t)
# return_type fn_ptr_name params
# GROUP 2 6 9
is_fnptr_typedef = re.match(typ_fnptr,t)
#x=re.match("(\S+(\s+[^(]+)*\s*\**)\s*(\(\*\s*([^(]+)\))\s*(\((.*)\))$",line)
if is_define:
alias=is_define.group(1).strip()
pound_defines[alias]=t
dprint(f"FOUND Early Declaration: '{alias}'")
pnddef.append(alias)
pnddef_re=re.compile(r"\b("+"|".join(pnddef)+r")\b")
#DEFINED.append(alias)
elif is_forward_decl:
#forward_decls.append(t)
ftype=is_forward_decl.group(1).strip()
alias=is_forward_decl.group(2).strip()
forward_decls[alias]={'line':t,'storage':ftype}
fwd_decl_types.add(alias)
dprint(f"FOUND FWD Declaration: '{alias}' <= '{t}")
elif is_enum:
etype=is_enum.group(3).strip()
ename=is_enum.group(2).strip()
eprefix=is_enum.group(1).strip()
efields=is_enum.group(4).strip()
# need 1 2 4
et = f"{eprefix} {ename} {efields};"
if etype in SYSTEM_TYPES or etype in pnddef:
#pnddef.append(ename)
#enum_types.add(ename)
enum_decls[ename]=et
enum_types.add(ename)
dprint(f"FOUND DEFINE: '{ename}'")
else:
dprint(f"ERROR: Can't readily resolve enumeration base type [{etype}]")
dprint(f"Just going to add it anyway")
#pnddef.append(et)
enum_decls[ename]=et
enum_types.add(ename)
elif is_simple_typedef and (is_fnptr_typedef is None):
_ltype=copy.copy(type_info)
base_type=is_simple_typedef.group(1).strip()
alias=is_simple_typedef.group(5).strip()
req_type=cleanup_basetype(base_type).strip()
if req_type=="":
req_type=None
# if any struct or union is inlined with the typedef, capture it
prefixes=['struct ','union ']
inline_def=[base_type.startswith(prefix) for prefix in prefixes]
if any(inline_def):
# ehhh, this is an implementation issue, in other types, struct or unions don't go into something like 'storage', but 'deftype'
# this should really be fixed
idx=inline_def.index(True)
_ltype['storage']=prefixes[idx].strip()
base_type=req_type
elif base_type in enum_types:
t=re.sub(r"\btypedef\b",f"typedef enum",t)
elif base_type in collective_types:
ref_line=type_to_dependencies[base_type]['line']
ref_stor=type_to_dependencies[base_type]['storage']
# we're prepending the type to make sure that 'struct' or 'union' prepends the base type name
if not re.search(r"\b"+ref_stor+r"\b",t):
t=re.sub(r"\btypedef\b",f"typedef {ref_stor}",t)