-
Notifications
You must be signed in to change notification settings - Fork 1
/
structmaker.py
2904 lines (2600 loc) · 110 KB
/
structmaker.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 re, xmltodict
from exectools import make_refresh
refresh_structmaker = make_refresh(os.path.abspath(__file__))
refresh = make_refresh(os.path.abspath(__file__))
###
# HOW TO USE:
# open function in decompiler, set type/name of variable representing struct
# to `__int64 self`. remember to map `v1` or similar as required.
#
# execute `StructMaker(idc.get_screen_ea(), "CStruct")` (replacing CStruct with w/e)
#
# change type/name of variable representing struct to `CStruct* self` and
# repeat previous procedure.
#
# repeat both procedures in other functions to refine the definition.
#
# in case of issues, try decompiling again by pressing F5
###
###
# TODO:
# ~find better way to set struct type, probably by removing following members
# that prevent simply creating a QWORD (it won't let you, if there isn't
# enough room in the struct)~ **done**
#
# treat unaligned QWORD (e.g. at 0x04) as being 2 x DWORD being initialised
# quickly?
#
# ~do something with the undefined gaps that are created when a QWORD is
# shrunk to a smaller type~ **done**
#
# rename matched fields `SetMemberName` to dword_02c or somesuch **huh?**
#
# ~read the decompiled function ourselves~ **done**
#
# ~create the initial struct ourselves~ **done**
###
def line_split(foo): return iter(foo.splitlines())
if '__typedefs' not in globals():
__typedefs = dict()
__typedefs = dict()
__typedefs_h = """
// wierd things seen in snowman
typedef bool int1_t
// stdpokey.h
#define CONST const
#define FAR far
#define NEAR near
#define VOID void
typedef char *PSZ;
typedef BOOL far *LPBOOL;
typedef BOOL near *PBOOL;
typedef BOOLEAN *PBOOLEAN;
typedef BYTE BOOLEAN;
typedef BYTE far *LPBYTE;
typedef BYTE near *PBYTE;
typedef CONST void far *LPCVOID;
typedef DWORD far *LPDWORD;
typedef DWORD near *PDWORD;
typedef FLOAT *PFLOAT;
typedef UCHAR *PUCHAR;
typedef ULONG *PULONG;
typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR;
typedef USHORT *PUSHORT;
typedef WORD far *LPWORD;
typedef WORD near *PWORD;
typedef __PTRDIFF_TYPE__ intptr_t;
typedef __PTRDIFF_TYPE__ ptrdiff_t;
typedef __PTRDIFF_TYPE__ ssize_t;
typedef __SIZE_TYPE__ size_t;
typedef __SIZE_TYPE__ uintptr_t;
typedef __WCHAR_TYPE__ wchar_t;
typedef __int64 __time64_t;
typedef __int64 INT_PTR, *PINT_PTR;
typedef __int64 LONG64, *PLONG64;
typedef __int64 LONG_PTR, *PLONG_PTR;
typedef __int64_t int64_t;
typedef __uint64_t uint64_t;
typedef char CHAR;
typedef float FLOAT;
typedef int errno_t;
typedef int BOOL;
typedef int INT;
typedef int INT;
typedef int INT;
typedef int far *LPINT;
typedef int near *PINT;
typedef long __time32_t;
typedef long LONG;
typedef long far *LPLONG;
typedef short SHORT;
typedef signed __int64 INT64, *PINT64;
typedef signed char INT8, *PINT8;
typedef signed char int8_t;
typedef signed int INT32, *PINT32;
typedef signed int LONG32, *PLONG32;
typedef signed int int32_t;
typedef signed short INT16, *PINT16;
typedef signed short int int16_t;
typedef unsigned __int64 UINT64, *PUINT64;
typedef unsigned __int64 DWORD64, *PDWORD64;
typedef unsigned __int64 UINT_PTR, *PUINT_PTR;
typedef unsigned __int64 ULONG64, *PULONG64;
typedef unsigned __int64 ULONG_PTR, *PULONG_PTR;
typedef unsigned char BYTE;
typedef unsigned char UINT8, *PUINT8;
typedef unsigned char UCHAR;
typedef unsigned char uint8_t;
typedef unsigned int *PUINT;
typedef unsigned int *PUINT;
typedef unsigned int UINT32, *PUINT32;
typedef unsigned int UINT;
typedef unsigned int UINT;
typedef unsigned int DWORD32, *PDWORD32;
typedef unsigned int ULONG32, *PULONG32;
typedef unsigned int uint32_t;
typedef unsigned long DWORD;
typedef unsigned long ULONG;
typedef unsigned short wctype_t;
typedef unsigned short wint_t;
typedef unsigned short UINT16, *PUINT16;
typedef unsigned short WORD;
typedef unsigned short USHORT;
typedef unsigned short int uint16_t;
typedef void far *LPVOID;
// stdint.h
typedef int int32_t;
typedef int int_fast16_t;
typedef int int_fast32_t;
typedef int int_least32_t;
typedef long long int64_t;
typedef long long int_fast64_t;
typedef long long int_least64_t;
typedef long long intmax_t;
typedef short int16_t;
typedef short int_least16_t;
typedef signed char int8_t;
typedef signed char int_fast8_t;
typedef signed char int_least8_t;
typedef unsigned char uint8_t;
typedef unsigned char uint_fast8_t;
typedef unsigned char uint_least8_t;
typedef unsigned int uint32_t;
typedef unsigned int uint_fast16_t;
typedef unsigned int uint_fast32_t;
typedef unsigned int uint_least32_t;
typedef unsigned long long uint64_t;
typedef unsigned long long uint_fast64_t;
typedef unsigned long long uint_least64_t;
typedef unsigned long long uintmax_t;
typedef unsigned short uint16_t;
typedef unsigned short uint_least16_t;
// basestd.h
#define POINTER_64 __ptr64
#define POINTER_32 __ptr32
#define POINTER_32
#define POINTER_64 __ptr64
#define POINTER_64 __ptr64
#define POINTER_64
#define POINTER_32
#define FIRMWARE_PTR
#define POINTER_SIGNED __sptr
#define POINTER_UNSIGNED __uptr
#define POINTER_SIGNED
#define POINTER_UNSIGNED
#define SPOINTER_32 POINTER_SIGNED POINTER_32
#define UPOINTER_32 POINTER_UNSIGNED POINTER_32
#define _W64 __w64
#define _W64
#define __int3264 __int64
#define ADDRESS_TAG_BIT 0x40000000000UI64
typedef unsigned __int64 POINTER_64_INT;
typedef unsigned __int64 POINTER_64_INT;
typedef unsigned long POINTER_64_INT;
typedef signed char INT8, *PINT8;
typedef signed short INT16, *PINT16;
typedef signed int INT32, *PINT32;
typedef signed __int64 INT64, *PINT64;
typedef unsigned char UINT8, *PUINT8;
typedef unsigned short UINT16, *PUINT16;
typedef unsigned int UINT32, *PUINT32;
typedef unsigned __int64 UINT64, *PUINT64;
typedef signed int LONG32, *PLONG32;
typedef unsigned int ULONG32, *PULONG32;
typedef unsigned int DWORD32, *PDWORD32;
typedef __int3264 INT_PTR, *PINT_PTR;
typedef unsigned __int3264 UINT_PTR, *PUINT_PTR;
typedef __int3264 LONG_PTR, *PLONG_PTR;
typedef unsigned __int3264 ULONG_PTR, *PULONG_PTR;
typedef __int64 INT_PTR, *PINT_PTR;
typedef unsigned __int64 UINT_PTR, *PUINT_PTR;
typedef __int64 LONG_PTR, *PLONG_PTR;
typedef unsigned __int64 ULONG_PTR, *PULONG_PTR;
typedef __int64 SHANDLE_PTR;
typedef unsigned __int64 HANDLE_PTR;
typedef unsigned int UHALF_PTR, *PUHALF_PTR;
typedef int HALF_PTR, *PHALF_PTR;
typedef ULONG_PTR SIZE_T, *PSIZE_T;
typedef LONG_PTR SSIZE_T, *PSSIZE_T;
typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR;
typedef __int64 LONG64, *PLONG64;
typedef unsigned __int64 ULONG64, *PULONG64;
typedef unsigned __int64 DWORD64, *PDWORD64;
typedef ULONG_PTR KAFFINITY;
typedef KAFFINITY *PKAFFINITY;
// minwindef.h
typedef unsigned long ULONG;
typedef ULONG* PULONG;
typedef unsigned short USHORT;
typedef USHORT* PUSHORT;
typedef unsigned char UCHAR;
typedef UCHAR* PUCHAR;
typedef _Null_terminated_ char* PSZ;
typedef unsigned long DWORD;
typedef int BOOL;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef float FLOAT;
typedef FLOAT* PFLOAT;
typedef BOOL near* PBOOL;
typedef BOOL far* LPBOOL;
typedef BYTE near* PBYTE;
typedef BYTE far* LPBYTE;
typedef int near* PINT;
typedef int far* LPINT;
typedef WORD near* PWORD;
typedef WORD far* LPWORD;
typedef long far* LPLONG;
typedef DWORD near* PDWORD;
typedef DWORD far* LPDWORD;
typedef void far* LPVOID;
typedef CONST void far* LPCVOID;
typedef int INT;
typedef unsigned int UINT;
typedef unsigned int* PUINT;
typedef UINT_PTR WPARAM;
typedef LONG_PTR LPARAM;
typedef LONG_PTR LRESULT;
typedef HANDLE NEAR* SPHANDLE;
typedef HANDLE FAR* LPHANDLE;
typedef HANDLE HGLOBAL;
typedef HANDLE HLOCAL;
typedef HANDLE GLOBALHANDLE;
typedef HANDLE LOCALHANDLE;
typedef INT_PTR(FAR WINAPI* FARPROC)();
typedef INT_PTR(NEAR WINAPI* NEARPROC)();
typedef INT_PTR(WINAPI* PROC)();
typedef int(FAR WINAPI* FARPROC)();
typedef int(NEAR WINAPI* NEARPROC)();
typedef int(WINAPI* PROC)();
typedef int(CALLBACK* FARPROC)();
typedef int(CALLBACK* NEARPROC)();
typedef int(CALLBACK* PROC)();
typedef INT_PTR(WINAPI* FARPROC)(void);
typedef INT_PTR(WINAPI* NEARPROC)(void);
typedef INT_PTR(WINAPI* PROC)(void);
typedef WORD ATOM; // BUGBUG - might want to remove this from minwin
typedef HKEY* PHKEY;
typedef HINSTANCE HMODULE; /* HMODULEs can be used in place of HINSTANCEs */
typedef int HFILE;
typedef short HFILE;
// ida_defs.h
typedef __int64 ll;
typedef unsigned __int64 ull;
typedef long long ll;
typedef unsigned long long ull;
#define __int64 long long
#define __int32 int
#define __int16 short
#define __int8 char
#define _BYTE uint8
#define _WORD uint16
#define _DWORD uint32
#define _QWORD uint64
#define BYTE uint8
#define WORD uint16
#define DWORD uint32
#define QWORD uint64
#define _LONGLONG __int128
#define _OWORD __int128
typedef long long ll;
typedef unsigned long long ull;
typedef __int64 ll;
typedef unsigned __int64 ull;
typedef __int64 ll;
typedef unsigned __int64 ull;
typedef __int64 ll;
typedef unsigned __int64 ull;
typedef unsigned int uint;
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned long ulong;
typedef char int8;
typedef signed char sint8;
typedef unsigned char uint8;
typedef short int16;
typedef signed short sint16;
typedef unsigned short uint16;
typedef int int32;
typedef signed int sint32;
typedef unsigned int uint32;
typedef ll int64;
typedef ll sint64;
typedef ull uint64;
typedef int8 _BOOL1;
typedef int16 _BOOL2;
typedef int32 _BOOL4;
typedef int32 LONG;
typedef int BOOL; // uppercase BOOL is usually 4 bytes
// ida header export
#define __int8 char
#define __int16 short
#define __int32 int
#define __int64 long long
typedef struct _GUID GUID;
typedef unsigned __int32 DWORD;
typedef unsigned __int64 ULONG_PTR;
typedef __int32 LONG;
typedef char CHAR;
typedef unsigned __int32 ULONG;
typedef HWND__ *HWND;
typedef const CHAR *LPCSTR;
typedef HINSTANCE__ *HINSTANCE;
typedef HKEY__ *HKEY;
typedef void *HANDLE;
typedef _RTL_CRITICAL_SECTION_DEBUG *PRTL_CRITICAL_SECTION_DEBUG;
typedef unsigned __int16 WORD;
typedef _LIST_ENTRY LIST_ENTRY;
typedef unsigned __int16 wchar_t;
typedef wchar_t WCHAR;
typedef unsigned __int64 ULONGLONG;
typedef __int64 LONGLONG;
typedef unsigned __int64 DWORD64;
typedef unsigned __int8 BYTE;
typedef _XSAVE_FORMAT XSAVE_FORMAT;
typedef unsigned __int16 VARTYPE;
typedef WORD PROPVAR_PAD1;
typedef WORD PROPVAR_PAD2;
typedef WORD PROPVAR_PAD3;
typedef unsigned __int8 UCHAR;
typedef __int16 SHORT;
typedef unsigned __int16 USHORT;
typedef float FLOAT;
typedef double DOUBLE;
typedef __int16 VARIANT_BOOL;
typedef LONG SCODE;
typedef double DATE;
typedef GUID CLSID;
typedef tagCLIPDATA CLIPDATA;
typedef WCHAR OLECHAR;
typedef OLECHAR *BSTR;
typedef CHAR *LPSTR;
typedef WCHAR *LPWSTR;
typedef int INT;
typedef unsigned int UINT;
typedef tagVersionedStream *LPVERSIONEDSTREAM;
typedef tagSAFEARRAY SAFEARRAY;
typedef SAFEARRAY *LPSAFEARRAY;
typedef void *PVOID;
typedef tagSAFEARRAYBOUND SAFEARRAYBOUND;
typedef __int32 HRESULT;
typedef DWORD LCID;
typedef OLECHAR *LPOLESTR;
typedef LONG DISPID;
typedef tagDISPPARAMS DISPPARAMS;
typedef tagVARIANT VARIANT;
typedef tagEXCEPINFO EXCEPINFO;
typedef tagSTATSTG STATSTG;
typedef LPOLESTR *SNB;
typedef tagTYPEATTR TYPEATTR;
typedef tagFUNCDESC FUNCDESC;
typedef tagVARDESC VARDESC;
typedef DISPID MEMBERID;
typedef DWORD HREFTYPE;
typedef tagINVOKEKIND INVOKEKIND;
typedef tagTYPEKIND TYPEKIND;
typedef tagTYPEDESC TYPEDESC;
typedef tagIDLDESC IDLDESC;
typedef tagELEMDESC ELEMDESC;
typedef tagFUNCKIND FUNCKIND;
typedef tagCALLCONV CALLCONV;
typedef tagPARAMDESCEX *LPPARAMDESCEX;
typedef tagPARAMDESC PARAMDESC;
typedef tagVARKIND VARKIND;
typedef const OLECHAR *LPCOLESTR;
typedef int BOOL;
typedef tagDESCKIND DESCKIND;
typedef tagBINDPTR BINDPTR;
typedef tagTLIBATTR TLIBATTR;
typedef tagSYSKIND SYSKIND;
typedef USHORT ADDRESS_FAMILY;
typedef void *LPVOID;
typedef ULONG_PTR DWORD_PTR;
typedef ULONG_PTR SIZE_T;
typedef ULONGLONG DWORDLONG;
typedef tagWNDCLASSW WNDCLASSW;
typedef __int64 LONG_PTR;
typedef LONG_PTR LRESULT;
typedef unsigned __int64 UINT_PTR;
typedef UINT_PTR WPARAM;
typedef LONG_PTR LPARAM;
typedef LRESULT (__stdcall *WNDPROC)(HWND, UINT, WPARAM, LPARAM);
typedef HICON__ *HICON;
typedef HICON HCURSOR;
typedef HBRUSH__ *HBRUSH;
typedef const WCHAR *LPCWSTR;
typedef #253 POINT;
typedef _XINPUT_STATE XINPUT_STATE;
typedef _XINPUT_GAMEPAD XINPUT_GAMEPAD;
typedef tagRECT RECT;
typedef tagRAWINPUTDEVICE RAWINPUTDEVICE;
typedef _XINPUT_VIBRATION XINPUT_VIBRATION;
typedef addrinfo ADDRINFOA;
typedef unsigned __int64 size_t;
typedef GUID UUID;
typedef unsigned int u_int;
typedef UINT_PTR SOCKET;
typedef _tagpropertykey PROPERTYKEY;
typedef _AMMediaType AM_MEDIA_TYPE;
typedef AM_MEDIA_TYPE DMO_MEDIA_TYPE;
typedef _EXCEPTION_RECORD EXCEPTION_RECORD;
typedef _SYSTEMTIME SYSTEMTIME;
typedef BYTE *LPBYTE;
typedef threadlocaleinfostruct *pthreadlocinfo;
typedef struct threadmbcinfostruct *pthreadmbcinfo;
typedef tagLC_ID LC_ID;
typedef unsigned int _dev_t;
typedef unsigned __int16 _ino_t;
typedef __int64 __time64_t;
typedef _iobuf FILE;
typedef _MEMORY_BASIC_INFORMATION MEMORY_BASIC_INFORMATION;
typedef uint16_t NetObjectId;
typedef in_addr IN_ADDR;
typedef size_t size_type;
typedef _RTL_CRITICAL_SECTION RTL_CRITICAL_SECTION;
typedef RTL_CRITICAL_SECTION CRITICAL_SECTION;
typedef scrNativeCallContext *native;
typedef __MIDL___MIDL_itf_mfobjects_0000_0006_0003 MFT_REGISTER_TYPE_INFO;
enum tagINVOKEKIND
enum tagTYPEKIND
enum tagFUNCKIND
enum tagCALLCONV
enum tagVARKIND
enum tagDESCKIND
enum tagSYSKIND
enum eNetworkEvent
enum eReportType
enum eEntityType
enum MACRO_FALSE
enum eTlsOffset
enum btSeatbeltWindshieldBits
enum eThreadState
enum MACRO_NULL
enum MACRO_WM
enum bitwriter_flag_t
enum MACRO_SOCKET
enum MACRO_DNS_ERROR_INVALID_DATA
enum MACRO_AF
enum MACRO_SO_SNDBUF
enum MACRO_SOCK
enum MACRO_NULLPTR
// stdpkey.h
// types.h
typedef DWORD Any;
typedef DWORD Hash;
typedef DWORD Void;
typedef DWORD uint;
typedef int Blip;
typedef int Cam;
typedef int Camera;
typedef int CarGenerator;
typedef int ColourIndex;
typedef int CoverPoint;
typedef int Entity;
typedef int FireId;
typedef int Group;
typedef int Interior;
typedef int Object;
typedef int Ped;
typedef int Pickup;
typedef int Player;
typedef int ScrHandle;
typedef int Sphere;
typedef int TaskSequence;
typedef int Texture;
typedef int TextureDict;
typedef int Train;
typedef int Vehicle;
typedef int Weapon;
typedef uint Hash;
"""
"""
note: standard types for c++
bool size: 1
char size: 1
char16_t size: 2
char32_t size: 32
char8_t size: 0
double size: 8
float size: 4
int size: 4
long double size: 8
long int size: 4
long long int size: 8
short int size: 2
unsigned char size: 1
unsigned int size: 4
unsigned long int size: 4
unsigned long long int size: 8
unsigned short int size: 2
wchar_t => unsigned __int16 size: 2
"""
reclass_types = [
"nt_base", "nt_instance", "nt_struct", "nt_hidden", "nt_hex32", "nt_hex64",
"nt_hex16", "nt_hex8", "nt_pointer", "nt_int64", "nt_int32", "nt_int16",
"nt_int8", "nt_float", "nt_double", "nt_uint32", "nt_uint16", "nt_uint8",
"nt_text", "nt_unicode", "nt_functionptr", "nt_custom", "nt_vec2", "nt_vec3",
"nt_quat", "nt_matrix", "nt_vtable", "nt_array", "nt_class", "nt_pchar",
"nt_pwchar", "nt_bits", "nt_uint64", "nt_function",
"nt_ptrarray" ]
def getStrucSize(name):
return idc.get_struc_size(idc.get_struc_id(name))
def doesStrucExist(name):
return idc.get_struc_id(name) != idc.BADADDR
def get_tinfo_by_parse(name):
result = idc.parse_decl(name, idc.PT_SILENT)
if result is None:
return
_, tp, fld = result
tinfo = idaapi.tinfo_t()
tinfo.deserialize(idaapi.cvar.idati, tp, fld, None)
return tinfo
def get_tinfo_magic(name):
tif = get_tinfo_by_parse(name + '*')
if not tif:
return
return tif.get_pointed_object()
def get_tinfo_brute(name):
idati = ida_typeinf.get_idati()
ti = ida_typeinf.tinfo_t()
for ordinal in range(1, ida_typeinf.get_ordinal_qty(idati)+1):
if ti.get_numbered_type(idati, ordinal) and ti.dstr() == name:
return ti
return None
def get_tinfo_lame(name):
ordinal = idaapi.get_type_ordinal(idaapi.cvar.idati, name)
if ordinal:
tinfo = idaapi.tinfo_t()
if tinfo.get_numbered_type(idaapi.cvar.idati, ordinal):
return tinfo
def get_tinfo_elegant(name):
ti = ida_typeinf.tinfo_t()
til = ti.get_til()
# get_named_type(self, til, name, decl_type=BTF_TYPEDEF, resolve=True, try_ordinal=True)
if ti.get_named_type(til, name, ida_typeinf.BTF_STRUCT, True, True):
return ti
return None
# def get_type_tinfo(t):
# type_tuple = idaapi.get_named_type(None, t, 1)
# tif = idaapi.tinfo_t()
# try:
# tif.deserialize(None, type_tuple[1], type_tuple[2])
# return tif
# except TypeError:
# return None
def get_tinfo_settype(name, ea):
ea = eax(ea)
if idc.SetType(ea, name):
return ida_typeinf.idc_get_type_raw(ea)
return None
def get_tinfo_test(name):
f = [get_tinfo_by_parse, get_tinfo_elegant, get_tinfo_brute, get_tinfo_mega, get_tinfo_lame]
results = {}
for fn in f:
results[fn.__name__] = fn(name)
return results
def get_tinfo_mega(name):
r = idc.parse_decl("""
struct membrick_decl_test {{
{0} test_value;
{0}* test_ptr;
{0} test_array[2];
}};""".format(name), idc.PT_SILENT |idc.PT_TYP | idc.PT_REPLACE | idc.PT_PAK1)
if not r:
return False
tif = ida_typeinf.tinfo_t()
tif.deserialize(None, r[1], r[2])
tif = get_field_at_offset(tif, 0)
if not tif:
return False
tif = tif[0]
typename = tif.get_type_name()
if not typename:
print("[get_intof_mega [debug]] not a 'real' type")
typename = str(tif)
if typename == name:
return tif
return False
def get_structnames_by_ordinal():
idati = ida_typeinf.get_idati()
ti = ida_typeinf.tinfo_t()
for ordinal in range(1, ida_typeinf.get_ordinal_qty(idati)+1):
if ti.get_numbered_type(idati, ordinal):
yield ti.dstr()
def StructsMatching(regex=None, exclude=None, filter=lambda x: x, flags=0):
if regex and not isinstance(regex, re.Pattern):
regex = re.compile(regex, flags)
if exclude and not isinstance(exclude, re.Pattern):
exclude = re.compile(exclude, flags)
result = [a for a in get_structnames_by_ordinal() if filter(a) and (not regex or re.match(regex, a))]
if exclude:
result = [a for a in result if not re.search(regex, idc.get_name(a))]
return result
def get_field_at_offset(tinfo, offset):
result = []
udt_data = idaapi.udt_type_data_t()
tinfo.get_udt_details(udt_data)
udt_member = idaapi.udt_member_t()
udt_member.offset = offset * 8
idx = tinfo.find_udt_member(udt_member, idaapi.STRMEM_OFFSET)
if idx != -1:
while idx < tinfo.get_udt_nmembers() and udt_data[idx].offset == offset * 8:
udt_member = udt_data[idx]
if udt_member.offset == offset * 8:
result.append(udt_member.type)
idx += 1
return result
def has_decl(name, size=None, raw=False):
r = idc.parse_decl("""
struct membrick_decl_test {{
{0} test_value;
{0}* test_ptr;
{0} test_array[2];
}};""".format(name), idc.PT_SILENT) # |idc.PT_TYP | idc.PT_REPLACE | idc.PT_PAK1)
if r:
tif = ida_typeinf.tinfo_t()
tif.deserialize(None, r[1], r[2])
ti2 = get_field_at_offset(tif, 0)
# return ti2
if ti2 and len(ti2):
ti3 = ti2[0]
typename = ti3.get_type_name() or str(ti3)
if typename == name:
if size and size is not None:
if ti3.get_size() == size:
return ti3 if raw else (True, ti3)
return (False, "size", ti3.get_size())
return ti3 if raw else (True, ti3)
return (False, "get_type_name", [(t.get_type_name(), str(t)) for t in ti2])
return (False, "get_field_at_offset")
return (False, "parse_decl")
def get_fields_at_offset(tinfo, offset):
"""
Given tinfo and offset of the structure or union, returns list of all tinfo at that offset.
This function helps to find appropriate structures by type of the offset
"""
EA64 = idaapi.get_inf_structure().is_64bit()
EA_SIZE = 8 if EA64 else 4
result = []
if offset == 0:
result.append(tinfo)
udt_data = idaapi.udt_type_data_t()
tinfo.get_udt_details(udt_data)
udt_member = idaapi.udt_member_t()
udt_member.offset = offset * 8
idx = tinfo.find_udt_member(udt_member, idaapi.STRMEM_OFFSET)
if idx != -1:
while idx < tinfo.get_udt_nmembers() and udt_data[idx].offset <= offset * 8:
udt_member = udt_data[idx]
if udt_member.offset == offset * 8:
if udt_member.type.is_ptr():
result.append(idaapi.get_unk_type(EA_SIZE))
result.append(udt_member.type)
result.append(idaapi.dummy_ptrtype(EA_SIZE, False))
elif not udt_member.type.is_udt():
result.append(udt_member.type)
if udt_member.type.is_array():
if (offset - udt_member.offset // 8) % udt_member.type.get_array_element().get_size() == 0:
result.append(udt_member.type.get_array_element())
elif udt_member.type.is_udt():
result.extend(get_fields_at_offset(udt_member.type, offset - udt_member.offset // 8))
idx += 1
return result
def StructMatchOffset(_offset, _type, _limit = 32):
min_size = _offset # + sizeof type
_tinfo = get_tinfo(_type)
result = []
tinfo = idaapi.tinfo_t()
for ordinal in range(1, idaapi.get_ordinal_qty(idaapi.cvar.idati)):
tinfo.get_numbered_type(idaapi.cvar.idati, ordinal)
if tinfo.is_udt() and tinfo.get_size() >= min_size:
is_found = False
potential_members = get_fields_at_offset(tinfo, _offset)
for potential_member in potential_members:
if _tinfo.dstr() == potential_member.dstr():
# if tinfo.equals_to(_tinfo):
print(tinfo.dstr(), potential_member.dstr(), _tinfo.dstr())
is_found = True
break
if is_found:
result.append((ordinal, idaapi.tinfo_t(tinfo)))
return result
#
# def get_type_tinfo(t):
# type_tuple = idaapi.get_named_type(None, t, 1)
# tif = idaapi.tinfo_t()
# try:
# tif.deserialize(None, type_tuple[1], type_tuple[2])
# return tif
# except TypeError:
# return None
get_type_tinfo = get_tinfo
def parseTypeDefs(lines):
global __typedefs
re_typedef = re.compile(r'typedef\s+((?:(?:\w+)(?:\s+))+)((?:(?:\*?\w+)[,;]\s*)+)')
re_define = re.compile(r'#define\s+(\w+)((?:(?:\s+)(?:\w+))+)')
for l in lines:
found = 0
for (_type, _alias) in re.findall(re_typedef, l):
found += 1
_aliases = [x for x in [x.strip().rstrip(';') for x in _alias.split(",")] if len(x)]
_type = " ".join([x for x in [x.strip() for x in _type.split(" ")] if len(x)])
for _alias in _aliases:
if "*" not in _alias:
# _alias = resolveTypeDefModifiers(_alias)
_type = resolveTypeDefModifiers(_type)
if _alias is not None and _type is not None:
__typedefs[_alias] = _type
for (_alias, _type) in re.findall(re_define, l):
found += 1
_type = " ".join([x for x in [x.strip() for x in _type.split(" ")] if len(x)])
# _alias = resolveTypeDefModifiers(_alias)
_type = resolveTypeDefModifiers(_type)
if _alias is not None and _type is not None:
__typedefs[_alias] = _type
if not found:
pass
# print("No match found in line: %s" % l)
# else: print("Matched: %s" % l)
def parseHex(string, _default = None):
if string.startswith('0x'):
string = string[2:]
# string = string.lstrip('0x')
if not string:
print('empty string')
return int(string, 16)
def parseHexDefault(string, _default = None):
if not string:
return _default
try:
string = string.lstrip('0x')
return int(string, 16)
except ValueError:
print("Exception parseHex('{}'): Invalid".format(string))
def sizeTypeDef(type):
sid = idc.get_struc_id(type)
if sid != idc.BADADDR:
return idc.get_struc_size(sid)
try:
name, tp, fld = idc.parse_decl(type, 1)
if tp:
return idc.SizeOf(tp)
except:
return 0
def resolveTypeDefModifiers(type):
type = type.replace("std::", "")
modifiers = ["signed", "unsigned", "short", "long"]
modifiersFound = list()
words = [x for x in [x.strip() for x in type.split(" ")] if len(x)]
mods = list()
non = list()
for word in words:
if word in modifiers:
modifiersFound.append(modifiers.index(word))
mods.append(word)
else:
non.append(word)
if not len(non):
non = ["int"]
modBitmap = 0
for mod in modifiersFound:
modBitmap |= (1 << mod)
if modBitmap & 0b0011 == 0b0011: # signed and unsigned
print("invalid combination of signed and unsigned type modifiers")
return None
if modBitmap & 0b1100 == 0b1100: # long and short
print("invalid combination of long and short type modifiers")
return None
modCount = dict()
for mod in mods:
if mod in modCount:
if mod != "long" or mod == "long" and modCount["long"] == 2:
print("too many %s's in type modifier" % mod)
return None
modCount[mod] += 1
else:
modCount[mod] = 1
# todo: redo with bitmap
if "signed" in modCount:
del(mods[mods.index("signed")])
if "long" in modCount and "double" in modCount:
del(mods[mods.index("long")])
if "long" in modCount and "float" in modCount:
del(mods[mods.index("long")])
del(mods[mods.index("float")])
mods.append("double")
mods.sort()
# after sorting, alphabetical order is conviently:
# long short signed unsigned
mods.reverse()
mods.extend(non)
return " ".join(mods)
def resolveTypeDef(type):
global __typedefs
type = resolveTypeDefModifiers(type)
while type in __typedefs:
type = __typedefs[type]
type = resolveTypeDefModifiers(type)
return type
def resolveTypeDefs():
global __typedefs
types = list(__typedefs.keys())
types = ["bool", "char", "char8_t", "char16_t", "char32_t", "double",
"float", "int", "long", "long double", "long int", "long int unsigned long", "long long", "long long int", "short", "short int", "signed",
"signed char", "signed int", "signed long", "signed long int", "signed long long", "signed long long int", "signed short", "signed short int",
"unsigned", "unsigned char", "unsigned int", "unsigned long", "unsigned long int", "unsigned long long", "unsigned long long int", "unsigned short",
"unsigned short int", "std::wchar_t", "std::uint8_t",
"std::uint16_t", "std::uint32_t", "std::uint64_t", "std::int8_t",
"std::int16_t", "std::int32_t", "unsigned std::int64_t", "std::uintptr_t",
"std::intptr_t", "const std::size_t", "DWORD", "_DWORD", "QWORD", "_QWORD",
"_OWORD", "PSZ", "LPBOOL", "PBOOL", "PBOOLEAN", "BOOLEAN", "LPBYTE",
"PBYTE", "LPCVOID", "LPDWORD", "PDWORD", "PFLOAT", "PUCHAR", "PULONG",
"PDWORD_PTR", "PUSHORT", "LPWORD", "PWORD", "intptr_t", "ptrdiff_t",
"ssize_t", "size_t", "uintptr_t", "wchar_t", "__time64_t", "PINT_PTR",
"PLONG64", "PLONG_PTR", "CHAR", "FLOAT", "errno_t", "BOOL", "INT", "INT",
"INT", "LPINT", "PINT", "__time32_t", "LONG", "LPLONG", "SHORT", "PINT64",
"PINT8", "int8_t", "PINT32", "PLONG32", "int32_t", "PINT16", "int16_t",
"PUINT64", "PDWORD64", "PUINT_PTR", "PULONG64", "PULONG_PTR", "BYTE",
"PUINT8", "UCHAR", "uint8_t", "PUINT", "PUINT", "PUINT32", "UINT", "UINT",
"PDWORD32", "PULONG32", "uint32_t", "DWORD", "ULONG", "wctype_t", "wint_t",
"PUINT16", "WORD", "USHORT", "uint16_t", "LPVOID" ]
# types.extend(__typedefs.keys())
for type in types:
path = list()
path.append(type)
type = resolveTypeDefModifiers(type)
path.append(type)
while type in __typedefs:
type = __typedefs[type]
path.append(type)
resolved = resolveTypeDefModifiers(type)
if resolved != type:
path.append(resolved)
print(" => ".join(path) + " size: %s" % sizeTypeDef(type))
def parseStrucStringInternal(st):
re_line = re.compile(r'^\s*((?:(?:\s+)(?:\w+))+)([ *]+)(\w+)((?:\[[0-9]+\])?);')
line_iter = line_split(st)
try:
next(line_iter)
next(line_iter)
except StopIteration:
print("StopIteration: Not enough lines: {}".format(st))
raise StopIteration
member_types = dict()
alignments = dict()
for l in line_iter:
l = string_between('', ';', l, inclusive=1)
if not l:
continue
# __declspec(align(8)) float y;
alignment, l = string_between_splice('__declspec(align(', ')) ', l, inclusive=1, repl='')
for (_type, _stars, _name, _subscript) in re.findall(re_line, l):
# dprint("[debug] _type, _stars, _name, _subscript")
if debug:
print("[debug] _type:{}, _stars:{}, _name:{}, _subscript:{}".format(_type, _stars, _name, _subscript))
_type = " ".join([x for x in [x.strip() for x in _type.split(" ")] if len(x)]) + _stars.strip() + _subscript
if debug:
print("[debug] _type:{}".format(_type))
member_types[_name] = _type
if alignment and string_between('__declspec(align(', ')) ', alignment):
alignment = int(string_between('__declspec(align(', ')) ', alignment))
alignments[_name] = alignment
if debug:
print("[debug] _alignment:{}".format(alignment))
return member_types, alignments
def my_print_decls(name, flags = PDF_INCL_DEPS | PDF_DEF_FWD):
names = A(name)
ordinals = []
for name in names:
ti = get_tinfo_by_parse(name)
if ti:
ordinal = ti.get_ordinal()
if ordinal:
ordinals.append(ordinal)
continue
print("[warn] couldn't get ordinal for type '{}'".format(name))
if not ordinals:
print("[warn] couldn't get ordinals for types '{}'".format(name))
return ''
# else:
# print("[info] ordinals: {}".format(ordinals))
# dprint("[debug] ordinals")
# print("[debug] ordinals:{}".format(ordinals))
# void __fastcall(__int64 a1, void (__fastcall ***a2)(_QWORD, __int64))
result = ''
if ordinals:
result = idc.print_decls(','.join([str(x) for x in ordinals if x > -1]), flags)
splitted = re.split(r'\n\n/\* \d+ \*/\n', result)
result_object = dict()
for s in splitted:
s1 = string_between('', '\n', s, retn_all_on_fail=1)
# typedef struct tagCALPSTR CALPSTR;
# typedef unsigned __int8 uint8_t;
# typedef/struct/union
t = string_between('', ' ', s1)
t1 = string_between('', ' : ', s1, retn_all_on_fail=1)
# struct/typedef/union name
t2 = string_between(' ', '', t1, rightmost=1)
# skip forward decls
if t == 'struct' and t2.endswith(';'):
continue
t2 = t2.rstrip(';')
result_object[t2] = s
print(result)
return result_object