Repository navigation
Expand file tree
/
Copy pathlifter.py
More file actions
2838 lines (2601 loc) · 120 KB
/
Copy pathlifter.py
File metadata and controls
2838 lines (2601 loc) · 120 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
"""
x86 → C instruction lifter.
Translates individual x86 instructions (and common multi-instruction
patterns like cmp+jcc) into C statements using the recomp_types.h macros.
Register model:
- eax, ebx, ecx, edx, esi, edi, ebp: uint32_t locals
- esp: uint32_t local (stack pointer)
- FPU: shared double g_fp_stack[8] with g_fp_top index
Memory model:
- MEM8/MEM16/MEM32 macros for memory access at flat addresses
- Xbox data sections mapped at original VAs
"""
import struct
from .disasm import Instruction, Operand
from .config import is_code_address, is_data_address, va_to_file_offset
# ── Operand formatting ──────────────────────────────────────
def _fmt_reg(name, size=4):
"""Format a register name as a C expression."""
if not name:
return "0"
# Segment registers → constants
if name in ("fs", "gs", "cs", "ds", "es", "ss"):
return f"0 /* seg:{name} */"
# Map sub-registers to expressions on 32-bit locals
SUB_REGS = {
"al": "LO8(eax)", "ah": "HI8(eax)", "ax": "LO16(eax)",
"bl": "LO8(ebx)", "bh": "HI8(ebx)", "bx": "LO16(ebx)",
"cl": "LO8(ecx)", "ch": "HI8(ecx)", "cx": "LO16(ecx)",
"dl": "LO8(edx)", "dh": "HI8(edx)", "dx": "LO16(edx)",
"si": "LO16(esi)", "di": "LO16(edi)",
"bp": "LO16(ebp)", "sp": "LO16(esp)",
}
if name in SUB_REGS:
return SUB_REGS[name]
return name
def _fmt_set_reg(name, value_expr):
"""Format assignment to a register, handling sub-register writes."""
# Segment registers → no-op
if name in ("fs", "gs", "cs", "ds", "es", "ss"):
return f"/* mov {name}, {value_expr} - segment register */;"
SET_MAP = {
"al": f"SET_LO8(eax, {value_expr})",
"ah": f"SET_HI8(eax, {value_expr})",
"ax": f"SET_LO16(eax, {value_expr})",
"bl": f"SET_LO8(ebx, {value_expr})",
"bh": f"SET_HI8(ebx, {value_expr})",
"bx": f"SET_LO16(ebx, {value_expr})",
"cl": f"SET_LO8(ecx, {value_expr})",
"ch": f"SET_HI8(ecx, {value_expr})",
"cx": f"SET_LO16(ecx, {value_expr})",
"dl": f"SET_LO8(edx, {value_expr})",
"dh": f"SET_HI8(edx, {value_expr})",
"dx": f"SET_LO16(edx, {value_expr})",
"si": f"SET_LO16(esi, {value_expr})",
"di": f"SET_LO16(edi, {value_expr})",
"bp": f"SET_LO16(ebp, {value_expr})",
"sp": f"SET_LO16(esp, {value_expr})",
}
if name in SET_MAP:
return SET_MAP[name] + ";"
return f"{name} = {value_expr};"
def _fmt_imm(val):
"""Format an immediate value as a C hex literal."""
if val == 0:
return "0"
if val <= 9:
return str(val)
if val > 0x7FFFFFFF:
return f"0x{val:08X}u"
return f"0x{val:X}"
def _mem_accessor(size):
"""Return the MEM macro name for a given operand size."""
return {1: "MEM8", 2: "MEM16", 4: "MEM32", 8: "MEM64"}.get(size, "MEM32")
def _smem_accessor(size):
"""Return the signed MEM macro for a given operand size."""
return {1: "SMEM8", 2: "SMEM16", 4: "SMEM32", 8: "SMEM64"}.get(size, "SMEM32")
def _fmt_mem(op):
"""Format a memory operand as a C expression (the address computation)."""
parts = []
if op.mem_base:
parts.append(_fmt_reg(op.mem_base))
if op.mem_index:
idx = _fmt_reg(op.mem_index)
if op.mem_scale and op.mem_scale > 1:
parts.append(f"{idx} * {op.mem_scale}")
else:
parts.append(idx)
if op.mem_disp:
if op.mem_disp < 0:
# Negative displacement - but we stored unsigned, check sign
if op.mem_disp > 0x80000000:
# Actually negative (two's complement)
signed_disp = op.mem_disp - 0x100000000
if parts:
parts.append(f"- {_fmt_imm(-signed_disp)}")
else:
parts.append(_fmt_imm(op.mem_disp))
else:
parts.append(_fmt_imm(op.mem_disp))
else:
parts.append(_fmt_imm(op.mem_disp))
if not parts:
return "0"
return " + ".join(parts)
def _fmt_mem_read(op):
"""Format reading from a memory operand."""
accessor = _mem_accessor(op.mem_size)
addr = _fmt_mem(op)
return f"{accessor}({addr})"
def _fmt_mem_write(op, value_expr):
"""Format writing to a memory operand."""
accessor = _mem_accessor(op.mem_size)
addr = _fmt_mem(op)
return f"{accessor}({addr}) = {value_expr};"
def _fmt_operand_read(op):
"""Format reading any operand type."""
if op.type == "reg":
return _fmt_reg(op.reg)
elif op.type == "imm":
return _fmt_imm(op.imm)
elif op.type == "mem":
return _fmt_mem_read(op)
return "/* unknown operand */"
def _operand_width(op):
"""Return an integer operand's architectural width in bytes."""
if op.type == "mem":
return op.mem_size
if op.type == "reg":
if op.reg in ("al", "ah", "bl", "bh", "cl", "ch", "dl", "dh"):
return 1
if op.reg in ("ax", "bx", "cx", "dx", "si", "di", "bp", "sp"):
return 2
return 4
return None
def _make_sized_cmp(cmp_macro, lhs, rhs, width):
"""Format a comparison with x86's operand-width truncation/sign rules."""
if width not in (1, 2):
return f"{cmp_macro}({lhs}, {rhs})"
operators = {
"CMP_EQ": "==", "CMP_NE": "!=", "CMP_B": "<", "CMP_AE": ">=",
"CMP_BE": "<=", "CMP_A": ">", "CMP_L": "<", "CMP_GE": ">=",
"CMP_LE": "<=", "CMP_G": ">",
}
signed = cmp_macro in ("CMP_L", "CMP_GE", "CMP_LE", "CMP_G")
c_type = f"int{width * 8}_t" if signed else f"uint{width * 8}_t"
return f"(({c_type})({lhs}) {operators[cmp_macro]} ({c_type})({rhs}))"
def _fmt_operand_write(op, value_expr):
"""Format writing to any operand type. Returns a C statement."""
if op.type == "reg":
return _fmt_set_reg(op.reg, value_expr)
elif op.type == "mem":
return _fmt_mem_write(op, value_expr)
return f"/* cannot write to {op.type} */;"
# ── Condition code mapping ───────────────────────────────────
# Maps jcc mnemonic → (cmp_macro, test_macro, description)
# cmp_macro takes (lhs, rhs), test_macro takes (lhs, rhs)
COND_MAP = {
"je": ("CMP_EQ", "TEST_Z", "equal / zero"),
"jz": ("CMP_EQ", "TEST_Z", "zero"),
"jne": ("CMP_NE", "TEST_NZ", "not equal / not zero"),
"jnz": ("CMP_NE", "TEST_NZ", "not zero"),
"jb": ("CMP_B", None, "below (unsigned <)"),
"jnae": ("CMP_B", None, "below"),
"jae": ("CMP_AE", None, "above or equal (unsigned >=)"),
"jnb": ("CMP_AE", None, "above or equal"),
"jbe": ("CMP_BE", None, "below or equal (unsigned <=)"),
"jna": ("CMP_BE", None, "below or equal"),
"ja": ("CMP_A", None, "above (unsigned >)"),
"jl": ("CMP_L", "TEST_S", "less (signed <)"),
"jge": ("CMP_GE", None, "greater or equal (signed >=)"),
"jle": ("CMP_LE", None, "less or equal (signed <=)"),
"jg": ("CMP_G", None, "greater (signed >)"),
"js": (None, "TEST_S", "sign (negative)"),
"jns": (None, None, "not sign (positive)"),
"jo": (None, None, "overflow"),
"jno": (None, None, "not overflow"),
"jp": (None, None, "parity"),
"jnp": (None, None, "not parity"),
"jecxz": (None, None, "ecx is zero"),
"jcxz": (None, None, "cx is zero"),
}
# Instructions that set arithmetic flags (primary set, fully handled)
FLAG_SETTERS = frozenset({
"cmp", "test", "sub", "add", "and", "or", "xor",
"inc", "dec", "neg", "shl", "shr", "sar", "imul", "adc", "sbb",
"comiss", "comisd", "ucomiss", "ucomisd", # SSE float compare
})
# Additional instructions that modify EFLAGS (tracked but handled as generic)
_EFLAGS_SETTERS = frozenset({
"shld", "shrd", "rol", "ror", "rcl", "rcr", # Shifts/rotates set CF
"bsf", "bsr", # Bit scan sets ZF
"bt", "bts", "btr", "btc", # Bit test sets CF
"cmpxchg", "lock cmpxchg", # Compare-and-exchange sets ZF
"xadd", # Exchange-and-add sets flags
})
# Instructions with undefined/unpredictable flags (clear tracking)
_FLAGS_UNDEFINED = frozenset({
"mul", "div", "idiv", # Flags partially undefined
"rdtsc", "cpuid", # Special instructions
"lock xadd", # Lock prefix - complex flag behavior
})
# Instructions that do NOT modify EFLAGS (preserve flag tracking)
_EFLAGS_PRESERVE = frozenset({
# General-purpose data movement / stack
"mov", "lea", "push", "pop", "nop", "leave", "ret",
"movzx", "movsx", "xchg", "bswap",
"cdq", "cwde", "cbw", "cwd",
"lahf",
"not", # NOT does not modify flags
"call",
"int3", "int", "wait",
"cld", "std", "cli", "sti",
"pushfd", "popfd", "pushal",
"sgdt", "ljmp", "sfence",
# SSE scalar float
"movss", "movsd",
"addss", "subss", "mulss", "divss",
"minss", "maxss", "sqrtss", "rsqrtss", "rcpss",
"addsd", "subsd", "mulsd", "divsd",
"minsd", "maxsd", "sqrtsd",
"cvtsi2ss", "cvtss2si", "cvttss2si",
"cvtsi2sd", "cvtsd2si", "cvttsd2si",
"cvtss2sd", "cvtsd2ss",
"cmpss", "cmpsd",
"cmpltss", "cmpeqss", "cmpleps", "cmpneqss",
# SSE packed float
"movaps", "movups", "movlps", "movhps", "movlhps", "movhlps",
"addps", "subps", "mulps", "divps",
"minps", "maxps", "sqrtps", "rsqrtps", "rcpps",
"shufps", "unpcklps", "unpckhps",
"andps", "orps", "xorps", "andnps",
"cmpps", "cmpneqps",
"movmskps",
# SSE2 packed double
"movapd", "movupd",
"addpd", "subpd", "mulpd", "divpd",
# SSE/MMX integer
"movd", "movq", "movntq",
"emms",
"paddb", "paddw", "paddd", "paddq",
"psubb", "psubw", "psubd",
"pmullw", "pmulhw", "pmulhuw", "pmaddwd",
"pand", "pandn", "por", "pxor",
"pcmpeqb", "pcmpeqw", "pcmpeqd",
"pcmpgtb", "pcmpgtw", "pcmpgtd",
"psllw", "pslld", "psllq",
"psrlw", "psrld", "psrlq",
"psraw", "psrad",
"pshufw", "pshufd", "pshufhw", "pshuflw",
"punpcklbw", "punpcklwd", "punpckldq", "punpcklqdq",
"punpckhbw", "punpckhwd", "punpckhdq", "punpckhqdq",
"packsswb", "packssdw", "packuswb",
"pmovmskb",
"cvtpi2ps", "cvtps2pi", "cvttps2pi",
# String operations (without rep prefix)
"stosb", "stosw", "stosd",
"movsb", "movsw", "movsd",
"lodsb", "lodsw", "lodsd",
# Prefetch hints
"prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2",
})
def _make_condition(jcc, flag_setter, flag_ops):
"""
Generate a C condition expression for a jcc based on what set the flags.
Returns (cond_expr, description) or None.
"""
cond_info = COND_MAP.get(jcc)
if not cond_info:
return None
cmp_macro, test_macro, desc = cond_info
if len(flag_ops) >= 2:
lhs = _fmt_operand_read(flag_ops[0])
rhs = _fmt_operand_read(flag_ops[1])
elif len(flag_ops) == 1:
lhs = _fmt_operand_read(flag_ops[0])
rhs = None
else:
lhs = None
rhs = None
# SAHF loads SF/ZF/AF/PF/CF directly from AH.
if flag_setter == "sahf":
ah = "HI8(eax)"
sahf_conditions = {
"ja": f"(({ah} & 0x41u) == 0)",
"jnbe": f"(({ah} & 0x41u) == 0)",
"jae": f"(({ah} & 0x01u) == 0)",
"jnb": f"(({ah} & 0x01u) == 0)",
"jnc": f"(({ah} & 0x01u) == 0)",
"jb": f"(({ah} & 0x01u) != 0)",
"jnae": f"(({ah} & 0x01u) != 0)",
"jc": f"(({ah} & 0x01u) != 0)",
"jbe": f"(({ah} & 0x41u) != 0)",
"jna": f"(({ah} & 0x41u) != 0)",
"je": f"(({ah} & 0x40u) != 0)",
"jz": f"(({ah} & 0x40u) != 0)",
"jne": f"(({ah} & 0x40u) == 0)",
"jnz": f"(({ah} & 0x40u) == 0)",
"js": f"(({ah} & 0x80u) != 0)",
"jns": f"(({ah} & 0x80u) == 0)",
"jp": f"(({ah} & 0x04u) != 0)",
"jnp": f"(({ah} & 0x04u) == 0)",
}
condition = sahf_conditions.get(jcc)
return (condition, desc) if condition else None
# ── FPU compare-to-EFLAGS: no standard operands ──
if flag_setter in ("fcompi", "fcomip", "fucomi", "fucompi",
"fucomip", "fcomi"):
fpu_cmp_map = {
"ja": ">", "jnbe": ">",
"jae": ">=", "jnb": ">=", "jnc": ">=",
"jb": "<", "jnae": "<", "jc": "<",
"jbe": "<=", "jna": "<=",
"je": "==", "jz": "==",
"jne": "!=", "jnz": "!=",
}
op = fpu_cmp_map.get(jcc)
if op:
return f"(_fpu_cmp {op} 0) /* {flag_setter} */", desc
if jcc == "jp":
return "(_fpu_cmp == 2) /* fpu: unordered/NaN */", desc
if jcc == "jnp":
return "(_fpu_cmp != 2) /* fpu: ordered */", desc
return None
# If no operands available for other flag-setters, can't generate condition
if lhs is None:
return None
# ── comiss/ucomiss: float comparison, sets CF/ZF/PF ──
if flag_setter in ("comiss", "comisd", "ucomiss", "ucomisd"):
def _sse_op(op):
if op.type == "reg":
return op.reg
elif op.type == "mem":
if op.mem_size == 8:
return f"MEMD({_fmt_mem(op)})"
return f"MEMF({_fmt_mem(op)})"
return _fmt_operand_read(op)
a = _sse_op(flag_ops[0]) if len(flag_ops) >= 1 else "0.0f"
b = _sse_op(flag_ops[1]) if len(flag_ops) >= 2 else "0.0f"
# COMISS/UCOMISS set ZF/PF/CF to 111 for unordered operands.
# Preserve those unsigned x86 conditions instead of relying on the
# host language's all-false NaN comparisons.
unordered = f"(isnan((double)({a})) || isnan((double)({b})))"
if jcc in ("ja", "jnbe"):
return f"(!{unordered} && ({a} > {b}))", desc
if jcc in ("jae", "jnb", "jnc"):
return f"(!{unordered} && ({a} >= {b}))", desc
if jcc in ("jb", "jnae", "jc"):
return f"({unordered} || ({a} < {b}))", desc
if jcc in ("jbe", "jna"):
return f"({unordered} || ({a} <= {b}))", desc
if jcc in ("je", "jz"):
return f"({unordered} || ({a} == {b}))", desc
if jcc in ("jne", "jnz"):
return f"(!{unordered} && ({a} != {b}))", desc
if jcc == "jp":
return unordered, desc
if jcc == "jnp":
return f"!{unordered}", desc
return None
# ── cmp: flags from (a - b), operands unchanged ──
if flag_setter == "cmp":
if cmp_macro:
return _make_sized_cmp(
cmp_macro, lhs, rhs, _operand_width(flag_ops[0])
), desc
if jcc == "js":
width = _operand_width(flag_ops[0])
if width in (1, 2):
bits = width * 8
return (f"((int{bits}_t)((uint{bits}_t)({lhs}) - "
f"(uint{bits}_t)({rhs})) < 0)"), desc
return f"((int32_t)({lhs} - {rhs}) < 0)", desc
if jcc == "jns":
width = _operand_width(flag_ops[0])
if width in (1, 2):
bits = width * 8
return (f"((int{bits}_t)((uint{bits}_t)({lhs}) - "
f"(uint{bits}_t)({rhs})) >= 0)"), desc
return f"((int32_t)({lhs} - {rhs}) >= 0)", desc
if jcc in ("jp", "jnp"):
parity = f"EVEN_PARITY8((uint8_t)({lhs} - {rhs}))"
return (parity if jcc == "jp" else f"!{parity}"), desc
return None
# ── test: flags from (a & b), operands unchanged ──
if flag_setter == "test":
if test_macro:
return f"{test_macro}({lhs}, {rhs})", desc
if cmp_macro:
return _make_sized_cmp(
cmp_macro, f"({lhs} & {rhs})", "0",
_operand_width(flag_ops[0])
), desc
if jcc == "js":
width = _operand_width(flag_ops[0])
if width in (1, 2):
bits = width * 8
return (f"((int{bits}_t)(uint{bits}_t)({lhs} & {rhs}) "
"< 0)"), desc
return f"((int32_t)({lhs} & {rhs}) < 0)", desc
if jcc == "jns":
width = _operand_width(flag_ops[0])
if width in (1, 2):
bits = width * 8
return (f"((int{bits}_t)(uint{bits}_t)({lhs} & {rhs}) "
">= 0)"), desc
return f"((int32_t)({lhs} & {rhs}) >= 0)", desc
if jcc == "jo":
return "0", desc # OF=0 after test
if jcc == "jno":
return "1", desc
if jcc in ("jp", "jnp"):
parity = f"EVEN_PARITY8((uint8_t)({lhs} & {rhs}))"
return (parity if jcc == "jp" else f"!{parity}"), desc
return None
# ── sub: a = a - b, flags from (a_orig - b) ──
if flag_setter == "sub":
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc == "js":
return f"((int32_t){lhs} < 0)", desc
if jcc == "jns":
return f"((int32_t){lhs} >= 0)", desc
# Ordered: reconstruct original a = result + b
if cmp_macro and rhs:
return f"{cmp_macro}((uint32_t){lhs} + (uint32_t){rhs}, (uint32_t){rhs})", desc
if jcc in ("jb", "jnae"):
return f"((uint32_t){lhs} + (uint32_t){rhs} < (uint32_t){rhs})", desc
if jcc in ("jae", "jnb"):
return f"((uint32_t){lhs} + (uint32_t){rhs} >= (uint32_t){rhs})", desc
if jcc in ("jl", "jnge"):
return f"((int32_t){lhs} < 0)", desc
if jcc in ("jge", "jnl"):
return f"((int32_t){lhs} >= 0)", desc
if jcc in ("jle", "jng"):
return f"((int32_t){lhs} <= 0)", desc
if jcc in ("jg", "jnle"):
return f"((int32_t){lhs} > 0)", desc
return None
# ── add: a = a + b, flags from result ──
if flag_setter == "add":
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc == "js":
return f"((int32_t){lhs} < 0)", desc
if jcc == "jns":
return f"((int32_t){lhs} >= 0)", desc
if jcc in ("jb", "jnae", "jc"):
return f"({lhs} < (uint32_t){rhs})", desc
if jcc in ("jae", "jnb", "jnc"):
return f"({lhs} >= (uint32_t){rhs})", desc
if jcc in ("jl", "jnge"):
return f"((int32_t){lhs} < 0)", desc
if jcc in ("jge", "jnl"):
return f"((int32_t){lhs} >= 0)", desc
if jcc in ("jle", "jng"):
return f"((int32_t){lhs} <= 0)", desc
if jcc in ("jg", "jnle"):
return f"((int32_t){lhs} > 0)", desc
return None
# ── adc/sbb: result-based (like add/sub but with carry) ──
if flag_setter in ("adc", "sbb"):
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc == "js":
return f"((int32_t){lhs} < 0)", desc
if jcc == "jns":
return f"((int32_t){lhs} >= 0)", desc
return None
# ── and/or/xor: result-based, CF=0, OF=0 ──
if flag_setter in ("and", "or", "xor"):
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc in ("js", "jl"):
return f"((int32_t){lhs} < 0)", desc
if jcc in ("jns", "jge"):
return f"((int32_t){lhs} >= 0)", desc
if jcc == "jle":
return f"((int32_t){lhs} <= 0)", desc
if jcc == "jg":
return f"((int32_t){lhs} > 0)", desc
if jcc in ("jb", "jnae", "jc"):
return "0", desc # CF=0 after and/or/xor
if jcc in ("jbe", "jna"):
# JBE is CF || ZF. Logical instructions clear CF, so this is
# exactly the zero condition—not an always-false branch.
return f"({lhs} == 0)", desc
if jcc in ("jae", "jnb", "jnc"):
return "1", desc
if jcc in ("ja", "jnbe"):
# JA is !CF && !ZF. Logical instructions clear CF, so this is
# exactly the non-zero condition.
return f"({lhs} != 0)", desc
return None
# ── dec/inc: result-based, CF unchanged ──
if flag_setter in ("dec", "inc"):
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc == "js":
return f"((int32_t){lhs} < 0)", desc
if jcc == "jns":
return f"((int32_t){lhs} >= 0)", desc
if jcc in ("jl", "jle", "jg", "jge"):
cast = "(int32_t)" + lhs
op = {"jl": "<", "jle": "<=", "jg": ">", "jge": ">="}[jcc]
return f"({cast} {op} 0)", desc
return None
# ── neg: flags from (0 - a_orig), result is -a ──
if flag_setter == "neg":
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc in ("jb", "jnae", "jc"):
# CF=1 unless original was 0
return f"({lhs} != 0)", desc
if jcc in ("jae", "jnb", "jnc"):
return f"({lhs} == 0)", desc
if jcc == "js":
return f"((int32_t){lhs} < 0)", desc
if jcc == "jns":
return f"((int32_t){lhs} >= 0)", desc
if jcc in ("jg", "jnle"):
return f"((int32_t){lhs} > 0)", desc
if jcc in ("jge", "jnl"):
return f"((int32_t){lhs} >= 0)", desc
if jcc in ("jl", "jnge"):
return f"((int32_t){lhs} < 0)", desc
if jcc in ("jle", "jng"):
return f"((int32_t){lhs} <= 0)", desc
return None
# ── shift: result-based ──
if flag_setter in ("shl", "shr", "sar"):
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc == "js":
return f"((int32_t){lhs} < 0)", desc
if jcc == "jns":
return f"((int32_t){lhs} >= 0)", desc
return None
# ── shld/shrd: double-precision shift, result-based ──
if flag_setter in ("shld", "shrd"):
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
if jcc == "js":
return f"((int32_t){lhs} < 0)", desc
if jcc == "jns":
return f"((int32_t){lhs} >= 0)", desc
return None
# ── rol/ror/rcl/rcr: rotation, only CF/OF affected ──
if flag_setter in ("rol", "ror", "rcl", "rcr"):
# ZF/SF not modified by rotations - can't resolve most conditions
return None
# ── bsf/bsr: bit scan, ZF set if source is zero ──
if flag_setter in ("bsf", "bsr"):
if rhs is None:
return None
if jcc in ("je", "jz"):
return f"({rhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({rhs} != 0)", desc
return None
# ── bt/bts/btr/btc: bit test, sets CF ──
if flag_setter in ("bt", "bts", "btr", "btc"):
if rhs is None:
return None
if jcc in ("jb", "jnae", "jc"):
return f"(({lhs} >> ({rhs} & 31)) & 1)", desc
if jcc in ("jae", "jnb", "jnc"):
return f"!(({lhs} >> ({rhs} & 31)) & 1)", desc
return None
# ── cmpxchg: compares accumulator with dest, sets ZF on match ──
if flag_setter in ("cmpxchg", "lock cmpxchg"):
if jcc in ("je", "jz"):
return "(_flags != 0)", desc
if jcc in ("jne", "jnz"):
return "(_flags == 0)", desc
return None
# ── xadd: exchange and add, flags from addition ──
if flag_setter == "xadd":
if jcc in ("je", "jz"):
return f"({lhs} == 0)", desc
if jcc in ("jne", "jnz"):
return f"({lhs} != 0)", desc
return None
# ── repe cmps* / repne scas*: string comparison ──
if "cmps" in flag_setter or "scas" in flag_setter:
if jcc in ("je", "jz"):
return "(_flags != 0) /* REP string comparison ZF */", desc
if jcc in ("jne", "jnz"):
return "(_flags == 0) /* REP string comparison !ZF */", desc
return None
return None
def _make_sse_lahf_value(flag_setter, flag_ops):
"""Encode COMISS/UCOMISS ZF/PF/CF as the AH value produced by LAHF."""
if (flag_setter not in ("comiss", "comisd", "ucomiss", "ucomisd")
or len(flag_ops) < 2):
return None
def _operand(op):
if op.type == "reg":
return op.reg
if op.type == "mem":
accessor = "MEMD" if op.mem_size == 8 else "MEMF"
return f"{accessor}({_fmt_mem(op)})"
return _fmt_operand_read(op)
a = _operand(flag_ops[0])
b = _operand(flag_ops[1])
return (
f"((isnan((double)({a})) || isnan((double)({b}))) ? 0x45u : "
f"(({a}) < ({b})) ? 0x01u : (({a}) == ({b})) ? 0x40u : 0u)"
)
def _make_setcc_value(setcc_mnemonic, flag_setter, flag_ops):
"""Generate the condition expression for a SETcc instruction."""
cc = setcc_mnemonic[3:]
jcc = "j" + cc
result = _make_condition(jcc, flag_setter, flag_ops)
if result:
return result[0]
return None
def _make_cmovcc_cond(cmov_mnemonic, flag_setter, flag_ops):
"""Generate the condition expression for a CMOVcc instruction."""
cc = cmov_mnemonic[4:]
jcc = "j" + cc
result = _make_condition(jcc, flag_setter, flag_ops)
if result:
return result[0]
return None
_COMPLEMENT_CONDITION_CODES = {
"e": "ne", "ne": "e",
"z": "nz", "nz": "z",
"b": "ae", "ae": "b",
"nae": "nb", "nb": "nae",
"be": "a", "a": "be",
"na": "nbe", "nbe": "na",
"l": "ge", "ge": "l",
"le": "g", "g": "le",
"s": "ns", "ns": "s",
}
def _condition_code(mnemonic):
"""Return the condition-code suffix shared by Jcc/SETcc/CMOVcc."""
if mnemonic.startswith("cmov"):
return mnemonic[4:]
if mnemonic.startswith("set"):
return mnemonic[3:]
if mnemonic.startswith("j"):
return mnemonic[1:]
return None
def _snapshot_condition_test(consumer_mnemonic, snapshot_consumer):
"""Reuse a snapshotted boolean for the same or complementary condition."""
consumer_cc = _condition_code(consumer_mnemonic)
snapshot_cc = _condition_code(snapshot_consumer)
if not consumer_cc or not snapshot_cc:
return None
if consumer_cc == snapshot_cc:
return "_flags != 0"
if _COMPLEMENT_CONDITION_CODES.get(snapshot_cc) == consumer_cc:
return "_flags == 0"
return None
# ── Pattern matching for flag-setter + jcc ────────────────────
def _emit_cond_goto(cond_expr, jcc, desc, target, lifter):
"""Emit a conditional goto or call for a jump target."""
if target is None:
return f"if ({cond_expr}) {{ /* {jcc}: {desc} - indirect */ }}"
if lifter and lifter._is_external_target(target):
name = lifter._call_target_name(target)
return (f"if ({cond_expr}) {{ {name}(); return; }}"
f" /* {jcc}: {desc} */")
return f"if ({cond_expr}) goto loc_{target:08X}; /* {jcc}: {desc} */"
def try_match_cmp_jcc(insns, idx, lifter=None):
"""
Try to match a cmp/test + jcc pattern starting at insns[idx].
Returns (c_statement, num_consumed) or None.
"""
if idx + 1 >= len(insns):
return None
first = insns[idx]
second = insns[idx + 1]
if first.mnemonic not in ("cmp", "test") or not second.is_cond_jump:
return None
if len(first.operands) < 2:
return None
result = _make_condition(second.mnemonic, first.mnemonic, first.operands)
if not result:
return None
cond_expr, desc = result
target = second.jump_target
stmt = _emit_cond_goto(cond_expr, second.mnemonic, desc, target, lifter)
return (stmt, 2)
# ── Single instruction lifting ───────────────────────────────
# MSVC's __SEH_prolog establishes the caller's frame pointer, so the lifter has
# to know which function it is. The address is per-title, and hardcoding it
# meant every other game silently got no frame set up after the call: ebp kept
# whatever stale value it had, and the first ebp-relative local access read
# through it. In Halo that surfaced as a read of 0xFFFFFFFC (ebp=0, [ebp-4]).
#
# Both helpers are compiler boilerplate with distinctive bodies, so detect them
# rather than asking every project to look them up by hand.
#
# __SEH_prolog mov eax, fs:[0] 64 A1 00 00 00 00
# lea ebp, [esp+0x10] 8D 6C 24 10
# __SEH_epilog mov fs:[0], ecx 64 89 0D 00 00 00 00
# leave; push ecx; ret C9 51 C3
_SEH_PROLOG_MARKERS = (b"\x64\xa1\x00\x00\x00\x00", b"\x8d\x6c\x24\x10")
_SEH_EPILOG_MARKERS = (b"\x64\x89\x0d\x00\x00\x00\x00", b"\xc9\x51\xc3")
# Both are tiny; a large match is something else that happens to touch fs:[0].
_SEH_PROLOG_MAX_SIZE = 128
_SEH_EPILOG_MAX_SIZE = 64
def detect_seh_helpers(func_db, xbe_data, verbose=False):
"""Locate __SEH_prolog / __SEH_epilog in the target binary.
Returns (prolog_addr, epilog_addr); either may be None if not found, which
is normal for a title whose CRT does not use them.
"""
from .config import va_to_file_offset
prolog = epilog = None
def _size_of(info):
# "end" is a hex string in functions.json but BatchTranslator rewrites
# it to an int in place, so accept either.
try:
size = int(info.get("size") or 0)
except (TypeError, ValueError):
size = 0
if size:
return size
end = info.get("end")
if isinstance(end, str):
try:
end = int(end, 16)
except ValueError:
return 0
return (end - addr) if isinstance(end, int) else 0
for addr in sorted(func_db):
info = func_db[addr]
size = _size_of(info)
if size <= 0 or size > _SEH_PROLOG_MAX_SIZE:
continue
offset = va_to_file_offset(addr)
if offset is None or xbe_data is None or offset + size > len(xbe_data):
continue
body = xbe_data[offset:offset + size]
if (prolog is None and size <= _SEH_PROLOG_MAX_SIZE
and all(m in body for m in _SEH_PROLOG_MARKERS)):
prolog = addr
elif (epilog is None and size <= _SEH_EPILOG_MAX_SIZE
and all(m in body for m in _SEH_EPILOG_MARKERS)):
epilog = addr
if prolog is not None and epilog is not None:
break
if verbose:
import sys
fmt = lambda a: f"0x{a:08X}" if a else "not found"
print(f" SEH helpers: __SEH_prolog {fmt(prolog)}, "
f"__SEH_epilog {fmt(epilog)}", file=sys.stderr)
return prolog, epilog
class Lifter:
"""Translates x86 instructions to C statements."""
def __init__(self, func_db=None, label_db=None, abi_db=None, xbe_data=None,
seh_prolog=None, seh_epilog=None):
"""
func_db: dict of func_addr → func_info (for naming call targets)
label_db: dict of addr → name (for kernel imports, etc.)
abi_db: dict of addr → ABI info (for calling conventions)
xbe_data: raw XBE file bytes (for reading jump tables)
seh_prolog/seh_epilog: override the detected __SEH_prolog/__SEH_epilog
"""
self.func_db = func_db or {}
self.label_db = label_db or {}
self.abi_db = abi_db or {}
self.xbe_data = xbe_data
self._fp_top = 0 # FPU stack top index
self._direction_step = 1 # CLD by ABI at function entry
self.func_start = 0 # Set per-function by translator
self.func_end = 0
# Every direct call target we emit a name for, as {addr: name}. The
# batch translator diffs this against the functions it actually defined
# so it can stub out the remainder (see translate_batch_split).
self.referenced_calls = {}
# Detect if either is missing, so overriding one does not silently
# leave the other unset -- that is the bug this whole path fixes.
if (seh_prolog is None or seh_epilog is None) and self.func_db:
found_prolog, found_epilog = detect_seh_helpers(self.func_db, xbe_data)
seh_prolog = seh_prolog if seh_prolog is not None else found_prolog
seh_epilog = seh_epilog if seh_epilog is not None else found_epilog
self.SEH_PROLOG = seh_prolog
self.SEH_EPILOG = seh_epilog
def _call_target_name(self, addr):
"""Get the name for a call target address.
func_db wins over label_db. The function definition is emitted from
func_db, so consulting labels first meant a renamed function was
*defined* as cseries__sub_0008DB80 but *called* as sub_0008DB80 -- the
disassembler's generic auto-label -- and the link failed on every
function any naming pass had touched. Labels still cover call targets
that are not known function starts.
"""
if addr in self.func_db:
name = self.func_db[addr].get("name", f"sub_{addr:08X}")
elif addr in self.label_db:
name = self.label_db[addr]
else:
name = f"sub_{addr:08X}"
self.referenced_calls[addr] = name
return name
def lift_instruction(self, insn):
"""
Translate a single x86 instruction to one or more C statements.
Returns a list of C statement strings.
"""
m = insn.mnemonic
ops = insn.operands
nops = len(ops)
# ── NOP ──
if m == "nop" or (m == "lea" and nops == 2 and
ops[0].type == "reg" and ops[1].type == "mem" and
ops[1].mem_base == ops[0].reg and
not ops[1].mem_index and ops[1].mem_disp == 0):
return [f"/* nop */"]
# ── Data movement ──
if m == "mov":
return self._lift_mov(insn, ops)
if m == "movzx":
return self._lift_movzx(insn, ops)
if m == "movsx":
return self._lift_movsx(insn, ops)
if m == "lea":
return self._lift_lea(insn, ops)
if m == "xchg":
return self._lift_xchg(insn, ops)
if m in ("cmpxchg", "lock cmpxchg"):
return self._lift_cmpxchg(insn, ops)
# ── Stack ──
if m == "push":
return self._lift_push(insn, ops)
if m == "pop":
return self._lift_pop(insn, ops)
# ── Arithmetic ──
if m in ("add", "sub", "and", "or", "xor"):
return self._lift_alu_binop(insn, ops, m)
if m in ("inc", "dec"):
return self._lift_inc_dec(insn, ops, m)
if m == "neg":
return self._lift_neg(insn, ops)
if m == "not":
return self._lift_not(insn, ops)
if m == "imul":
return self._lift_imul(insn, ops)
if m in ("mul", "div", "idiv"):
return self._lift_muldiv(insn, ops, m)
if m == "sbb":
return self._lift_sbb(insn, ops)
if m == "adc":
return self._lift_adc(insn, ops)
if m in ("shl", "sal"):
return self._lift_shift(insn, ops, m)
if m == "shr":
return self._lift_shift(insn, ops, m)
if m == "sar":
return self._lift_shift(insn, ops, m)
if m in ("rol", "ror", "rcl", "rcr"):
return self._lift_rotate(insn, ops, m)
# ── Comparison / test (standalone, not part of cmp+jcc pattern) ──
if m == "cmp":
return self._lift_cmp(insn, ops)
if m == "test":
return self._lift_test(insn, ops)
# ── Control flow ──
if m == "call":
return self._lift_call(insn, ops)
if m in ("ret", "retn", "retf"):
return self._lift_ret(insn, ops)
if m == "jmp":
return self._lift_jmp(insn, ops)
if insn.is_cond_jump:
return self._lift_jcc(insn)