-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathida_analyze_util.py
More file actions
9028 lines (8096 loc) · 316 KB
/
ida_analyze_util.py
File metadata and controls
9028 lines (8096 loc) · 316 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
#!/usr/bin/env python3
"""Shared utility helpers for IDA analyze scripts."""
import asyncio
import json
import math
import os
import re
import tempfile
import textwrap
from pathlib import Path
try:
import yaml
except ImportError:
yaml = None
try:
from ida_llm_utils import (
call_llm_text,
create_openai_client,
normalize_optional_effort,
normalize_optional_temperature,
)
except Exception:
call_llm_text = None
create_openai_client = None
normalize_optional_effort = None
normalize_optional_temperature = None
# Combined vtable lookup + entry reading script for IDA py_eval.
# Merges logic from get-vtable-address/SKILL.md and write-vtable-as-yaml/SKILL.md.
# Uses CLASS_NAME_PLACEHOLDER for substitution (avoids brace-escaping issues).
# Returns JSON via the 'result' variable.
_VTABLE_PY_EVAL_TEMPLATE = r'''
import ida_auto, ida_bytes, ida_name, idaapi, ida_segment, idautils, idc, json
class_name = CLASS_NAME_PLACEHOLDER
candidate_symbols = CANDIDATE_SYMBOLS_PLACEHOLDER
debug_enabled = DEBUG_PLACEHOLDER
ptr_size = 8 if idaapi.inf_is_64bit() else 4
vtable_start = None
vtable_symbol = ""
is_linux = False
def _resolve_windows_rtti_symbol(symbol_name, fallback_vtable_symbol=None):
col_addr = ida_name.get_name_ea(idaapi.BADADDR, symbol_name)
if col_addr == idaapi.BADADDR:
return None
rdata_seg = ida_segment.get_segm_by_name(".rdata")
for ref in idautils.DataRefsTo(col_addr):
if rdata_seg and not (rdata_seg.start_ea <= ref < rdata_seg.end_ea):
continue
vtable_start = ref + ptr_size
sym = (
ida_name.get_name(vtable_start)
or fallback_vtable_symbol
or ("vftable@" + hex(vtable_start))
)
return (vtable_start, sym, False)
return None
def _try_direct_symbol(symbol_name):
if not symbol_name:
return None
addr = ida_name.get_name_ea(idaapi.BADADDR, symbol_name)
if addr == idaapi.BADADDR:
return None
if symbol_name.startswith("_ZTV"):
linux_address_point_offset = 2 * ptr_size
return (
addr + linux_address_point_offset,
symbol_name + " + " + hex(linux_address_point_offset),
True,
)
if symbol_name.startswith("??_R4"):
return _resolve_windows_rtti_symbol(symbol_name)
return (addr, symbol_name, False)
def _debug(message):
if debug_enabled:
print(message)
def _resolve_vtable_func_start(ptr_value):
func = idaapi.get_func(ptr_value)
if func is not None and func.start_ea <= ptr_value < func.end_ea:
return func.start_ea
flags = ida_bytes.get_full_flags(ptr_value)
if not ida_bytes.is_code(flags):
try:
ida_bytes.del_items(ptr_value, ida_bytes.DELIT_SIMPLE, ptr_size)
except Exception as exc:
_debug(
f" Preprocess vtable: del_items failed for {hex(ptr_value)}: {exc}"
)
try:
idc.create_insn(ptr_value)
except Exception as exc:
_debug(
f" Preprocess vtable: create_insn failed for {hex(ptr_value)}: {exc}"
)
try:
idaapi.add_func(ptr_value)
except Exception as exc:
_debug(f" Preprocess vtable: add_func failed for {hex(ptr_value)}: {exc}")
try:
ida_auto.auto_wait()
except Exception:
pass
func = idaapi.get_func(ptr_value)
if func is None:
_debug(
f" Preprocess vtable: no function covers {hex(ptr_value)} after recovery"
)
return None
if not (func.start_ea <= ptr_value < func.end_ea):
_debug(
" Preprocess vtable: recovered function "
f"{hex(func.start_ea)} does not cover {hex(ptr_value)}"
)
return None
return func.start_ea
# Workaround: py_eval uses exec(code, exec_globals, exec_locals) with separate
# dicts. Top-level variables land in exec_locals, but nested functions only see
# exec_globals. Copy everything into globals so functions can resolve ptr_size,
# debug_enabled, _debug, etc.
globals().update(locals())
for symbol_name in candidate_symbols:
_found = _try_direct_symbol(symbol_name)
if _found:
vtable_start, vtable_symbol, is_linux = _found
break
# Direct symbol: Windows ??_7ClassName@@6B@
if vtable_start is None:
_found = _try_direct_symbol("??_7" + class_name + "@@6B@")
if _found:
vtable_start, vtable_symbol, is_linux = _found
# Direct symbol: Linux _ZTV<len>ClassName
if vtable_start is None:
_found = _try_direct_symbol("_ZTV" + str(len(class_name)) + class_name)
if _found:
vtable_start, vtable_symbol, is_linux = _found
# RTTI fallback: Windows ??_R4ClassName@@6B@
if vtable_start is None:
col_name = "??_R4" + class_name + "@@6B@"
_found = _resolve_windows_rtti_symbol(
col_name,
"??_7" + class_name + "@@6B@",
)
if _found:
is_linux = False
vtable_start, vtable_symbol, is_linux = _found
# RTTI fallback: Linux _ZTI<len>ClassName
if vtable_start is None:
ti_name = "_ZTI" + str(len(class_name)) + class_name
ti_addr = ida_name.get_name_ea(idaapi.BADADDR, ti_name)
if ti_addr != idaapi.BADADDR:
is_linux = True
for ref in idautils.DataRefsTo(ti_addr):
ott = ida_bytes.get_qword(ref - ptr_size) if ptr_size == 8 else ida_bytes.get_dword(ref - ptr_size)
if ott == 0:
vtable_start = ref + ptr_size
ztv_addr = ref - ptr_size
ztv_name = ida_name.get_name(ztv_addr) or ("_ZTV" + str(len(class_name)) + class_name)
vtable_symbol = ztv_name + " + 0x10"
break
if vtable_start is None:
result = json.dumps(None)
else:
vtable_seg = ida_segment.getseg(vtable_start)
entries = {}
count = 0
for i in range(1000):
ea = vtable_start + i * ptr_size
if is_linux and i > 0:
name = ida_name.get_name(ea)
if name and (name.startswith("_ZTV") or name.startswith("_ZTI")):
break
ptr_value = ida_bytes.get_qword(ea) if ptr_size == 8 else ida_bytes.get_dword(ea)
if ptr_value == 0:
if is_linux:
entries[count] = hex(ptr_value)
count += 1
continue
else:
break
if ptr_value == 0xFFFFFFFFFFFFFFFF:
break
target_seg = ida_segment.getseg(ptr_value)
if not target_seg:
break
# If an entry points back into the vtable's own segment (.rdata/.rodata),
# it is metadata or unrelated data, not a virtual function.
if vtable_seg and (vtable_seg.start_ea <= ptr_value < vtable_seg.end_ea):
break
if not (target_seg.perm & ida_segment.SEGPERM_EXEC):
break
func_start = _resolve_vtable_func_start(ptr_value)
if func_start is None:
break
entries[count] = hex(func_start)
count += 1
continue
size_in_bytes = count * ptr_size
result = json.dumps({
"vtable_class": class_name,
"vtable_symbol": vtable_symbol,
"vtable_va": hex(vtable_start),
"vtable_size": hex(size_in_bytes),
"vtable_numvfunc": count,
"vtable_entries": entries
})
'''
DEFAULT_IDA_STRING_MIN_LENGTH = 4
IDA_STRING_MIN_LENGTH_ENV_VAR = "CS2VIBE_STRING_MIN_LENGTH"
IDA_STRING_SETUP_STATE_NODE = "$CS2VIBE_STRING_SETUP_STATE"
IDA_STRING_SETUP_STATE_VERSION = 1
IDA_STRING_SETUP_STRTYPES_LABEL = "STRTYPE_C"
_IDA_STRING_MIN_LENGTH_AUTO = object()
def _coerce_ida_string_min_length(value):
try:
min_length = int(str(value).strip())
except (TypeError, ValueError):
return DEFAULT_IDA_STRING_MIN_LENGTH
if min_length < 1:
return DEFAULT_IDA_STRING_MIN_LENGTH
return min_length
def _resolve_ida_string_min_length_config():
raw_min_length = os.getenv(IDA_STRING_MIN_LENGTH_ENV_VAR)
if raw_min_length is None:
return None
if not str(raw_min_length).strip():
return None
return _coerce_ida_string_min_length(raw_min_length)
def _resolve_ida_string_min_length():
resolved = _resolve_ida_string_min_length_config()
if resolved is None:
return DEFAULT_IDA_STRING_MIN_LENGTH
return resolved
def _resolve_ida_string_min_length_for_py_lines(min_length):
if min_length is _IDA_STRING_MIN_LENGTH_AUTO:
return _resolve_ida_string_min_length_config()
if min_length is None:
return None
return _coerce_ida_string_min_length(min_length)
def _build_ida_strings_enumerator_py_lines(
*,
min_length=_IDA_STRING_MIN_LENGTH_AUTO,
strings_var_name: str = "strings",
) -> list[str]:
"""Return py_eval code lines for IDA string enumeration.
``None`` min_length means using the IDB's current string-list state without
calling ``Strings.setup``. Integer min_length emits a netnode-guarded setup.
"""
resolved_min_length = _resolve_ida_string_min_length_for_py_lines(min_length)
lines = [
f"{strings_var_name} = idautils.Strings(default_setup=False)",
]
if resolved_min_length is None:
return lines
expected_state = {
"version": IDA_STRING_SETUP_STATE_VERSION,
"minlen": resolved_min_length,
"strtypes": IDA_STRING_SETUP_STRTYPES_LABEL,
}
return [
"import ida_netnode, json",
*lines,
f"CS2VIBE_STRING_SETUP_STATE_NODE = {IDA_STRING_SETUP_STATE_NODE!r}",
"def _cs2vibe_string_setup_node():",
" return ida_netnode.netnode(CS2VIBE_STRING_SETUP_STATE_NODE, 0, True)",
"def _cs2vibe_read_string_setup_state():",
" try:",
" raw = _cs2vibe_string_setup_node().valobj()",
" if isinstance(raw, bytes):",
" raw = raw.decode('utf-8', errors='ignore')",
" if raw is None or raw == '':",
" return None",
" return json.loads(str(raw))",
" except Exception:",
" return None",
"def _cs2vibe_write_string_setup_state(state):",
" try:",
" payload = json.dumps(state, sort_keys=True)",
" _cs2vibe_string_setup_node().set(payload)",
" except Exception:",
" pass",
f"expected_state = {expected_state!r}",
"globals().update(locals())",
"if _cs2vibe_read_string_setup_state() != expected_state:",
(
f" {strings_var_name}.setup("
"strtypes=[ida_nalt.STRTYPE_C], "
f"minlen={resolved_min_length}"
")"
),
" _cs2vibe_write_string_setup_state(expected_state)",
]
def _build_ida_strings_setup_py_lines(
*,
min_length=_IDA_STRING_MIN_LENGTH_AUTO,
strings_var_name: str = "strings",
) -> list[str]:
return _build_ida_strings_enumerator_py_lines(
min_length=min_length,
strings_var_name=strings_var_name,
)
def _build_ida_exact_string_index_py_lines(
target_texts_var_name="target_strings",
result_var_name="exact_string_hits",
min_length=_IDA_STRING_MIN_LENGTH_AUTO,
*,
target_strings_var_name=None,
hits_var_name=None,
):
"""Return py_eval code lines that build `{text: [ea_list]}` exact-hit index.
调用方需先在 py_eval 代码中导入 ``idautils`` 与 ``ida_nalt``;本 helper 在
显式 minlen 配置时会额外注入 ``ida_netnode`` 与 ``json`` import。
"""
if target_strings_var_name is not None:
target_texts_var_name = target_strings_var_name
if hits_var_name is not None:
result_var_name = hits_var_name
return [
f"{result_var_name} = {{text: [] for text in {target_texts_var_name} if text}}",
*_build_ida_strings_enumerator_py_lines(min_length=min_length),
"for item in strings:",
" try:",
" text = str(item)",
" ea = int(item.ea)",
" except Exception:",
" continue",
f" if text in {result_var_name}:",
f" {result_var_name}[text].append(ea)",
]
def parse_mcp_result(result):
"""Parse CallToolResult content to a Python object."""
if result.content:
text = result.content[0].text
try:
return json.loads(text)
except (json.JSONDecodeError, TypeError):
return text
return None
def _normalize_mangled_class_names(mangled_class_names, debug=False):
if mangled_class_names is None:
return {}
if not isinstance(mangled_class_names, dict):
if debug:
print(
" Preprocess: mangled_class_names must be a dict, got "
f"{type(mangled_class_names).__name__}"
)
return None
normalized = {}
for class_name, aliases in mangled_class_names.items():
if not isinstance(class_name, str) or not class_name:
if debug:
print(
" Preprocess: invalid mangled_class_names key: "
f"{class_name!r}"
)
return None
if not isinstance(aliases, (list, tuple)):
if debug:
print(
" Preprocess: aliases for "
f"{class_name} must be a list/tuple"
)
return None
normalized_aliases = []
for alias in aliases:
if not isinstance(alias, str) or not alias:
if debug:
print(
" Preprocess: invalid alias for "
f"{class_name}: {alias!r}"
)
return None
normalized_aliases.append(alias)
normalized[class_name] = normalized_aliases
return normalized
def _normalize_generate_yaml_desired_fields(generate_yaml_desired_fields, debug=False):
if not generate_yaml_desired_fields:
if debug:
print(" Preprocess: missing generate_yaml_desired_fields")
return None
true_directive_fields = (
"gv_sig_allow_across_function_boundary",
"func_sig_allow_across_function_boundary",
"vfunc_sig_allow_across_function_boundary",
"offset_sig_allow_across_function_boundary",
)
normalized = {}
for spec in generate_yaml_desired_fields:
if not isinstance(spec, (tuple, list)) or len(spec) != 2:
if debug:
print(f" Preprocess: invalid desired-fields spec: {spec}")
return None
symbol_name, desired_fields = spec
if not isinstance(symbol_name, str) or not symbol_name:
if debug:
print(f" Preprocess: invalid desired-fields symbol: {symbol_name}")
return None
if symbol_name in normalized:
if debug:
print(f" Preprocess: duplicated desired-fields symbol: {symbol_name}")
return None
if not isinstance(desired_fields, (tuple, list)) or not desired_fields:
if debug:
print(f" Preprocess: empty desired-fields for {symbol_name}")
return None
desired_output_fields = []
generation_options = {}
def _handle_true_directive(field_name, directive_name):
if field_name == directive_name:
if debug:
print(
f" Preprocess: bare {directive_name} field is "
f"not allowed for {symbol_name}"
)
return None
if not field_name.startswith(f"{directive_name}:"):
return False
if directive_name in generation_options:
if debug:
print(
f" Preprocess: duplicated {directive_name} "
f"directive for {symbol_name}"
)
return None
value_text = field_name.split(":", 1)[1].strip().lower()
if value_text != "true":
if debug:
print(
f" Preprocess: invalid {directive_name} value "
f"for {symbol_name}: {value_text}"
)
return None
desired_output_fields.append(directive_name)
generation_options[directive_name] = True
return True
for field_name in desired_fields:
if not isinstance(field_name, str) or not field_name:
if debug:
print(f" Preprocess: invalid desired field list for {symbol_name}")
return None
if field_name == "vfunc_sig_max_match":
if debug:
print(
f" Preprocess: bare vfunc_sig_max_match field is "
f"not allowed for {symbol_name}"
)
return None
if field_name.startswith("vfunc_sig_max_match:"):
if "vfunc_sig_max_match" in generation_options:
if debug:
print(
f" Preprocess: duplicated vfunc_sig_max_match "
f"directive for {symbol_name}"
)
return None
max_match_text = field_name.split(":", 1)[1]
try:
max_match = int(max_match_text)
except ValueError:
if debug:
print(
f" Preprocess: invalid vfunc_sig_max_match "
f"value for {symbol_name}: {max_match_text}"
)
return None
if max_match <= 0:
if debug:
print(
f" Preprocess: invalid vfunc_sig_max_match "
f"value for {symbol_name}: {max_match_text}"
)
return None
desired_output_fields.append("vfunc_sig_max_match")
generation_options["vfunc_sig_max_match"] = max_match
continue
handled_true_directive = False
for directive_name in true_directive_fields:
directive_parse_result = _handle_true_directive(
field_name,
directive_name,
)
if directive_parse_result is None:
return None
if directive_parse_result:
handled_true_directive = True
break
if handled_true_directive:
continue
desired_output_fields.append(field_name)
if "vfunc_sig_max_match" in generation_options and "vfunc_sig" not in desired_output_fields:
if debug:
print(
f" Preprocess: vfunc_sig_max_match requires vfunc_sig "
f"for {symbol_name}"
)
return None
normalized[symbol_name] = {
"desired_output_fields": desired_output_fields,
"generation_options": generation_options,
}
return normalized
def _build_target_kind_map(
func_names,
gv_names,
patch_names,
struct_member_names,
vtable_class_names,
inherit_vfuncs,
func_xrefs_map,
debug=False,
):
target_kind_map = {}
def _register(symbol_name, target_kind):
existing_kind = target_kind_map.get(symbol_name)
if existing_kind is not None and existing_kind != target_kind:
if debug:
print(
f" Preprocess: symbol kind conflict for {symbol_name}: "
f"{existing_kind} vs {target_kind}"
)
return False
target_kind_map[symbol_name] = target_kind
return True
for func_name in list(func_names) + list(func_xrefs_map):
if not _register(func_name, "func"):
return None
for inherit_spec in inherit_vfuncs:
if not _register(inherit_spec[0], "func"):
return None
for gv_name in gv_names:
if not _register(gv_name, "gv"):
return None
for patch_name in patch_names:
if not _register(patch_name, "patch"):
return None
for struct_member_name in struct_member_names:
if not _register(struct_member_name, "struct_member"):
return None
for class_name in vtable_class_names:
if not _register(class_name, "vtable"):
return None
return target_kind_map
def _get_mangled_class_aliases(mangled_class_names, class_name):
aliases = (mangled_class_names or {}).get(class_name, [])
if not aliases:
return None
return list(aliases)
_VTABLE_ARTIFACT_STEM_RE = re.compile(r"_vtable(?:\d+)?$")
def _is_vtable_artifact_stem(vtable_name):
return isinstance(vtable_name, str) and bool(
_VTABLE_ARTIFACT_STEM_RE.search(vtable_name)
)
def _normalize_vtable_artifact_stem(vtable_name):
if _is_vtable_artifact_stem(vtable_name):
return vtable_name
return f"{vtable_name}_vtable"
def _build_vtable_yaml_path(binary_dir, vtable_name, platform):
artifact_stem = _normalize_vtable_artifact_stem(vtable_name)
return os.path.join(
os.fspath(binary_dir),
f"{artifact_stem}.{platform}.yaml",
)
def build_remote_text_export_py_eval(
*,
output_path,
producer_code,
content_var="payload_text",
format_name="text",
):
"""Build a py_eval script that writes large text to disk and returns a small ack."""
output_path_str = os.fspath(output_path)
if not os.path.isabs(output_path_str):
raise ValueError(f"output_path must be absolute, got {output_path_str!r}")
if not str(producer_code).strip():
raise ValueError("producer_code cannot be empty")
if not str(content_var).strip():
raise ValueError("content_var cannot be empty")
producer_block = textwrap.indent(str(producer_code).rstrip(), " ")
return (
"import json, os, traceback\n"
f"output_path = {output_path_str!r}\n"
f"format_name = {str(format_name)!r}\n"
"tmp_path = output_path + '.tmp'\n"
"def _truncate_text(value, limit=800):\n"
" text = '' if value is None else str(value)\n"
" return text if len(text) <= limit else text[:limit] + ' [truncated]'\n"
"try:\n"
" if not os.path.isabs(output_path):\n"
" raise ValueError(f'output_path must be absolute: {output_path}')\n"
f"{producer_block}\n"
f" payload_text = str({content_var})\n"
" parent_dir = os.path.dirname(output_path)\n"
" if parent_dir:\n"
" os.makedirs(parent_dir, exist_ok=True)\n"
" with open(tmp_path, 'w', encoding='utf-8') as handle:\n"
" handle.write(payload_text)\n"
" os.replace(tmp_path, output_path)\n"
" result = json.dumps({\n"
" 'ok': True,\n"
" 'output_path': output_path,\n"
" 'bytes_written': len(payload_text.encode('utf-8')),\n"
" 'format': format_name,\n"
" })\n"
"except Exception as exc:\n"
" try:\n"
" if os.path.exists(tmp_path):\n"
" os.unlink(tmp_path)\n"
" except Exception:\n"
" pass\n"
" result = json.dumps({\n"
" 'ok': False,\n"
" 'output_path': output_path,\n"
" 'error': _truncate_text(exc),\n"
" 'traceback': _truncate_text(traceback.format_exc()),\n"
" })\n"
)
def _build_vtable_py_eval(class_name, symbol_aliases=None, debug=False):
"""Build the vtable py_eval script for the given class name."""
return (
_VTABLE_PY_EVAL_TEMPLATE
.replace("CLASS_NAME_PLACEHOLDER", json.dumps(class_name))
.replace(
"CANDIDATE_SYMBOLS_PLACEHOLDER",
json.dumps(list(symbol_aliases or [])),
)
.replace("DEBUG_PLACEHOLDER", "True" if debug else "False")
)
FUNC_YAML_ORDER = [
"func_name",
"func_va",
"func_rva",
"func_size",
"func_sig",
"func_sig_allow_across_function_boundary",
"vtable_name",
"vfunc_offset",
"vfunc_index",
"vfunc_sig",
"vfunc_sig_max_match",
"vfunc_sig_allow_across_function_boundary",
]
GV_YAML_ORDER = [
"gv_name",
"gv_va",
"gv_rva",
"gv_sig",
"gv_sig_va",
"gv_inst_offset",
"gv_inst_length",
"gv_inst_disp",
"gv_sig_allow_across_function_boundary",
]
VTABLE_YAML_ORDER = [
"vtable_class",
"vtable_symbol",
"vtable_va",
"vtable_rva",
"vtable_size",
"vtable_numvfunc",
"vtable_entries",
]
PATCH_YAML_ORDER = ["patch_name", "patch_sig", "patch_bytes"]
STRUCT_MEMBER_YAML_ORDER = [
"struct_name",
"member_name",
"offset",
"size",
"offset_sig",
"offset_sig_disp",
"offset_sig_allow_across_function_boundary",
]
TARGET_KIND_TO_FIELD_ORDER = {
"func": FUNC_YAML_ORDER,
"gv": GV_YAML_ORDER,
"vtable": VTABLE_YAML_ORDER,
"patch": PATCH_YAML_ORDER,
"struct_member": STRUCT_MEMBER_YAML_ORDER,
}
TARGET_KIND_TO_FIELD_SET = {
kind: set(field_order)
for kind, field_order in TARGET_KIND_TO_FIELD_ORDER.items()
}
def _build_ordered_yaml_payload(data, ordered_keys):
payload = {}
for key in ordered_keys:
if key not in data:
continue
value = data[key]
if key == "vtable_entries":
normalized_entries = {
int(entry_index): str(entry_value)
for entry_index, entry_value in value.items()
}
payload[key] = dict(sorted(normalized_entries.items()))
continue
if key.endswith("_va") or key.endswith("_rva") or key.endswith("_size"):
payload[key] = str(value)
continue
payload[key] = value
return payload
def _assemble_symbol_payload(symbol_name, target_kind, candidate_data, desired_fields_map, debug=False):
desired_field_spec = desired_fields_map.get(symbol_name)
if desired_field_spec is None:
if debug:
print(f" Preprocess: missing desired-fields entry for {symbol_name}")
return None
desired_fields = desired_field_spec["desired_output_fields"]
payload = {}
for field_name in desired_fields:
if field_name not in candidate_data:
if debug:
print(
f" Preprocess: missing desired field {field_name} "
f"for {symbol_name}"
)
return None
payload[field_name] = candidate_data[field_name]
ordered_keys = TARGET_KIND_TO_FIELD_ORDER[target_kind]
return _build_ordered_yaml_payload(payload, ordered_keys)
def _is_slot_only_inherit_vfunc_fields(desired_fields):
slot_only_fields = {
"func_name",
"vtable_name",
"vfunc_offset",
"vfunc_index",
}
return len(desired_fields) == len(slot_only_fields) and set(desired_fields) == slot_only_fields
def _build_inherited_vfunc_name(
base_vfunc_name,
base_vtable_name,
inherit_vtable_class,
fallback_name,
):
func_name = fallback_name
base_artifact_stem = Path(str(base_vfunc_name)).name
if base_vtable_name and base_artifact_stem.startswith(base_vtable_name + "_"):
method_suffix = base_artifact_stem[len(base_vtable_name) + 1:]
func_name = f"{inherit_vtable_class}_{method_suffix}"
return func_name
def write_vtable_yaml(path, data):
"""Write vtable YAML matching the format produced by write-vtable-as-yaml skill."""
if yaml is None:
raise RuntimeError("PyYAML is required to write vtable YAML")
payload = _build_ordered_yaml_payload(data, VTABLE_YAML_ORDER)
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump(
payload,
f,
sort_keys=False,
default_flow_style=False,
allow_unicode=False,
)
def write_func_yaml(path, data):
"""Write function/vfunc YAML with the same key set and key order as write-func-as-yaml; scalar quoting/styling is handled by PyYAML."""
if yaml is None:
raise RuntimeError("PyYAML is required to write function YAML")
payload = _build_ordered_yaml_payload(data, FUNC_YAML_ORDER)
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump(
payload,
f,
sort_keys=False,
default_flow_style=False,
allow_unicode=False,
)
def write_gv_yaml(path, data):
"""Write global-variable YAML with the same key set and key order as write-globalvar-as-yaml; scalar quoting/styling is handled by PyYAML."""
if yaml is None:
raise RuntimeError("PyYAML is required to write global-variable YAML")
payload = _build_ordered_yaml_payload(data, GV_YAML_ORDER)
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump(
payload,
f,
sort_keys=False,
default_flow_style=False,
allow_unicode=False,
)
def write_patch_yaml(path, data):
"""Write patch YAML with stable key order."""
if yaml is None:
raise RuntimeError("PyYAML is required to write patch YAML")
payload = _build_ordered_yaml_payload(data, PATCH_YAML_ORDER)
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump(
payload,
f,
sort_keys=False,
default_flow_style=False,
allow_unicode=False,
)
def write_struct_offset_yaml(path, data):
"""Write struct-member offset YAML matching write-structoffset-as-yaml key order."""
if yaml is None:
raise RuntimeError("PyYAML is required to write struct offset YAML")
payload = _build_ordered_yaml_payload(data, STRUCT_MEMBER_YAML_ORDER)
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump(
payload,
f,
sort_keys=False,
default_flow_style=False,
allow_unicode=False,
)
def _empty_llm_decompile_result():
return {
"found_vcall": [],
"found_call": [],
"found_funcptr": [],
"found_gv": [],
"found_struct_offset": [],
}
def _normalize_llm_retry_attempts(value, default=3):
try:
attempts = int(value)
except (TypeError, ValueError):
attempts = int(default)
return max(1, attempts)
def _normalize_llm_retry_delay(value, default, minimum=0.0):
try:
delay = float(value)
except (TypeError, ValueError):
delay = float(default)
if delay < minimum:
return minimum
return delay
def _extract_llm_error_status_code(exc):
for source in (exc, getattr(exc, "response", None)):
if source is None:
continue
status_code = getattr(source, "status_code", None)
if status_code is None:
continue
try:
return int(status_code)
except (TypeError, ValueError):
continue
return None
def _is_transient_llm_error(exc):
status_code = _extract_llm_error_status_code(exc)
if status_code == 429 or (
status_code is not None and 500 <= status_code < 600
):
return True
message = str(exc or "").lower()
retryable_fragments = (
"transport received error",
"timeout",
"timed out",
"read timeout",
"rate limit",
"rate_limit",
"too many requests",
"http 429",
"status 429",
"status_code=429",
" 429",
"http 500",
"http 502",
"http 503",
"http 504",
"status 500",
"status 502",
"status 503",
"status 504",
"status_code=500",
"status_code=502",
"status_code=503",
"status_code=504",
" 500",
" 502",