-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathpcileech.py
More file actions
1797 lines (1570 loc) · 60.4 KB
/
pcileech.py
File metadata and controls
1797 lines (1570 loc) · 60.4 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
"""
PCILeech Firmware Generator - Unified Entry Point
This is the single entry point for all PCILeech functionality with automatic
dependency checking and installation.
"""
import argparse
import importlib
import logging
import os
import platform
import subprocess
import sys
import shutil
from pathlib import Path
from types import SimpleNamespace
# Add project root to path for imports (use absolute path to avoid symlink issues)
project_root = Path(__file__).resolve().parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / "src"))
# Create pcileechfwgenerator namespace mapping for direct script execution
# This is needed because pyproject.toml maps pcileechfwgenerator -> src/
# but that only works when the package is installed via pip
_src_path = project_root / "src"
if _src_path.exists() and "pcileechfwgenerator" not in sys.modules:
import importlib.util
# Check if package is already installed (editable or regular install)
_spec = importlib.util.find_spec("pcileechfwgenerator")
if _spec is None:
# Package not installed, create the namespace mapping manually
# This allows "from pcileechfwgenerator.x import y" to work as "from src.x import y"
import types
_pkg = types.ModuleType("pcileechfwgenerator")
_pkg.__path__ = [str(_src_path)]
_pkg.__file__ = str(_src_path / "__init__.py")
sys.modules["pcileechfwgenerator"] = _pkg
def get_version():
"""Get the current version from the centralized version resolver."""
try:
from pcileechfwgenerator.utils.version_resolver import get_version_info
version_info = get_version_info()
title = version_info.get("title", "PCILeech Firmware Generator")
version = version_info.get("version", "unknown")
return f"{title} v{version}"
except (ImportError, AttributeError, KeyError):
return "PCILeech Firmware Generator (version unknown)"
class RequirementsError(Exception):
"""Raised when requirements cannot be satisfied."""
pass
def _is_interactive_stdin() -> bool:
"""Check if stdin is interactive (safe for all environments)."""
try:
return sys.stdin.isatty()
except (AttributeError, OSError, ValueError):
return False
def check_and_install_requirements():
"""Check if all requirements are installed and optionally install them."""
requirements_file = project_root / "requirements.txt"
if not requirements_file.exists():
print("Warning: requirements.txt not found")
return True
# Parse requirements.txt
missing_packages = []
with open(requirements_file, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
# Handle different requirement formats
package_name = (
line.split("==")[0]
.split(">=")[0]
.split("<=")[0]
.split("~=")[0]
.split("!=")[0]
)
package_name = package_name.strip()
# Skip git+https and other URL-based requirements for now
if package_name.startswith(("git+", "http://", "https://", "-e")):
continue
# Check if package is importable
if not is_package_available(package_name):
missing_packages.append(line.strip())
if not missing_packages:
return True
print("\nMissing required packages:")
for pkg in missing_packages:
print(f" • {pkg}")
# Ask user if they want to install
if os.getenv("PCILEECH_AUTO_INSTALL") == "1":
install = True
else:
print("\nInstallation options:")
print(" 1. Auto-install missing packages (requires pip)")
print(" 2. Exit and install manually")
print(" 3. Continue anyway (may cause errors)")
if not _is_interactive_stdin():
print(
"\nError: Non-interactive environment detected.\n"
"Set PCILEECH_AUTO_INSTALL=1 to auto-install or run in an interactive terminal."
)
sys.exit(1)
choice = input("\nChoice [1/2/3]: ").strip()
install = choice == "1"
if choice == "2":
print(f"\nTo install manually:\n pip install -r {requirements_file}")
print("\nTip: Set PCILEECH_AUTO_INSTALL=1 to auto-install next time")
sys.exit(1)
elif choice == "3":
print("Warning: Continuing without installing dependencies")
return False
if install:
return install_requirements(requirements_file)
return False
def is_package_available(package_name):
"""Check if a package is available for import."""
if not package_name:
return False
# Handle package name mappings (PyPI name vs import name)
import_mappings = {
"pyyaml": "yaml",
"pillow": "PIL",
"beautifulsoup4": "bs4",
"python-dateutil": "dateutil",
"msgpack": "msgpack",
"protobuf": "google.protobuf",
"pycryptodome": "Crypto",
"pyserial": "serial",
"python-magic": "magic",
"opencv-python": "cv2",
"scikit-learn": "sklearn",
"matplotlib": "matplotlib", # not matplotlib.pyplot to avoid backend init
}
import_name = import_mappings.get(package_name.lower(), package_name)
if not import_name:
return False
try:
importlib.import_module(import_name)
return True
except (ImportError, ModuleNotFoundError, ValueError):
# Try alternative import patterns
alternatives = [
package_name.replace("-", "_"),
package_name.replace("_", "-"),
package_name.lower(),
]
for alt_name in alternatives:
try:
importlib.import_module(alt_name)
return True
except (ImportError, ModuleNotFoundError, ValueError):
continue
return False
def install_requirements(requirements_file):
"""Install requirements using pip."""
print(f"\nInstalling requirements from {requirements_file}...")
try:
# Use current Python interpreter to ensure we install to the right environment
cmd = [sys.executable, "-m", "pip", "install", "-r", str(requirements_file)]
# Check if we're in a virtual environment
in_venv = hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix
)
if in_venv:
print("Detected virtual environment")
else:
print(
"Warning: Installing to system Python (consider using a virtual environment)\n"
"Note: Python 3.12+/Debian 12+ may show 'externally-managed-environment' errors.\n"
"See docs/installation-python312.md for details."
)
# Ask for confirmation for system-wide install
if os.getenv("PCILEECH_AUTO_INSTALL") != "1":
if not _is_interactive_stdin():
print("Non-interactive shell; refusing to install to system Python.")
return False
confirm = (
input("\nInstall to system Python anyway? [y/N]: ")
.strip()
.lower()
)
if confirm not in ("y", "yes"):
print(
"\nAborted. Recommended setup:\n"
f" python3 -m venv ~/.pcileech-venv\n"
f" source ~/.pcileech-venv/bin/activate\n"
f" pip install -r {requirements_file}\n"
f" sudo ~/.pcileech-venv/bin/python3 {sys.argv[0]} {' '.join(sys.argv[1:])}"
)
sys.exit(1)
# Try --user flag, but catch externally-managed-environment errors
cmd.append("--user")
# Run pip install
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode == 0:
print("Requirements installed successfully")
return True
# no-dd-sa:python-best-practices/if-return-no-else
else:
print("Failed to install requirements:")
if result.stderr:
print(f" {result.stderr}")
# Check for externally-managed-environment error
if "externally-managed-environment" in result.stderr:
print(
"\nPython 3.12+ / Debian 12+ detected with PEP 668 protection.\n\n"
"Solution 1 (Recommended): Use a virtual environment\n"
f" python3 -m venv ~/.pcileech-venv\n"
f" source ~/.pcileech-venv/bin/activate\n"
f" pip install -r {requirements_file}\n"
f" sudo ~/.pcileech-venv/bin/python3 {sys.argv[0]} {' '.join(sys.argv[1:])}\n\n"
"Solution 2: Use pipx\n"
f" pipx install pcileechfwgenerator[tui]\n"
f" sudo $(which pcileech) tui\n\n"
"Solution 3: Override (not recommended)\n"
f" pip install --break-system-packages -r {requirements_file}\n\n"
"See: site/docs/installation-python312.md for detailed instructions"
)
else:
print(f"\nTry installing manually:\n pip install -r {requirements_file}")
return False
except FileNotFoundError:
print("Error: pip not found. Please install pip first.")
return False
except subprocess.SubprocessError as e:
print(f"Error during installation process: {e}")
return False
except (OSError, PermissionError) as e:
print(f"Error: Cannot write to installation directory: {e}")
return False
except Exception as e:
print(f"Unexpected error installing requirements: {e}")
return False
def check_critical_imports():
"""Check for imports that are absolutely required for basic functionality.
Only checks TUI dependencies if the 'tui' command is being used.
"""
# Check if user is trying to run TUI command
is_tui_command = len(sys.argv) > 1 and sys.argv[1] == "tui"
critical_packages = {
"psutil": "System information (install with: pip install psutil)",
}
# Only require textual/rich for TUI command
if is_tui_command:
critical_packages["textual"] = "TUI functionality (install with: pip install textual)"
critical_packages["rich"] = "Rich text display (install with: pip install rich)"
missing_critical = []
for package, description in critical_packages.items():
if not is_package_available(package):
missing_critical.append((package, description))
return missing_critical
def safe_import_with_fallback(module_name, fallback_msg=None):
"""Safely import a module with a helpful error message."""
try:
return importlib.import_module(module_name)
except (ImportError, ModuleNotFoundError) as e:
if fallback_msg:
print(f"Error: {fallback_msg}")
else:
print(
f"Error: Required module '{module_name}' not available\n"
f" Install with: pip install {module_name}"
)
raise RequirementsError(
f"Missing required module: {module_name}"
) from e
# Early requirements check before any other imports
if __name__ == "__main__":
pass # Requirements check moved to main() after argparse
# Import our custom utilities (after requirements check)
try:
from pcileechfwgenerator.log_config import get_logger, setup_logging
from pcileechfwgenerator.string_utils import (
log_debug_safe,
log_error_safe,
log_info_safe,
log_warning_safe,
safe_format,
)
from pcileechfwgenerator.utils.validation_constants import KNOWN_DEVICE_TYPES
except (ImportError, ModuleNotFoundError) as e:
print(
f"Error: Failed to import PCILeech modules: {e}\n"
"Make sure you're running from the PCILeech project directory"
)
sys.exit(1)
def get_available_boards():
"""Get list of available board configurations."""
try:
from pcileechfwgenerator.device_clone.board_config import list_supported_boards
boards = list_supported_boards()
return sorted(boards) if boards else get_fallback_boards()
except (ImportError, AttributeError, ValueError):
return get_fallback_boards()
def get_fallback_boards():
"""Get fallback board list when discovery fails."""
from pcileechfwgenerator.device_clone.constants import BOARD_FALLBACKS
return sorted(list(BOARD_FALLBACKS))
def check_sudo():
"""Check if running as root and warn if not."""
logger = get_logger(__name__)
if not hasattr(os, "geteuid"):
# Non-POSIX system (e.g., Windows)
log_warning_safe(
logger, "Non-POSIX OS detected; root check skipped", prefix="SUDO"
)
return False
if os.geteuid() != 0:
log_warning_safe(
logger,
"Root privileges required for hardware access. Please run with sudo or as root user.",
prefix="SUDO",
)
return False
return True
def check_vfio_requirements():
"""Check if VFIO modules are loaded and rebuild constants."""
logger = get_logger(__name__)
try:
# Check if VFIO modules are loaded
with open("/proc/modules", "r") as f:
modules = f.read()
if "vfio " not in modules or "vfio_pci " not in modules:
log_warning_safe(
logger,
"VFIO modules not loaded. Run: sudo modprobe vfio vfio-pci",
prefix="VFIO"
)
return False
except (FileNotFoundError, PermissionError, OSError):
# /proc/modules not available or inaccessible, skip check
pass
# Always rebuild VFIO constants to ensure they match the current kernel
log_info_safe(
logger, "Rebuilding VFIO constants for current kernel...", prefix="VFIO"
)
if not rebuild_vfio_constants():
log_warning_safe(
logger,
"VFIO constants rebuild failed - may cause ioctl errors",
prefix="VFIO",
)
return True
def rebuild_vfio_constants():
"""Rebuild VFIO constants using the build script."""
logger = get_logger(__name__)
script = project_root / "build_vfio_constants.sh"
if not script.exists():
log_warning_safe(
logger,
safe_format("VFIO constants script missing: {script}", script=script),
prefix="VFIO"
)
return False
if not os.access(script, os.X_OK):
log_warning_safe(
logger,
safe_format("VFIO constants script not executable: {script}", script=script),
prefix="VFIO"
)
return False
try:
result = subprocess.run(
[str(script)],
capture_output=True,
text=True,
cwd=project_root,
timeout=60,
)
if result.returncode == 0:
log_info_safe(logger, "VFIO constants rebuilt successfully", prefix="VFIO")
return True
else:
error_detail = (result.stderr or result.stdout or "").strip()
if not error_detail:
error_detail = safe_format(
"script exited with code {code} (no output captured - "
"ensure gcc and linux-headers are installed)",
code=result.returncode,
)
log_warning_safe(
logger,
safe_format(
"VFIO constants rebuild failed: {error}", error=error_detail
),
prefix="VFIO",
)
return False
except subprocess.TimeoutExpired:
log_warning_safe(logger, "VFIO constants rebuild timed out", prefix="VFIO")
return False
except subprocess.SubprocessError as e:
log_warning_safe(
logger,
safe_format("VFIO constants rebuild failed: {error}", error=str(e)),
prefix="VFIO",
)
return False
except (OSError, PermissionError) as e:
log_warning_safe(
logger,
safe_format(
"VFIO constants script execution error: {error}", error=str(e)
),
prefix="VFIO",
)
return False
def create_parser():
"""Create the main argument parser with subcommands."""
# Determine script name for auto-command detection
script_name = Path(sys.argv[0]).name
parser = argparse.ArgumentParser(
prog="pcileech",
description="PCILeech Firmware Generator - Unified Entry Point",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Commands:
build Build firmware (CLI mode)
tui Launch interactive TUI
flash Flash firmware to device
check Check VFIO configuration and ACS bypass requirements
donor-template Generate donor info template
version Show version information
Examples:
# Interactive TUI mode
sudo python3 pcileech.py tui
# CLI build mode
sudo python3 pcileech.py build --bdf 0000:03:00.0 --board pcileech_35t325_x1
# Check VFIO configuration
sudo python3 pcileech.py check --device 0000:03:00.0
# Flash firmware
sudo python3 pcileech.py flash firmware.bin
# Generate donor template
sudo python3 pcileech.py donor-template --save-to my_device.json
Environment Variables:
PCILEECH_AUTO_INSTALL=1 Automatically install missing dependencies
PCILEECH_AUTO_CONTAINER=1 Skip container mode prompt (auto-select container)
NO_INTERACTIVE=1 Disable all interactive prompts
CI=1 CI mode (implies NO_INTERACTIVE)
""",
)
# Add global options
parser.add_argument("--version", action="version", version=get_version())
parser.add_argument(
"--verbose", "-v", action="store_true", help="Enable verbose logging"
)
parser.add_argument(
"--quiet", "-q", action="store_true", help="Suppress non-error messages"
)
parser.add_argument(
"--skip-requirements-check",
action="store_true",
help="Skip automatic requirements checking",
)
# Auto-detect command from script name for console scripts
auto_command = None
if script_name == "pcileech-build":
auto_command = "build"
elif script_name == "pcileech-tui":
auto_command = "tui"
elif script_name == "pcileech-generate":
auto_command = "build" # generate is just an alias for build
# Create subparsers for different modes
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Build command (CLI mode)
build_parser = subparsers.add_parser("build", help="Build firmware (CLI mode)")
build_parser.add_argument(
"--bdf", required=True, help="PCI Bus:Device.Function (e.g., 0000:03:00.0)"
)
build_parser.add_argument(
"--board",
required=True,
help="Target board configuration",
)
build_parser.add_argument(
"--advanced-sv",
action="store_true",
help="Enable advanced SystemVerilog features",
)
build_parser.add_argument(
"--enable-variance", action="store_true", help="Enable manufacturing variance"
)
build_parser.add_argument(
"--enable-error-injection",
action="store_true",
help=(
"Enable hardware error injection test hooks (AER). "
"Use only in controlled test environments."
),
)
build_parser.add_argument(
"--build-dir", default="build", help="Directory for generated firmware files"
)
build_parser.add_argument(
"--generate-donor-template",
help="Generate donor info JSON template alongside build artifacts",
)
build_parser.add_argument(
"--donor-template",
help="Use donor info JSON template to override discovered values",
)
build_parser.add_argument(
"--device-type",
choices=KNOWN_DEVICE_TYPES,
default="generic",
help="Override device type detection (default: auto-detect from class code)",
)
build_parser.add_argument(
"--vivado-path",
help="Manual path to Vivado installation directory (e.g., /tools/Xilinx/2025.1/Vivado)",
)
build_parser.add_argument(
"--vivado-jobs",
type=int,
default=4,
help="Number of parallel jobs for Vivado builds (default: 4)",
)
build_parser.add_argument(
"--vivado-timeout",
type=int,
default=3600,
help="Timeout for Vivado operations in seconds (default: 3600)",
)
build_parser.add_argument(
"--host-collect-only",
action="store_true",
help="Stage 1: collect PCIe data on host and exit (no build)",
)
build_parser.add_argument(
"--local",
action="store_true",
help="Run full pipeline locally instead of container",
)
build_parser.add_argument(
"--datastore",
default="pcileech_datastore",
help="Host dir for device_context.json and outputs",
)
build_parser.add_argument(
"--no-mmio-learning",
action="store_true",
help="Disable MMIO trace capture for BAR register learning",
)
build_parser.add_argument(
"--force-recapture",
action="store_true",
help="Force recapture of MMIO traces even if cached models exist",
)
build_parser.add_argument(
"--container-mode",
choices=["auto", "container", "local"],
default="auto",
help=(
"Templating execution mode: 'auto' (detect best, prompt if needed), "
"'container' (isolated, requires podman/docker), "
"'local' (direct execution). Default: auto"
),
)
# TUI command
tui_parser = subparsers.add_parser("tui", help="Launch interactive TUI")
tui_parser.add_argument("--profile", help="Load configuration profile on startup")
# Flash command
flash_parser = subparsers.add_parser("flash", help="Flash firmware to device")
flash_parser.add_argument("firmware", help="Path to firmware file")
flash_parser.add_argument("--board", help="Board type for flashing")
flash_parser.add_argument("--device", help="USB device for flashing")
# Check command (VFIO)
check_parser = subparsers.add_parser(
"check", help="Check VFIO configuration and ACS bypass requirements"
)
check_parser.add_argument("--device", help="Specific device to check (BDF format)")
check_parser.add_argument(
"--interactive", "-i", action="store_true", help="Interactive remediation mode"
)
check_parser.add_argument(
"--fix", action="store_true", help="Attempt to fix issues automatically"
)
# Version command
subparsers.add_parser("version", help="Show version information")
# Donor template command
donor_parser = subparsers.add_parser(
"donor-template", help="Generate donor info template"
)
donor_parser.add_argument(
"--save-to",
default="donor_info_template.json",
help="File path to save template (default: donor_info_template.json)",
)
donor_parser.add_argument(
"--compact",
action="store_true",
help="Generate compact JSON without indentation",
)
donor_parser.add_argument(
"--blank",
action="store_true",
help="Generate minimal template with only essential fields",
)
donor_parser.add_argument(
"--bdf", help="Pre-fill template with device info from specified BDF"
)
donor_parser.add_argument("--validate", help="Validate an existing donor info file")
# Set auto-detected command as default
if auto_command and not any(arg in sys.argv for arg in subparsers.choices):
parser.set_defaults(command=auto_command)
return parser
def main():
"""Main entry point."""
# Parse args early to check for skip flag
parser = create_parser()
args = parser.parse_args()
# Skip requirements check if requested
if not args.skip_requirements_check:
try:
requirements_ok = check_and_install_requirements()
# Check critical packages that might not be in requirements.txt
missing_critical = check_critical_imports()
if missing_critical:
print("\n❌ Critical packages missing:")
for package, description in missing_critical:
print(f" - {package}: {description}")
if not requirements_ok:
print("\nPlease install missing packages and try again.")
return 1
except KeyboardInterrupt:
print("\nInstallation interrupted by user")
return 1
except RequirementsError:
return 1
except (OSError, IOError) as e:
print(f"Error accessing requirements file: {e}")
return 1
except Exception as e:
print(f"Unexpected error during requirements check: {e}")
return 1
# Setup logging with our custom configuration
if args.verbose:
setup_logging(level=logging.DEBUG)
elif args.quiet:
setup_logging(level=logging.ERROR)
else:
setup_logging(level=logging.INFO)
logger = get_logger(__name__)
# Detect OS for platform-specific checks
is_linux = platform.system().lower() == "linux"
# Handle console script auto-command detection
if not args.command:
script_name = Path(sys.argv[0]).name
if script_name == "pcileech-build":
args.command = "build"
elif script_name == "pcileech-tui":
args.command = "tui"
elif script_name == "pcileech-generate":
args.command = "build"
else:
# No command specified, show help
parser.print_help()
return 1
# Check sudo requirements for hardware operations (Linux only)
if args.command in ["build", "check"]:
if not is_linux:
log_error_safe(logger, "This command requires Linux.", prefix="MAIN")
return 1
if not check_sudo():
log_error_safe(
logger,
"Root privileges required for hardware operations.",
prefix="MAIN",
)
return 1
# Check VFIO requirements for build operations (Linux only)
if args.command == "build" and is_linux and not check_vfio_requirements():
log_error_safe(
logger,
"Run 'sudo python3 pcileech.py check' to validate VFIO setup.",
prefix="MAIN",
)
return 1
# Route to appropriate handler with safe imports
try:
if args.command == "build":
return handle_build(args)
elif args.command == "tui":
return handle_tui(args)
elif args.command == "flash":
return handle_flash(args)
elif args.command == "check":
return handle_check(args)
elif args.command == "version":
return handle_version(args)
elif args.command == "donor-template":
return handle_donor_template(args)
else:
# No command specified, show help
parser.print_help()
return 1
except RequirementsError:
return 1
def handle_build(args):
"""Handle CLI build mode."""
logger = get_logger(__name__)
try:
# Validate board before proceeding
valid_boards = set(get_available_boards())
if args.board not in valid_boards:
print(
f"Error: Unknown board '{args.board}'\n"
f"Valid options: {', '.join(sorted(valid_boards))}"
)
return 1
# Stage 1: host-only data collection
if getattr(args, "host_collect_only", False):
return run_host_collect(args)
# If datastore exists we assume stages 1 done; otherwise run it now
datastore = Path(args.datastore)
device_ctx = datastore / "device_context.json"
if not device_ctx.exists():
log_info_safe(
logger,
"No datastore found; running host collect now",
prefix="BUILD",
)
rc = run_host_collect(args)
if rc != 0:
return rc
# Stage 2: templating / parsing (container or local)
container_mode = getattr(args, "container_mode", "auto")
if container_mode == "local" or getattr(args, "local", False):
rc = run_local_templating(args)
else:
# auto or container - will be resolved in run_container_templating
rc = run_container_templating(args)
if rc != 0:
return rc
# Stage 3: host-side Vivado batch
return run_host_vivado(args)
except KeyboardInterrupt:
log_error_safe(logger, "Build interrupted by user", prefix="BUILD")
return 1
except (ImportError, ModuleNotFoundError) as e:
log_error_safe(
logger,
safe_format("Required module not available: {error}", error=str(e)),
prefix="BUILD",
)
return 1
except Exception as e:
from pcileechfwgenerator.error_utils import log_error_with_root_cause
log_error_with_root_cause(logger, "Build failed", e)
return 1
# ──────────────────────────────────────────────────────────────────────────────
# Orchestration helpers: host collect → templating (container/local) → Vivado
# ──────────────────────────────────────────────────────────────────────────────
def run_host_collect(args):
"""Stage 1: probe device and write datastore on the host."""
logger = get_logger(__name__)
try:
from pcileechfwgenerator.host_collect.collector import HostCollector
except (ImportError, ModuleNotFoundError) as e:
log_error_safe(
logger,
safe_format("Host collector module not found: {err}", err=str(e)),
prefix="BUILD",
)
return 1
datastore = Path(getattr(args, "datastore", "pcileech_datastore")).resolve()
datastore.mkdir(parents=True, exist_ok=True)
# Ensure output directory exists with proper permissions for container access
output_dir = datastore / "output"
output_dir.mkdir(parents=True, exist_ok=True)
# Set permissions to allow container writes (0o755 = rwxr-xr-x)
output_dir.chmod(0o755)
# Get MMIO learning flags
enable_mmio_learning = not getattr(args, "no_mmio_learning", False)
force_recapture = getattr(args, "force_recapture", False)
log_info_safe(
logger,
"Stage 1: Collecting device data on host (VFIO operations enabled)",
prefix="BUILD",
)
collector = HostCollector(
args.bdf,
datastore,
logger,
enable_mmio_learning=enable_mmio_learning,
force_recapture=force_recapture,
)
rc = collector.run()
if rc == 0:
log_info_safe(
logger,
safe_format("Host collect complete → {path}", path=str(datastore)),
prefix="BUILD",
)
return rc
def _ensure_container_image(runtime: str, logger, tag: str = "pcileech-fwgen") -> bool:
"""Always rebuild the container image to ensure latest code is used."""
try:
log_info_safe(
logger,
safe_format("Building container image: {tag} (always rebuilds for consistency)", tag=tag),
prefix="BUILD",
)
build = subprocess.run(
[runtime, "build", "--no-cache", "-t", tag, "-f", "Containerfile", "."],
cwd=str(project_root),
)
return build.returncode == 0
except subprocess.SubprocessError as e:
log_error_safe(
logger,
safe_format("Container build process failed: {err}", err=str(e)),
prefix="BUILD",
)
return False
except (OSError, FileNotFoundError) as e:
log_error_safe(
logger,
safe_format(
"Container runtime or Containerfile not found: {err}", err=str(e)
),
prefix="BUILD",
)
return False
def run_container_templating(args):
"""Stage 2a: launch container with datastore mounted to run templating."""
logger = get_logger(__name__)
datastore = Path(getattr(args, "datastore", "pcileech_datastore")).resolve()
output_dir = datastore / "output"
output_dir.mkdir(parents=True, exist_ok=True)
# Determine execution mode
mode = getattr(args, "container_mode", "auto")
runtime = _detect_container_runtime()
can_use_container = runtime is not None
# Log workflow explanation
log_info_safe(
logger,
"Stage 2: Template generation from collected device data",
prefix="BUILD"
)
# Resolve mode (logging happens in helper functions)
if mode == "container":
if not can_use_container:
log_error_safe(
logger,
"Container mode requested but no podman/docker available",
prefix="BUILD"
)
return 1
use_container = True
elif mode == "local":
use_container = False
else: # mode == "auto"
if not can_use_container:
use_container = False
else:
# Both options available - check if interactive (logs decision)
use_container = _choose_container_mode(runtime, logger)
# Single logging point for final decision
if use_container:
log_info_safe(
logger,
safe_format(
"Using container mode with {rt} (VFIO not needed - using host data)",
rt=runtime