-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlabsync.py
1950 lines (1514 loc) · 64.1 KB
/
labsync.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
from __future__ import annotations
import configparser
import contextlib
import dataclasses
import functools
import heapq
import io
import logging
import os
import pathlib
import re
import string
import tempfile
import time
import uuid
from collections.abc import Generator
from typing import IO, Any, Optional
import git
import parse
import yaml
try:
import functioninliner
except ModuleNotFoundError:
# define a mock that will allow us to work without functioninliner installed
class functioninliner: # noqa: N801
class ClonesStorage(dict):
def update_from_storage(self) -> None:
pass
try:
import ida_diskio
import ida_idaapi
import ida_idp
import ida_kernwin
import ida_loader
import ida_nalt
import ida_name
import ida_segment
import ida_typeinf
import ida_xref
import idautils
import netnode
import sark
except ModuleNotFoundError:
# define mocks to support importing outside of IDA for testing
class ida_kernwin: # noqa: N801
class action_handler_t: # noqa: N801
pass
class UI_Hooks: # noqa: N801
pass
class ida_idaapi: # noqa: N801
PLUGIN_MOD = 0
PLUGIN_HIDE = 0
BADADDR = 0
class plugin_t: # noqa: N801
pass
class ida_idp: # noqa: N801
IDP_INTERFACE_VERSION = 0
class ida_typeinf: # noqa: N801
class text_sink_t: # noqa: N801
pass
class tinfo_t: # noqa: N801
pass
class netnode: # noqa: N801
class Netnode:
pass
# CONFIGURATION
# we decided not to normalize prototypes because it makes it much harder to resolve conflicts since
# you don't know which function you're looking at
#
# the downside is that a conflict on a function name change will result in two conflicts (one on
# the name and one on the prototype)
NORMALIZE_PROTOTYPES = False
# we decided not to remove names and prototypes that are missing in the YAML since some times
# exporting/importing them remotely can be an issue and so they will be removed locally as well
REMOVE_MISSING_NAMES_AND_PROTOTYPES = False
LOCAL_TYPES_COMMENT_FMT = "/* >> LABSYNC DO NOT TOUCH: {} << */"
LOCKFILE = "labsync.lock"
DEFAULT_LOCK_TIMEOUT = 60 # sec
# LOGGING
class LoggerWithTrace(logging.getLoggerClass()):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
logging.TRACE = 5
logging.addLevelName(logging.TRACE, "TRACE")
def trace(self, msg: str, *args, **kwargs) -> None:
self.log(logging.TRACE, msg, *args, **kwargs)
logger = LoggerWithTrace("LabSync")
# EXCEPTIONS
class LabSyncError(Exception):
pass
class LabSyncLockError(LabSyncError):
pass
class LabSyncBinaryMatchingError(LabSyncError):
pass
# HELPERS
class LabSyncYAMLDumper(yaml.CDumper):
@staticmethod
def _hex_representer(dumper: yaml.Dumper, data: int) -> str:
return dumper.represent_scalar("tag:yaml.org,2002:int", hex(data))
@staticmethod
def _str_representer(dumper: yaml.dumper, data: str) -> str:
if "\n" in data:
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
else:
return dumper.represent_scalar("tag:yaml.org,2002:str", data)
LabSyncYAMLDumper.add_representer(int, LabSyncYAMLDumper._hex_representer) # noqa: SLF001
LabSyncYAMLDumper.add_representer(str, LabSyncYAMLDumper._str_representer) # noqa: SLF001
@contextlib.contextmanager
def wait_box(msg: str, *, hide_cancel: bool = False) -> None:
prefix = "HIDECANCEL\n" if hide_cancel else ""
ida_kernwin.show_wait_box(prefix + msg)
try:
yield None
finally:
ida_kernwin.hide_wait_box()
class StringIOTextSink(ida_typeinf.text_sink_t):
def __init__(self):
super().__init__()
self.sio = io.StringIO()
def _print(self, thing: str) -> int:
self.sio.write(thing)
return 0
def local_types() -> Generator[str]:
name = ida_typeinf.first_named_type(None, ida_typeinf.NTF_TYPE)
while name:
yield name
name = ida_typeinf.next_named_type(None, name, ida_typeinf.NTF_TYPE)
# EXPORT LOGIC
@dataclasses.dataclass(eq=True, order=True)
class SyncedBinary:
idb_id: str = dataclasses.field(compare=False)
start_ea: int = 0 # must be the first field, because we rely on it when sorting
end_ea: int = ida_idaapi.BADADDR # exclusive
base_ea: int = 0
seg_prefix: Optional[str] = None
def contains(self, ea: int) -> bool:
return self.start_ea <= ea < self.end_ea
def ea2dump(self, ea: int) -> int:
return ea - self.base_ea
def dump2ea(self, dea: int) -> int:
return dea + self.base_ea
def dump_names(binary: SyncedBinary, storage: functioninliner.ClonesStorage) -> dict[int, str]:
d = {}
for ea, name in idautils.Names():
if not binary.contains(ea):
continue
seg = ida_segment.getseg(ea)
seg_name = ida_segment.get_segm_name(seg)
# skip names that are in inlined chunks
if seg_name.startswith("inlined_"):
continue
# skip names for inlined functions
if ea in storage:
continue
dea = binary.ea2dump(ea)
d[dea] = name
return d
def dump_inlined_funcs(binary: SyncedBinary, storage: functioninliner.ClonesStorage) -> list[int]:
funcs = (binary.ea2dump(ea) for ea in storage if binary.contains(ea))
return list(sorted(funcs)) # noqa: C413
def stable_topological_sort(graph: dict[Any, set[Any]]) -> Generator[Any]:
heap = []
next_v = None
while heap or graph:
for v, edges in list(graph.items()):
if next_v is not None:
edges.discard(next_v)
if not edges:
heapq.heappush(heap, v)
del graph[v]
if not heap:
msg = "graph contains unsolvable dependencies"
raise ValueError(msg)
next_v = heapq.heappop(heap)
yield next_v
def dump_local_types(types: netnode.Netnode) -> str:
# we emulate print_decls() ourselves because it internally uses PRTYPE_NOREGEX and this
# removes namespaces which starts with double underscore (e.g. std::__1::__libcpp_refstring)
local_types_by_ordinal = {} # ordinal: (name, decl, dependencies)
local_types_by_name = {} # name: (ordinal, decl, dependencies)
tinfo = ida_typeinf.tinfo_t()
for ordinal in range(1, ida_typeinf.get_ordinal_qty(None)):
if not tinfo.get_numbered_type(None, ordinal):
continue # deleted ordinal
name = tinfo.get_type_name()
flags = (
ida_typeinf.PRTYPE_MULTI | # multiline
ida_typeinf.PRTYPE_TYPE | # required to have it named
ida_typeinf.PRTYPE_PRAGMA | # include alignment pragmas
ida_typeinf.PRTYPE_SEMI | # end with semicolon
ida_typeinf.PRTYPE_CPP | # unsure if this is needed, but to be on the safe side...
ida_typeinf.PRTYPE_DEF | # required to have a full definition
ida_typeinf.PRTYPE_NOREGEX # required to keep the name as-is
)
decl = ida_typeinf.print_tinfo(None, 2, 0, flags, tinfo, name, None)
decl = decl.strip()
# also strip trailing spaces since they arn't block-encodable in YAML
decl = "\n".join(line.rstrip() for line in decl.splitlines())
# TODO @TH: there is an IDA bug where comment-only changes to local types are not updated
# when using parse_decls() so for now we just strip all comments until it'll be
# fixed
decl = strip_comments(decl)
# IDA apparently can't handle templates in parse_decls(), so we we don't bother syncing
# them at all. hopefully no sane reverser actually uses them and these are only imported
# from debug symbols and never touched
if "<" in decl:
logger.warning(
f"skipping syncing of local type {name!r} because templates are unsupported" # noqa: COM812
)
continue
# do a sanity for the extract of the name, since it'll be used when updating
parsed_name, _ = decl_to_name_and_type(decl)
assert name == parsed_name
# see if this type is dependent on others
dependencies = set()
udt = ida_typeinf.udt_type_data_t()
if tinfo.get_udt_details(udt):
for i in range(udt.size()):
udm = udt[i]
udm_ordinal = udm.type.get_ordinal()
if udm_ordinal:
dependencies.add(udm_ordinal)
# keep it
local_types_by_ordinal[ordinal] = (name, decl, dependencies)
assert name not in local_types_by_name
local_types_by_name[name] = (ordinal, decl, dependencies)
dep_graph = {}
for name, _, deps in local_types_by_ordinal.values():
dep_names = {local_types_by_ordinal[d][0] for d in deps if d in local_types_by_ordinal}
if len(dep_names) != len(deps):
logger.warning(
f"skipping syncing of local type {name!r} because it depends on other non-synced "
"local types" # noqa: COM812
)
continue
dep_graph[name] = dep_names
# generate a normalized header file that is sorted by dependecy order and lexigraphically,
# to make YAML diffs sane
nhdr = io.StringIO()
for name in stable_topological_sort(dep_graph):
_, decl, _ = local_types_by_name[name]
# add uuid
tid = ida_typeinf.get_named_type_tid(name)
if tid == ida_idaapi.BADADDR:
msg = f"failed to resolve tid of local type {name!r}:\n{decl}"
raise LabSyncError(msg)
decl_uuid = types.get(tid)
if not decl_uuid:
types[tid] = decl_uuid = str(uuid.uuid4())
nhdr.write(LOCAL_TYPES_COMMENT_FMT.format(decl_uuid))
nhdr.write("\n")
nhdr.write(decl)
nhdr.write("\n\n")
return nhdr.getvalue().strip()
def strip_comments(decl: str) -> str:
stripped_lines = []
for line in decl.splitlines():
try:
line = line[:line.index("//")].rstrip()
if not line:
continue
except ValueError:
pass
stripped_lines.append(line)
return "\n".join(stripped_lines)
@functools.cache
def decl_to_type_name_pat() -> re.Pattern:
"""this generates a pattern that tries to match the first line of a (stripped) decl to the
its type (e.g. struct/union/typedef) and name
the regex matches 2N groups where group 2i is "type" and group 2i+1 is name, for different
possible subregexes. Only 2 groups (for some i) should be matched
this regex is a bit more "allowing" than how IDA formats decls, since we also use it to
match decls from YAMLs in which the user might've changed some whitespacing while manually
resolving a merge conflict
"""
# from ida.cfg:TypeNameChars
name_chars = r"_:$()`'{}" + string.digits + string.ascii_letters
# from blackbox testing what's allowed from name_chars as the first character
name_first_chars = r"_$`" + string.ascii_letters
name_pat = r"([" + re.escape(name_first_chars) + "][" + re.escape(name_chars) + "]*?)"
type_pat = (
r"(?!typedef)(\S+)(?=\s)" # only match non-typedefs
r".*?\s" + # everything up to the name (i.e. type + attributes)
name_pat +
r"(?:\s*(?<!:):(?!:).*)?" # optional inheritance or IDA syntax for data types of enums
r"\s*;?" # optional semicolon in case of forward declarations
)
fptr_typedef_pat = (
r"(typedef)(?=\s)" # only match typdefs
r".*?" # everything up to the name
r"\*\s*" + # the star before the name
name_pat +
r"\s*\)\(.*" # match the first function def in the line, in case there is also a fptr arg
r".*;" # everything else
)
norm_typedef_pat = (
r"(typedef)(?=\s)" # only match typdefs
r".*?" # everything up to the name
r"\**" + # optional stars before the name
name_pat +
r"(?:\s*\[\s*\d*\s*\])?" # optional array part
r"\s*;" # end of the typedef
)
pat = (
r"^(?:" # start of line
r"(?:" + type_pat + ")"
r"|"
r"(?:" + fptr_typedef_pat + ")"
r"|"
r"(?:" + norm_typedef_pat + ")"
r")$" # end of line
)
return re.compile(pat)
def decl_to_name_and_type(decl: str) -> tuple[str, str]:
# skip pragma/comment lines
for first_line in decl.splitlines():
if not any(first_line.lstrip().startswith(x) for x in ("#", "//")):
break
else:
msg = f"empty local type:\n{decl}"
raise LabSyncError(msg)
# strip the first line
first_line = first_line.strip()
# extract the name and decl type
pat = decl_to_type_name_pat()
m = pat.match(first_line)
if not m:
msg = f"failed to parse local type:\n{decl}"
raise LabSyncError(msg)
decl_type = m.group(m.lastindex - 1)
name = m.group(m.lastindex)
# should never happen according to our regex
assert decl_type
assert name
return name, decl_type
def fix_non_present_arguments(name: str, tinfo: ida_typeinf.tinfo_t, *, add: bool = True) \
-> tuple[ida_typeinf.tinfo_t, bool]:
def type_exists(tinfo: ida_typeinf.tinfo_t) -> bool:
if tinfo.present():
return True
# originally we used just tinfo.present(), but for some reason it keeps returning False
# even after we saved the type (as a forward declaration)
#
# then we used tinfo.get_ordinal() > 0 as a test, but on huge IDBs with >10k types, for
# some reason it kept returning 0 even after we saved the type
#
# therefore we moved to checking if we can get the tid for the type name. you have to watch
# out, however, since for deleted types tinfo.get_type_name() raises UnicodeDecodeError
try:
tname = tinfo.get_type_name()
except UnicodeDecodeError:
return False
tid = ida_typeinf.get_named_type_tid(tname)
return tid != ida_idaapi.BADADDR
def fix_non_present(tinfo: ida_typeinf.tinfo_t) -> tuple[ida_typeinf.tinfo_t, bool]:
tinfo_orig = tinfo.copy()
# deref pointer/array until we reach the actual type
depth = 0
while depth < 128:
if not tinfo.remove_ptr_or_array():
break
depth += 1
else:
msg = "max pointer depth reached"
raise LabSyncError(msg)
# if we're allowed to and this type is missing, add its base to local types
if not type_exists(tinfo) and add:
# add the type to local types
if tinfo.save_type() == 0:
tname = tinfo.get_type_name()
logger.warning(
f"the prototype for {name} used type {tname} that was not present in the TIL. "
"we silently added it to allow syncing" # noqa: COM812
)
return tinfo_orig, False
else:
# we can't use tname for deleted types (it raises UnicodeDecodeError)
tinfo_clean = tinfo.copy()
tinfo_clean.set_modifiers(0)
tname = tinfo_clean.dstr()
logger.warning(
f"the prototype for {name} used type {tname} that was not present in the TIL. "
"we failed to silently add it to allow syncing (perhaps a deleted type?)" # noqa: COM812
)
# TODO @TH: IDA has a bug where they can't parse _BOOL8 args, so we replace them.
# remove this flow after they fix it
bool8_realtype = ida_typeinf.BT_BOOL | ida_typeinf.BTMT_BOOL8
if tinfo.get_realtype() == bool8_realtype:
pass
elif type_exists(tinfo):
# if it's real present type, we're good
return tinfo_orig, False
# replace the type with an unknown type
tinfo_generic = ida_typeinf.tinfo_t()
assert tinfo_generic.create_simple_type(ida_typeinf.BT_UNKNOWN)
# set the original modifiers
tinfo_generic.set_modifiers(tinfo.get_modifiers())
# recrate the pointer depth on top of tinfo_generic
for _ in range(depth):
assert tinfo_generic.create_ptr(tinfo_generic)
return tinfo_generic, True
ftype = ida_typeinf.func_type_data_t()
assert tinfo.get_func_details(ftype, ida_typeinf.GTD_NO_ARGLOCS)
ftype.rettype, fixed = fix_non_present(ftype.rettype)
for i, argtype in enumerate(ftype):
ftype[i].type, arg_fixed = fix_non_present(argtype.type)
fixed |= arg_fixed
tinfo_new = ida_typeinf.tinfo_t()
assert tinfo_new.create_func(ftype)
return tinfo_new, fixed
def prototype(ea: int) -> str:
tinfo = ida_typeinf.tinfo_t()
if not ida_nalt.get_tinfo(tinfo, ea):
return None
name = ida_name.get_ea_name(ea, ida_name.GN_VISIBLE)
# replace non-present arguments in the prototype if relevant
tinfo_new, fixed = fix_non_present_arguments(name, tinfo)
if fixed:
ptype = ida_typeinf.print_tinfo(None, 0, 0, ida_typeinf.PRTYPE_1LINE, tinfo, None, None)
new_ptype = ida_typeinf.print_tinfo(None, 0, 0, ida_typeinf.PRTYPE_1LINE, tinfo_new, None,
None)
logger.warning(
f"replacing prototype for {name} because it uses types that are not present in the "
f"TIL from:\n\t{ptype!r}\nto:\n\t{new_ptype!r}" # noqa: COM812
)
if not ida_nalt.set_tinfo(ea, tinfo_new):
logger.warning(f"failed setting new prototype for {name}! skipping it")
return None
tinfo = tinfo_new
# generate the prototype to dump
if NORMALIZE_PROTOTYPES:
name = "FUNCTION"
# we have to remove special characters from the name, otherwise we'll have an issue applying
# the prototype afterwards (e.g. `__Foo.cxx_destruct_`)
allowed = r"_$" + string.digits + string.ascii_letters
pname = "".join(c if c in allowed else "_" for c in name)
return ida_typeinf.print_tinfo(None, 0, 0, ida_typeinf.PRTYPE_1LINE, tinfo, pname, None)
def dump_prototypes(
binary: SyncedBinary, storage: functioninliner.ClonesStorage) -> dict[int, str]:
d = {}
for ea in idautils.Functions():
if not binary.contains(ea):
continue
seg = ida_segment.getseg(ea)
seg_name = ida_segment.get_segm_name(seg)
# skip funcs that are in inlined chunks somehow (shouldn't happen)
if seg_name.startswith("inlined_"):
continue
# skip funcs that have been inlined
if ea in storage:
continue
ptype = prototype(ea)
if ptype:
dea = binary.ea2dump(ea)
d[dea] = ptype
return d
def dump(binary: SyncedBinary, types: netnode.Netnode) -> str:
storage = functioninliner.ClonesStorage()
storage.update_from_storage()
d = {
"version": 4,
"names": dump_names(binary, storage),
"inlined_funcs": dump_inlined_funcs(binary, storage),
# we have to dump prototypes before we dump local types because this may add new types to
# the TIL
"prototypes": dump_prototypes(binary, storage),
"local_types": dump_local_types(types),
}
return yaml.dump(
d, Dumper=LabSyncYAMLDumper, default_flow_style=False, sort_keys=True,
)
# IMPORT LOGIC
def update_names(
binary: SyncedBinary, storage: functioninliner.ClonesStorage, names: dict[int, str]) -> None:
# delete names if required
if REMOVE_MISSING_NAMES_AND_PROTOTYPES:
for dea in dump_names(binary, storage):
# delete name if unnamed in the new dict
if dea not in names:
ea = binary.dump2ea(dea)
msg = f"removing name from {ea:#x}"
logger.debug(msg)
success = ida_name.set_name(ea, "", ida_name.SN_NOWARN)
if not success:
if logger.getEffectiveLevel() > logging.DEBUG:
logger.warning("failed " + msg)
else:
logger.warning("removal failed!")
# update names
for dea, name in names.items():
ea = binary.dump2ea(dea)
cur_name = ida_name.get_name(ea)
if cur_name != name:
msg = f"renaming {ea:#x} from {cur_name!r} to {name!r}"
logger.debug(msg)
# check if the new name already exists in the database
cur_ea = ida_name.get_name_ea(ida_idaapi.BADADDR, name)
name_changed = False
try:
# if the new name is already in use in the IDB --
if cur_ea != ida_idaapi.BADADDR:
# verify that the repo also has a different name for the EA currently holding
# the new name
#
# perhaps we can even assert that this never happens
cur_dea = binary.ea2dump(cur_ea)
if cur_dea not in names:
logger.warning(
f"cannot rename {ea:#x} to {name!r} as this name already "
f"exists in the IDB for {cur_ea:#x}, and that EA doesn't "
"have a different name in the repo" # noqa: COM812
)
continue
# temporarily rename it to something else
msg2 = f"temporarily renaming {cur_ea:#x} away from {name!r}"
logger.debug("\t" + msg2)
success = ida_name.set_name(
cur_ea,
name + "_labsync_temp",
ida_name.SN_NOWARN | ida_name.SN_FORCE,
)
# handle temporary rename failure
if not success:
if logger.getEffectiveLevel() > logging.DEBUG:
logger.warning("failed " + msg2)
else:
logger.warning("\ttemporary rename failed!")
continue
# now do the actual rename
success = ida_name.set_name(ea, name, ida_name.SN_NOWARN)
# handle rename failure
if not success:
if logger.getEffectiveLevel() > logging.DEBUG:
logger.warning("failed " + msg)
else:
logger.warning("rename failed!")
continue
name_changed = True
finally:
# if we failed, undo the temporary rename if we did any
if cur_ea != ida_idaapi.BADADDR and not name_changed:
msg2 = f"undoing the temporarily rename of {cur_ea:#x}"
logger.debug("\t" + msg2)
success = ida_name.set_name(cur_ea, name, ida_name.SN_NOWARN)
# handle temporary rename undoing failure
if not success:
if logger.getEffectiveLevel() > logging.DEBUG:
logger.warning("failed " + msg2)
else:
logger.warning("\ttemporary rename undoing failed!")
def update_inlined_funcs(
binary: SyncedBinary, storage: functioninliner.ClonesStorage, funcs: list[int]) -> None:
cur = {ea for ea in storage if binary.contains(ea)}
new = set(map(binary.dump2ea, funcs))
undo = cur - new
do = new - cur
for ea in undo:
func = sark.Function(ea)
if func.ea != ea:
logger.warning(f"\tcannot undo inlining of {ea:#x} since it's not a function start!")
continue
msg = f"undoing inlining of {func.name}"
logger.debug(msg)
functioninliner.undo_inline_function(func)
for ea in do:
func = sark.Function(ea)
if func.ea != ea:
logger.warning(
f"not inlining function @ {ea:#x} since it's not a function start" # noqa: COM812
)
logger.debug(f"inlining {func.name}")
functioninliner.inline_function(func)
def _rename_local_type(tid: int, name: str) -> tuple[int, str]:
"""note: if name is in use by another local type, that local type will be removed"""
ordinal = ida_typeinf.get_tid_ordinal(tid)
assert ordinal
tinfo = ida_typeinf.tinfo_t()
assert tinfo.get_numbered_type(None, ordinal)
# TODO @TH: perhaps tinfo.rename_type can be used instead? found out about it later
err = tinfo.set_numbered_type(None, ordinal, ida_typeinf.NTF_REPLACE, name)
errstr = ida_typeinf.tinfo_errstr(err)
return err, errstr
def rename_local_type(
cur_name: str, name: str, types: netnode.Netnode, uuids: dict[int, str],
) -> None:
msg = f"renaming local type {cur_name!r} to {name!r}"
logger.debug(msg)
# resolve the type we're changing
tid = ida_typeinf.get_named_type_tid(cur_name)
assert tid != ida_idaapi.BADADDR
# check if the new name is in use
cur_tid = ida_typeinf.get_named_type_tid(name)
name_changed = False
try:
# if the new name is already in use in the IDB --
if cur_tid != ida_idaapi.BADADDR:
# assert that the repo also has a different name for the type currently holding the new
# name
#
# this is an assertion because if it's missing from the repo we should've already
# deleted it
#
# also, we don't actually verify that the name since we already verified beforehand
# that there are no duplicate names
cur_uuid = types[cur_tid]
assert cur_uuid in uuids
# temporarily rename it to something else
msg2 = f"temporarily renaming local type {name!r}"
logger.debug("\t" + msg2)
err, errstr = _rename_local_type(cur_tid, name + "_labsync_temp")
# handle temporary rename failure
if err:
if logger.getEffectiveLevel() > logging.DEBUG:
logger.warning("failed " + msg2 + f": {errstr}")
else:
logger.warning(f"\ttemporary rename failed: {errstr}")
return False
# now do the actual rename
err, errstr = _rename_local_type(tid, name)
# handle rename failure
if err:
if logger.getEffectiveLevel() > logging.DEBUG:
logger.warning("failed " + msg + f": {errstr}")
else:
logger.warning(f"rename failed: {errstr}")
return False
name_changed = True
finally:
# if we failed, undo the temporary rename if we did any
if cur_tid != ida_idaapi.BADADDR and not name_changed:
msg2 = f"undoing the temporarily rename of local type {name!r}"
logger.debug("\t" + msg2)
err, errstr = _rename_local_type(cur_tid, name)
# handle temporary rename undoing failure
if err:
if logger.getEffectiveLevel() > logging.DEBUG:
logger.warning("failed " + msg2 + f": {errstr}")
else:
logger.warning(f"\ttemporary rename undoing failed: {errstr}")
return bool(err)
def parse_local_types(nhdr: str) -> Generator[tuple[str, str, str, str]]:
# split according to empty lines
decls = re.split(r"\n\n", nhdr)
for decl in decls:
decl = decl.strip()
# extract the uuid of the type
uuid_line, decl = decl.split("\n", maxsplit=1)
r = parse.parse(LOCAL_TYPES_COMMENT_FMT, uuid_line)
if not r:
msg = f"failed to extract uuid from local type uuid line:\n{uuid_line}"
raise LabSyncError(msg)
decl_uuid = r.fixed[0]
# extract the name of the type and generate a forward declaration for it
name, decl_type = decl_to_name_and_type(decl)
yield name, decl_uuid, decl, decl_type
def update_local_types(nhdr: str, types: netnode.Netnode) -> None:
# parse type declaration names
name2decl = {}
uuids = {}
decls = []
fdecls = []
typedefs = []
for name, decl_uuid, decl, decl_type in parse_local_types(nhdr):
# make sure it's unique, mostly for sanity purposes
if name in name2decl:
if (name2decl[name] == decl and
uuids.get(decl_uuid) == name):
# duplicate local type with same decl and UUID. probably accidentally copied from
# both sides during conflict resolution. we'll skip the redundant copy
continue
msg = f"found two local type declarations with the same name: {name}"
raise LabSyncError(msg)
name2decl[name] = decl
# remember the name for each uuid
uuids[decl_uuid] = name
# accumulate
if decl_type in {"struct", "union", "enum", "class"}:
decls.append(decl)
fdecl = f"{decl_type} {name};"
fdecls.append(fdecl)
elif decl_type == "typedef":
typedefs.append(decl)
else:
msg = f"found unexpected kind of local type:\n{decl}"
raise LabSyncError(msg)
# remove local types if required
for tid, decl_uuid in list(types.items()):
if decl_uuid not in uuids:
name = ida_typeinf.get_tid_name(tid)
logger.debug(f"removing local type {name!r}")
ida_typeinf.del_named_type(None, name, ida_typeinf.NTF_TYPE)
del types[tid]
# rename local types if required
# create a mapping from uuid to type name in our IDB
cur_uuid_to_name = {u: ida_typeinf.get_tid_name(t) for t, u in types.items()}
for decl_uuid, name in uuids.items():
# skip if uuid doesn't exist (this is a new type) or name didn't change
cur_name = cur_uuid_to_name.get(decl_uuid)
if not cur_name or cur_name == name:
continue
# do the renaming
rename_local_type(cur_name, name, types, uuids)
# create a reordered header that that should be parsable with regards to forward declarations
hdr = "\n".join(fdecls) + "\n\n" + "\n".join(typedefs) + "\n\n" + "\n\n".join(decls)
# iteratively try to load the header as long as dependencies get resolved
#
# TODO @TH: originally we didn't move the typedefs to before the decls, so honestly I think
# that now there should always be just one iteration here. we should probably verify
# that and remove the loop here afterwards
last_n_errors = float("inf")
iters = 1
while iters < len(name2decl) + 1:
# parse some more local types
n_errors = ida_typeinf.parse_decls(None, hdr, None, ida_typeinf.HTI_DCL)
logger.debug(f"loaded local types with {n_errors} errors")
# add new uuids. we do this on every iteration in case we will eventually bail out --
# we don't want to have added new types without keeping their uuids
for decl_uuid, name in uuids.items():
tid = ida_typeinf.get_named_type_tid(name)
if tid != ida_idaapi.BADADDR:
if tid not in types:
types[tid] = decl_uuid
else:
assert types[tid] == decl_uuid
# stop if there are no more errors or if we didn't add anything on this iteration
if n_errors == 0 or n_errors >= last_n_errors:
break
last_n_errors = n_errors
iters += 1
else:
msg = "local type loading took more than it makes sense. aborting"
raise LabSyncError(msg)
logger.debug(
f"finished loading local types with {n_errors} errors after {iters} iterations "
f"({len(name2decl)} types)" # noqa: COM812
)
if n_errors:
# IDA SDK doesn't properly export an interface for printer_t so we can't get the actual
# errors :/
fd, hdr_path = tempfile.mkstemp(suffix=".h", text=True)
os.write(fd, hdr.encode("latin1"))
os.close(fd)
logger.error(
"run the following in IDC shell to see the local types parsing errors:\n"
f'\tparse_decls("{hdr_path}", PT_FILE)' # noqa: COM812
)
msg = f"failed to parse local types ({n_errors} errors)"
raise LabSyncError(msg)
# in case loading the local types resulted in a new type being created, we might've encountered
# a bug where IDA recreates an anonymous local type for an unnamed embedded subtype
#
# in that case, look for and delete dangling anonymous local types that should've been left
new_names = set(local_types())
if set(name2decl.keys()) != new_names:
for name in new_names:
tinfo = ida_typeinf.tinfo_t()
assert tinfo.get_named_type(None, name)
# check if anonymous
if not tinfo.is_anonymous_udt():
continue
# check if it has any xrefs
tid = tinfo.get_tid()
if (ida_xref.get_first_cref_to(tid) != ida_idaapi.BADADDR or
ida_xref.get_first_dref_to(tid) != ida_idaapi.BADADDR):
continue
# check if it's referenced by any typedef
used_by_typedef = False
any_tinfo = ida_typeinf.tinfo_t()
for any_name in local_types():
assert any_tinfo.get_named_type(None, any_name)
if not any_tinfo.is_typedef():
continue
if any_tinfo.get_next_type_name() != name:
continue
used_by_typedef = True
break