-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibsurgeon.py
More file actions
1783 lines (1456 loc) · 59.9 KB
/
Copy pathlibsurgeon.py
File metadata and controls
1783 lines (1456 loc) · 59.9 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
# -*- coding: utf-8 -*-
"""
LibSurgeon - Static Library & ELF Reverse Engineering Tool
Automated decompilation of .a archive and ELF files to C/C++ source code
using Ghidra Headless mode.
Features:
- Support for .a, .lib archives and .so, .elf, .o, .axf, .out ELF files
- Recursive directory scanning
- Parallel decompilation (configurable jobs)
- Include/Exclude filters
- Quality evaluation integration
- Detailed progress tracking
- Summary reports
Usage:
python libsurgeon.py -g /path/to/ghidra /target/directory
python libsurgeon.py -g /path/to/ghidra -o output/ library.a
python libsurgeon.py -g /path/to/ghidra --evaluate firmware.elf
"""
import argparse
import glob
import os
import shutil
import subprocess
import sys
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional
# ============================================================
# Color and Display Utilities
# ============================================================
class Colors:
"""ANSI color codes for terminal output"""
RED = "\033[0;31m"
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
BLUE = "\033[0;34m"
CYAN = "\033[0;36m"
MAGENTA = "\033[0;35m"
BOLD = "\033[1m"
DIM = "\033[2m"
NC = "\033[0m" # No Color
@classmethod
def disable(cls):
"""Disable colors for non-TTY output"""
cls.RED = cls.GREEN = cls.YELLOW = cls.BLUE = ""
cls.CYAN = cls.MAGENTA = cls.BOLD = cls.DIM = cls.NC = ""
def log_info(msg: str):
print(f"{Colors.GREEN}[INFO]{Colors.NC} {msg}")
def log_warn(msg: str):
print(f"{Colors.YELLOW}[WARN]{Colors.NC} {msg}")
def log_error(msg: str):
print(f"{Colors.RED}[ERROR]{Colors.NC} {msg}")
def log_step(msg: str):
print(f"{Colors.MAGENTA}[STEP]{Colors.NC} {msg}")
def format_time(seconds: int) -> str:
"""Format seconds to human-readable time"""
if seconds < 60:
return f"{seconds}s"
elif seconds < 3600:
mins, secs = divmod(seconds, 60)
return f"{mins}m{secs}s"
else:
hours, remainder = divmod(seconds, 3600)
mins = remainder // 60
return f"{hours}h{mins}m"
def print_banner():
"""Print the program banner"""
print(f"{Colors.BLUE}")
print("╔══════════════════════════════════════════════════════════════╗")
print("║ LibSurgeon - Static Library Dissector ║")
print("║ Automated Reverse Engineering with Ghidra ║")
print("╚══════════════════════════════════════════════════════════════╝")
print(f"{Colors.NC}")
def draw_box(title: str, subtitle: str = "", color: str = Colors.BLUE) -> str:
"""Draw a text box with title"""
width = max(50, len(title) + 6, len(subtitle) + 6)
width = min(80, width)
line = "═" * width
# Center title
pad_left = (width - len(title)) // 2
pad_right = width - len(title) - pad_left
title_line = f"║{' ' * pad_left}{title}{' ' * pad_right}║"
result = f"{color}╔{line}╗{Colors.NC}\n"
result += f"{color}{title_line}{Colors.NC}\n"
if subtitle:
pad_left = (width - len(subtitle)) // 2
pad_right = width - len(subtitle) - pad_left
subtitle_line = f"║{' ' * pad_left}{subtitle}{' ' * pad_right}║"
result += f"{color}{subtitle_line}{Colors.NC}\n"
result += f"{color}╚{line}╝{Colors.NC}"
return result
def draw_progress_bar(current: int, total: int, width: int = 40) -> str:
"""Draw a progress bar"""
if total == 0:
return "░" * width
filled = int(current * width / total)
empty = width - filled
return "█" * filled + "░" * empty
def show_progress(
current: int,
total: int,
elapsed: int,
filename: str = "",
eta: int = 0,
):
"""Show progress bar with ETA - similar to shell version"""
if total <= 0:
return
percentage = current * 100 // total
bar = draw_progress_bar(current, total)
# Build progress line
progress_line = f"{Colors.CYAN}[{bar}]{Colors.NC} {Colors.BOLD}{percentage}%{Colors.NC} ({current}/{total})"
# Add time info
if eta > 0:
progress_line += f" | Elapsed: {format_time(elapsed)} | ETA: {Colors.YELLOW}{format_time(eta)}{Colors.NC}"
else:
progress_line += f" | Elapsed: {format_time(elapsed)}"
# Clear line and print
print(f"\r\033[K{progress_line}")
# Show current file (clear line first to avoid leftover characters)
if filename:
print(
f"\033[K{Colors.DIM} -> Completed: {Colors.NC}{Colors.GREEN}{filename}{Colors.NC}"
)
else:
print(f"\033[K{Colors.DIM} -> Processing...{Colors.NC}")
# Move cursor up 2 lines
print("\033[2A", end="")
def show_progress_final(total: int, elapsed: int):
"""Show final completed progress bar"""
bar = draw_progress_bar(total, total)
print("\r\033[K\n\033[K\n", end="")
print("\033[2A", end="")
print(
f"{Colors.GREEN}[{bar}]{Colors.NC} {Colors.BOLD}100%{Colors.NC} ({total}/{total}) | Total: {format_time(elapsed)}"
)
print()
# ============================================================
# File Type Detection
# ============================================================
class FileType(Enum):
ARCHIVE = "archive"
ELF = "elf"
UNKNOWN = "unknown"
# Extension to file type mapping
EXTENSION_MAP = {
".a": FileType.ARCHIVE,
".lib": FileType.ARCHIVE,
".so": FileType.ELF,
".elf": FileType.ELF,
".axf": FileType.ELF,
".out": FileType.ELF,
".o": FileType.ELF,
}
# Module grouping strategies for ELF files
MODULE_STRATEGIES = ["prefix", "alpha", "camelcase", "single"]
def get_file_type(filepath: str) -> FileType:
"""Determine file type based on extension"""
basename = os.path.basename(filepath)
# Handle .so.* pattern (e.g., libfoo.so.1.2.3)
if ".so." in basename:
return FileType.ELF
ext = os.path.splitext(basename)[1].lower()
return EXTENSION_MAP.get(ext, FileType.UNKNOWN)
def is_elf_file(filepath: str) -> bool:
"""Check if file is a valid ELF by magic number"""
try:
# Follow symlinks
real_path = os.path.realpath(filepath)
if not os.path.isfile(real_path):
return False
with open(real_path, "rb") as f:
magic = f.read(4)
return magic == b"\x7fELF"
except (IOError, OSError):
return False
def is_archive_file(filepath: str) -> bool:
"""Check if file is a valid archive by magic number"""
try:
with open(filepath, "rb") as f:
magic = f.read(8)
return magic == b"!<arch>\n"
except (IOError, OSError):
return False
# ELF machine type to Ghidra processor mapping
# ELF e_machine values: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
ELF_MACHINE_MAP = {
0x03: ("x86:LE:32:default", "gcc"), # EM_386 - Intel 80386
0x3E: ("x86:LE:64:default", "gcc"), # EM_X86_64 - AMD x86-64
0x28: ("ARM:LE:32:v7", "default"), # EM_ARM - ARM 32-bit
0xB7: ("AARCH64:LE:64:v8A", "default"), # EM_AARCH64 - ARM 64-bit
0x08: ("MIPS:BE:32:default", "default"), # EM_MIPS - MIPS
0x14: ("PowerPC:BE:32:default", "default"), # EM_PPC - PowerPC
0x15: ("PowerPC:BE:64:default", "default"), # EM_PPC64 - PowerPC 64-bit
0xF3: ("RISCV:LE:32:RV32GC", "default"), # EM_RISCV - RISC-V
0x2B: ("Sparc:BE:32:default", "default"), # EM_SPARC - SPARC
0x32: ("IA64:LE:64:default", "default"), # EM_IA_64 - Intel IA-64
0x53: ("AVR8:LE:16:atmega256", "default"), # EM_AVR - Atmel AVR
0x5E: ("Xtensa:LE:32:default", "default"), # EM_XTENSA - Tensilica Xtensa
}
def detect_elf_architecture(filepath: str) -> Optional[tuple]:
"""
Detect ELF file architecture by reading ELF header.
Returns:
Tuple of (processor_id, compiler_spec) for Ghidra, or None if detection fails
"""
try:
with open(filepath, "rb") as f:
magic = f.read(4)
if magic != b"\x7fELF":
return None
# ELF class (32/64 bit)
ei_class = ord(f.read(1))
is_64bit = ei_class == 2
# ELF data encoding (endianness)
ei_data = ord(f.read(1))
is_little_endian = ei_data == 1
# Skip to e_machine field (offset 18 for 32-bit, 18 for 64-bit)
f.seek(18)
machine_bytes = f.read(2)
if is_little_endian:
e_machine = int.from_bytes(machine_bytes, "little")
else:
e_machine = int.from_bytes(machine_bytes, "big")
# Look up in our mapping
if e_machine in ELF_MACHINE_MAP:
processor, cspec = ELF_MACHINE_MAP[e_machine]
# Adjust for endianness and bitness if needed
if e_machine == 0x28: # ARM
# ARM can be LE or BE
endian = "LE" if is_little_endian else "BE"
processor = f"ARM:{endian}:32:v7"
elif e_machine == 0xB7: # AARCH64
endian = "LE" if is_little_endian else "BE"
processor = f"AARCH64:{endian}:64:v8A"
elif e_machine == 0xF3: # RISC-V
endian = "LE" if is_little_endian else "BE"
bits = "64" if is_64bit else "32"
variant = "RV64GC" if is_64bit else "RV32GC"
processor = f"RISCV:{endian}:{bits}:{variant}"
elif e_machine == 0x08: # MIPS
endian = "LE" if is_little_endian else "BE"
bits = "64" if is_64bit else "32"
processor = f"MIPS:{endian}:{bits}:default"
return (processor, cspec)
# Unknown architecture, return None to let Ghidra auto-detect
log_warn(f"Unknown ELF machine type: 0x{e_machine:02X}")
return None
except (IOError, OSError) as e:
log_warn(f"Failed to detect ELF architecture: {e}")
return None
@dataclass
class DebugInfo:
"""Information about debug symbols in a file"""
has_debug: bool = False
format: str = "none" # "DWARF", "COFF", "none"
version: Optional[str] = None
sections: List[str] = field(default_factory=list)
has_local_vars: bool = False
compiler: Optional[str] = None
def detect_debug_info(filepath: str) -> DebugInfo:
"""
Detect debug information in an object file.
Supports:
- ELF files with DWARF debug info
- COFF/PE files with DWARF debug info (MinGW/GCC on Windows)
Args:
filepath: Path to the object file
Returns:
DebugInfo object with detection results
"""
info = DebugInfo()
try:
with open(filepath, "rb") as f:
magic = f.read(8)
# Check for ELF
if magic[:4] == b"\x7fELF":
info = _detect_elf_debug_info(filepath)
# Check for COFF/PE (Windows object files)
elif magic[:2] == b"MZ" or magic[:2] in (b"\x64\x86", b"\x4c\x01", b"\x00\x00"):
info = _detect_coff_debug_info(filepath)
except (IOError, OSError) as e:
log_warn(f"Failed to detect debug info: {e}")
return info
def _detect_elf_debug_info(filepath: str) -> DebugInfo:
"""Detect DWARF debug info in ELF file using readelf"""
info = DebugInfo()
try:
# Use readelf to check for debug sections
result = subprocess.run(
["readelf", "-S", filepath], capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
output = result.stdout
debug_sections = []
for line in output.split("\n"):
if ".debug_" in line:
# Extract section name
parts = line.split()
for part in parts:
if part.startswith(".debug_"):
debug_sections.append(part)
break
if debug_sections:
info.has_debug = True
info.format = "DWARF"
info.sections = debug_sections
# Check for local variable info (.debug_info section)
if ".debug_info" in debug_sections:
info.has_local_vars = True
# Try to get DWARF version and compiler info
result = subprocess.run(
["readelf", "--debug-dump=info", filepath],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0:
output = result.stdout[:5000] # Only check first part
# Extract DWARF version
for line in output.split("\n"):
if "版本" in line or "Version" in line:
parts = line.split()
for i, part in enumerate(parts):
if part.isdigit():
info.version = part
break
if info.version:
break
# Extract compiler info
if "DW_AT_producer" in output:
for line in output.split("\n"):
if "DW_AT_producer" in line:
# Extract compiler string
if ":" in line:
info.compiler = line.split(":", 1)[1].strip()[:100]
break
except subprocess.TimeoutExpired:
log_warn(f"Timeout detecting debug info for {filepath}")
except FileNotFoundError:
log_warn("readelf not found - cannot detect debug info")
except Exception as e:
log_warn(f"Error detecting ELF debug info: {e}")
return info
def _detect_coff_debug_info(filepath: str) -> DebugInfo:
"""Detect DWARF debug info in COFF/PE file using objdump"""
info = DebugInfo()
try:
# Use objdump to check for debug sections
result = subprocess.run(
["objdump", "-h", filepath], capture_output=True, text=True, timeout=10
)
if result.returncode == 0:
output = result.stdout
debug_sections = []
for line in output.split("\n"):
if ".debug_" in line:
parts = line.split()
for part in parts:
if part.startswith(".debug_"):
debug_sections.append(part)
break
if debug_sections:
info.has_debug = True
info.format = "DWARF"
info.sections = debug_sections
if ".debug_info" in debug_sections:
info.has_local_vars = True
# Try to get compiler info
result = subprocess.run(
["objdump", "--dwarf=info", filepath],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode == 0:
output = result.stdout[:5000]
if "DW_AT_producer" in output:
for line in output.split("\n"):
if "DW_AT_producer" in line:
if ":" in line:
info.compiler = line.split(":", 1)[1].strip()[:100]
break
except subprocess.TimeoutExpired:
log_warn(f"Timeout detecting debug info for {filepath}")
except FileNotFoundError:
log_warn("objdump not found - cannot detect COFF debug info")
except Exception as e:
log_warn(f"Error detecting COFF debug info: {e}")
return info
# ============================================================
# File Scanning
# ============================================================
@dataclass
class ScanResult:
"""Result of file scanning"""
archives: List[str] = field(default_factory=list)
elf_files: List[str] = field(default_factory=list)
total_files: int = 0
scan_time: float = 0.0
def scan_directory(
directory: str,
include_patterns: List[str] = None,
exclude_patterns: List[str] = None,
recursive: bool = True,
) -> ScanResult:
"""
Scan directory for supported files.
Args:
directory: Directory to scan
include_patterns: Only include files matching these patterns
exclude_patterns: Exclude files matching these patterns
recursive: Whether to scan recursively
"""
result = ScanResult()
start_time = time.time()
# Supported extensions
patterns = ["*.a", "*.lib", "*.so", "*.so.*", "*.elf", "*.axf", "*.out", "*.o"]
# Find all matching files
all_files = []
for pattern in patterns:
if recursive:
search_pattern = os.path.join(directory, "**", pattern)
all_files.extend(glob.glob(search_pattern, recursive=True))
else:
search_pattern = os.path.join(directory, pattern)
all_files.extend(glob.glob(search_pattern))
# Apply filters
for filepath in sorted(set(all_files)):
basename = os.path.basename(filepath)
# Check include patterns
if include_patterns:
if not any(matches_pattern(basename, p) for p in include_patterns):
continue
# Check exclude patterns
if exclude_patterns:
if any(matches_pattern(basename, p) for p in exclude_patterns):
continue
# Categorize by type
file_type = get_file_type(filepath)
if file_type == FileType.ARCHIVE:
result.archives.append(filepath)
elif file_type == FileType.ELF:
result.elf_files.append(filepath)
result.total_files += 1
result.scan_time = time.time() - start_time
return result
def matches_pattern(filename: str, pattern: str) -> bool:
"""Check if filename matches shell-style pattern"""
import fnmatch
return fnmatch.fnmatch(filename, pattern)
# ============================================================
# Archive Processing
# ============================================================
def extract_archive(archive_path: str, output_dir: str) -> List[str]:
"""Extract .o files from a .a archive"""
os.makedirs(output_dir, exist_ok=True)
# Convert to absolute path before changing directory
archive_path = os.path.abspath(archive_path)
orig_dir = os.getcwd()
try:
os.chdir(output_dir)
result = subprocess.run(
["ar", "x", archive_path], capture_output=True, text=True
)
if result.returncode != 0:
raise RuntimeError(f"ar extraction failed: {result.stderr}")
return sorted(glob.glob("*.o"))
finally:
os.chdir(orig_dir)
def list_archive_contents(archive_path: str) -> List[str]:
"""List contents of an archive without extracting"""
result = subprocess.run(["ar", "t", archive_path], capture_output=True, text=True)
if result.returncode != 0:
raise RuntimeError(f"Failed to list archive: {result.stderr}")
return result.stdout.strip().split("\n")
# ============================================================
# Decompilation
# ============================================================
@dataclass
class DecompileResult:
"""Result of decompiling a single file"""
input_file: str
output_file: str
success: bool = False
skipped: bool = False
lines: int = 0
error: Optional[str] = None
duration: float = 0.0
@dataclass
class BatchResult:
"""Result of batch decompilation"""
total: int = 0
success: int = 0
failed: int = 0
skipped: int = 0
total_lines: int = 0
duration: float = 0.0
results: List[DecompileResult] = field(default_factory=list)
failed_files: List[str] = field(default_factory=list)
def decompile_object_file(
obj_file: str,
output_dir: str,
ghidra_headless: str,
decompile_script: str,
project_dir: str,
skip_existing: bool = True,
timeout: int = 300,
processor: Optional[str] = None,
cspec: Optional[str] = None,
logs_dir: Optional[str] = None,
include_dir: Optional[str] = None,
) -> DecompileResult:
"""
Decompile a single object file using Ghidra Headless mode.
Args:
obj_file: Path to the object file to decompile
output_dir: Directory to write decompiled output
ghidra_headless: Path to Ghidra analyzeHeadless
decompile_script: Path to the Ghidra decompile script
project_dir: Directory for temporary Ghidra projects
skip_existing: Skip if output file already exists
timeout: Timeout in seconds for Ghidra processing
processor: Ghidra processor ID (e.g., "ARM:LE:32:v7")
cspec: Ghidra compiler spec (e.g., "default", "gcc")
logs_dir: Directory to save Ghidra logs (optional)
include_dir: Directory for header files (optional)
"""
basename = os.path.splitext(os.path.basename(obj_file))[0]
output_file = os.path.join(output_dir, f"{basename}.cpp")
result = DecompileResult(input_file=obj_file, output_file=output_file)
start_time = time.time()
# Skip if already exists
if skip_existing and os.path.isfile(output_file):
with open(output_file, "r") as f:
result.lines = sum(1 for _ in f)
result.success = True
result.skipped = True
result.duration = time.time() - start_time
return result
# Create unique project name
proj_name = f"proj_{basename}_{os.getpid()}"
try:
# Find DWARF configuration script
script_dir = os.path.dirname(os.path.abspath(__file__))
dwarf_script = os.path.join(script_dir, "ghidra_enable_dwarf.py")
cmd = [
ghidra_headless,
project_dir,
proj_name,
"-import",
obj_file,
]
# Add processor and compiler spec if specified
if processor:
cmd.extend(["-processor", processor])
if cspec:
cmd.extend(["-cspec", cspec])
# Add pre-script to configure DWARF options (if exists)
if os.path.isfile(dwarf_script):
cmd.extend(["-preScript", dwarf_script])
cmd.extend(
[
"-postScript",
decompile_script,
output_dir,
include_dir if include_dir else output_dir,
"-deleteProject",
]
)
proc_result = subprocess.run(
cmd, capture_output=True, text=True, timeout=timeout
)
# Save Ghidra log if logs_dir is specified
if logs_dir:
log_file = os.path.join(logs_dir, f"{basename}_ghidra.log")
with open(log_file, "w") as f:
f.write(f"=== Command ===\n{' '.join(cmd)}\n\n")
f.write(f"=== Return Code ===\n{proc_result.returncode}\n\n")
if proc_result.stdout:
f.write(f"=== STDOUT ===\n{proc_result.stdout}\n\n")
if proc_result.stderr:
f.write(f"=== STDERR ===\n{proc_result.stderr}\n")
# Check for output file
temp_output = os.path.join(output_dir, f"{basename}_decompiled.cpp")
if os.path.isfile(temp_output):
shutil.move(temp_output, output_file)
# Apply DWARF debug info post-processing
try:
from dwarf_parser import apply_dwarf_to_code, parse_dwarf_info
dwarf_info = parse_dwarf_info(obj_file)
if dwarf_info.has_local_vars:
with open(output_file, "r") as f:
code = f.read()
enhanced_code = apply_dwarf_to_code(code, dwarf_info)
with open(output_file, "w") as f:
f.write(enhanced_code)
except ImportError:
pass # DWARF parser not available
except Exception:
pass # DWARF processing failed, keep original
with open(output_file, "r") as f:
result.lines = sum(1 for _ in f)
result.success = True
else:
result.error = "No output file generated"
except subprocess.TimeoutExpired:
result.error = f"Timeout ({timeout}s)"
except Exception as e:
result.error = str(e)
result.duration = time.time() - start_time
return result
def process_archive(
archive_path: str,
output_base: str,
ghidra_path: str,
jobs: int = 1,
skip_existing: bool = True,
evaluate: bool = False,
) -> BatchResult:
"""
Process a static library archive.
Args:
archive_path: Path to .a archive
output_base: Base output directory
ghidra_path: Path to Ghidra installation
jobs: Number of parallel jobs
skip_existing: Skip already decompiled files
evaluate: Run quality evaluation after decompilation
"""
archive_name = os.path.splitext(os.path.basename(archive_path))[0]
output_dir = os.path.join(output_base, archive_name)
src_dir = os.path.join(output_dir, "src")
include_dir = os.path.join(output_dir, "include")
logs_dir = os.path.join(output_dir, "logs")
os.makedirs(src_dir, exist_ok=True)
os.makedirs(include_dir, exist_ok=True)
os.makedirs(logs_dir, exist_ok=True)
print()
print(draw_box(f"Processing Archive: {archive_name}", f"Jobs: {jobs}"))
print()
# Validate Ghidra
ghidra_headless = os.path.join(ghidra_path, "support", "analyzeHeadless")
# On Windows, use .bat extension
if sys.platform == "win32":
ghidra_headless += ".bat"
if not os.path.isfile(ghidra_headless):
raise FileNotFoundError(f"Ghidra analyzeHeadless not found: {ghidra_headless}")
# Find decompile script
script_dir = os.path.dirname(os.path.abspath(__file__))
decompile_script = os.path.join(script_dir, "ghidra_decompile_lib.py")
if not os.path.isfile(decompile_script):
raise FileNotFoundError(f"Decompile script not found: {decompile_script}")
# Extract archive
temp_extract_dir = tempfile.mkdtemp(prefix="libsurgeon_")
project_dir = os.path.join(output_dir, ".ghidra_projects")
os.makedirs(project_dir, exist_ok=True)
try:
log_step(f"Extracting archive: {archive_path}")
extract_archive(archive_path, temp_extract_dir)
obj_files = sorted(glob.glob(os.path.join(temp_extract_dir, "*.o")))
total = len(obj_files)
log_info(f"Found {total} object files")
# Detect architecture from first object file
processor = None
cspec = None
debug_info = None
if obj_files:
arch_info = detect_elf_architecture(obj_files[0])
if arch_info:
processor, cspec = arch_info
log_info(f"Detected architecture: {processor}")
else:
log_warn("Could not detect architecture, using Ghidra auto-detection")
# Detect debug information
debug_info = detect_debug_info(obj_files[0])
if debug_info.has_debug:
log_info(
f"{Colors.GREEN}Debug information detected: {debug_info.format}{Colors.NC}"
)
if debug_info.version:
log_info(f" DWARF version: {debug_info.version}")
if debug_info.has_local_vars:
log_info(
f" {Colors.GREEN}Local variable names available{Colors.NC}"
)
if debug_info.compiler:
log_info(f" Compiler: {debug_info.compiler[:60]}...")
if debug_info.sections:
log_info(f" Debug sections: {', '.join(debug_info.sections[:5])}")
else:
log_info(
"No debug information found - variable names will be auto-generated"
)
print() # Space for progress bar
print()
batch_result = BatchResult(total=total)
start_time = time.time()
completed = 0
def update_batch_result(result: DecompileResult, basename: str):
"""Update batch result with decompile result"""
nonlocal completed
batch_result.results.append(result)
if result.success:
batch_result.success += 1
if result.skipped:
batch_result.skipped += 1
batch_result.total_lines += result.lines
else:
batch_result.failed += 1
batch_result.failed_files.append(basename)
completed += 1
elapsed = int(time.time() - start_time)
eta = 0
if completed > 0:
avg_time = elapsed / completed
eta = int((total - completed) * avg_time)
status = (
"Skipped"
if result.skipped
else ("FAILED" if not result.success else "Done")
)
filename = f"{basename}.o ({status}, {result.lines} lines)"
show_progress(completed, total, elapsed, filename, eta)
if jobs == 1:
# Sequential processing
for obj_file in obj_files:
basename = os.path.splitext(os.path.basename(obj_file))[0]
result = decompile_object_file(
obj_file,
src_dir,
ghidra_headless,
decompile_script,
project_dir,
skip_existing,
processor=processor,
cspec=cspec,
logs_dir=logs_dir,
include_dir=include_dir,
)
update_batch_result(result, basename)
else:
# Parallel processing
with ThreadPoolExecutor(max_workers=jobs) as executor:
futures = {}
for obj_file in obj_files:
future = executor.submit(
decompile_object_file,
obj_file,
src_dir,
ghidra_headless,
decompile_script,
project_dir,
skip_existing,
processor=processor,
cspec=cspec,
logs_dir=logs_dir,
include_dir=include_dir,
)
futures[future] = obj_file
for future in as_completed(futures):
obj_file = futures[future]
basename = os.path.splitext(os.path.basename(obj_file))[0]
try:
result = future.result()
except Exception as e:
result = DecompileResult(
input_file=obj_file,
output_file="",
success=False,
error=str(e),
)
update_batch_result(result, basename)
batch_result.duration = time.time() - start_time
# Show final progress
show_progress_final(total, int(batch_result.duration))
finally:
# Cleanup
if os.path.isdir(temp_extract_dir):
shutil.rmtree(temp_extract_dir)
# Generate README
generate_archive_readme(archive_name, output_dir, batch_result)
# Log failed files
if batch_result.failed_files:
failed_log = os.path.join(logs_dir, "failed_files.txt")
with open(failed_log, "w") as f:
for name in batch_result.failed_files:
f.write(f"{name}\n")
# Generate master header file
generate_master_header_for_archive(archive_name, include_dir)
# Run quality evaluation
if evaluate:
run_quality_evaluation(src_dir, output_dir)
return batch_result