forked from nanvix/nanvix
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathz.py
More file actions
1439 lines (1191 loc) · 48.5 KB
/
Copy pathz.py
File metadata and controls
1439 lines (1191 loc) · 48.5 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
# Copyright(c) The Maintainers of Nanvix.
# Licensed under the MIT License.
"""Nanvix Unified Build System Backend.
This script is the single backend that drives all Nanvix build operations on both Linux and
Windows. The shell wrappers (z, z.ps1, z.bat) are thin shims that invoke this script.
All builds are driven through the project Makefile.
Requirements: Python 3.10+, standard library only.
"""
from __future__ import annotations
import os
import platform
import shutil
import subprocess
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import NoReturn, Sequence
# ==================================================================================================
# Constants
# ==================================================================================================
VALID_MACHINES: tuple[str, ...] = ("microvm",)
VALID_DEPLOYMENT_MODES: tuple[str, ...] = (
"standalone",
"single-process",
"multi-process",
"l2",
)
VALID_LOG_LEVELS: tuple[str, ...] = ("trace", "debug", "info", "warn", "error", "panic")
VALID_TARGETS: tuple[str, ...] = ("x86", "x86_64")
VALID_MESSAGE_FORMATS: tuple[str, ...] = ("json", "json-diagnostic-rendered-ansi")
DEFAULT_MACHINE = "microvm"
DEFAULT_TARGET = "x86"
DEFAULT_DEPLOYMENT_MODE_LINUX = "standalone"
DEFAULT_DEPLOYMENT_MODE_WINDOWS = "standalone"
DEFAULT_LOG_LEVEL_DEBUG = "trace"
DEFAULT_LOG_LEVEL_RELEASE = "warn"
DEFAULT_TIMEOUT = 600
DEFAULT_MEMORY_SIZE = 128
DEFAULT_IMAGE = "nanvix.img"
DEFAULT_RUN_PROGRAM = "bin/hello-rust-nostd.elf"
# Known Make variables that z.py understands and may inject.
KNOWN_MAKE_VARS: frozenset[str] = frozenset(
{
"TARGET",
"MACHINE",
"RELEASE",
"DEPLOYMENT_MODE",
"LOG_LEVEL",
"TIMEOUT",
"PROFILER",
"TIMESTAMP_MSG",
"WHP",
"IMAGE",
"CLH_DIR",
"HOST_CPU",
"MAKE_NO_PRINT",
"MEMORY_SIZE",
"MESSAGE_FORMAT",
"VERBOSE",
"SCCACHE",
"SYSROOT_DIR",
"VERUS_EXECUTABLE_DIR",
}
)
# ==================================================================================================
# Logging
# ==================================================================================================
_RED = "\033[31m"
_GREEN = "\033[32m"
_YELLOW = "\033[33m"
_CYAN = "\033[36m"
_RESET = "\033[0m"
def _supports_color() -> bool:
"""Check if the terminal supports ANSI color codes."""
if os.environ.get("NO_COLOR"):
return False
if sys.platform == "win32":
# Windows Terminal and modern consoles support ANSI.
return True
return hasattr(sys.stderr, "isatty") and sys.stderr.isatty()
_COLOR = _supports_color()
def _c(code: str, text: str) -> str:
return f"{code}{text}{_RESET}" if _COLOR else text
def print_error(msg: str) -> None:
"""Print error message to stderr."""
print(f"{_c(_RED, '[ERROR]')} {msg}", file=sys.stderr)
def print_success(msg: str) -> None:
"""Print success message to stderr."""
print(f"{_c(_GREEN, '[OK]')} {msg}", file=sys.stderr)
def print_info(msg: str) -> None:
"""Print info message to stderr."""
print(f"{_c(_CYAN, '[INFO]')} {msg}", file=sys.stderr)
def print_warning(msg: str) -> None:
"""Print warning message to stderr."""
print(f"{_c(_YELLOW, '[WARN]')} {msg}", file=sys.stderr)
def die(msg: str) -> NoReturn:
"""Print error and exit with code 1."""
print_error(msg)
sys.exit(1)
# ==================================================================================================
# Platform Detection
# ==================================================================================================
@dataclass(frozen=True)
class PlatformInfo:
"""Detected platform information."""
is_windows: bool
is_linux: bool
repo_root: Path
home_dir: Path
@staticmethod
def detect(repo_root: Path) -> PlatformInfo:
is_win = sys.platform == "win32"
is_lin = sys.platform.startswith("linux")
if is_win:
home = Path(os.environ.get("USERPROFILE", os.environ.get("HOME", "")))
else:
home = Path.home()
return PlatformInfo(
is_windows=is_win, is_linux=is_lin, repo_root=repo_root, home_dir=home
)
def _is_windows_server() -> bool:
"""Detect if running on Windows Server (vs desktop Windows)."""
try:
result = subprocess.run(
[
"powershell",
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_OperatingSystem).ProductType",
],
capture_output=True,
text=True,
timeout=10,
)
# ProductType: 1=Workstation, 2=Domain Controller, 3=Server
return result.stdout.strip() != "1"
except Exception:
return False
def _assert_windows_version() -> None:
"""Warn if not running Windows 11+."""
try:
build = int(platform.version().split(".")[-1])
if build < 22000:
print_warning(
f"Windows build {build} detected. Windows 11 (build 22000+) is recommended."
)
except (ValueError, IndexError):
pass
def _assert_developer_mode() -> None:
"""Check if Windows Developer Mode is enabled."""
try:
import winreg # type: ignore[import-not-found]
key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock",
)
val, _ = winreg.QueryValueEx(key, "AllowDevelopmentWithoutDevLicense")
winreg.CloseKey(key)
if val != 1:
print_warning(
"Developer Mode is not enabled. Symlinks may not work correctly.\n"
" Enable it in Settings > Privacy & Security > For developers."
)
except Exception:
print_warning("Could not check Developer Mode status.")
def _assert_hypervisor_enabled() -> None:
"""Check if Windows Hypervisor Platform is enabled."""
try:
result = subprocess.run(
[
"powershell",
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_ComputerSystem).HypervisorPresent",
],
capture_output=True,
text=True,
timeout=10,
)
if "True" not in result.stdout:
print_warning(
"Hypervisor is not present. Enable the 'HypervisorPlatform' Windows feature:\n"
" Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform"
)
except Exception:
print_warning("Could not check hypervisor status.")
# ==================================================================================================
# Build Configuration
# ==================================================================================================
@dataclass
class BuildConfig:
"""Build configuration assembled from CLI args and platform defaults."""
machine: str = DEFAULT_MACHINE
target: str = DEFAULT_TARGET
release: bool = False
profile: bool = False
deployment_mode: str = ""
log_level: str = ""
timeout: int = DEFAULT_TIMEOUT
profiler: bool = False
timestamp_msg: bool = False
whp: bool = False
nanvix_sdk: bool = False
l2_deployment: bool = False
verus: bool = False
_user_set_toolchain_dir: bool = False
toolchain_dir: str = ""
sysroot_dir: str = ""
host_cpu: str = ""
image: str = ""
memory_size: str = ""
message_format: str = ""
verbose: bool = False
# Raw args to forward to Make (everything after --).
make_args: list[str] = field(default_factory=list)
def apply_platform_defaults(self, plat: PlatformInfo) -> None:
"""Apply platform-specific defaults that weren't set by the user."""
if not self.deployment_mode:
if plat.is_windows:
self.deployment_mode = DEFAULT_DEPLOYMENT_MODE_WINDOWS
else:
self.deployment_mode = DEFAULT_DEPLOYMENT_MODE_LINUX
if not self.log_level:
self.log_level = (
DEFAULT_LOG_LEVEL_RELEASE if self.release else DEFAULT_LOG_LEVEL_DEBUG
)
if plat.is_windows and self.machine == "microvm":
self.whp = True
if not self.toolchain_dir:
if plat.is_linux:
self.toolchain_dir = str(plat.home_dir / "toolchain")
else:
self.toolchain_dir = str(plat.repo_root / "toolchain")
# ==================================================================================================
# CLI Argument Parsing
# ==================================================================================================
def _parse_make_var(config: BuildConfig, key: str, val: str) -> None:
"""Apply a known KEY=VALUE pair to the build config."""
match key:
case "MACHINE":
if val not in VALID_MACHINES:
die(f"Invalid MACHINE={val}. Valid: {', '.join(VALID_MACHINES)}")
config.machine = val
case "TARGET":
if val not in VALID_TARGETS:
die(f"Invalid TARGET={val}. Valid: {', '.join(VALID_TARGETS)}")
config.target = val
case "RELEASE":
config.release = val.lower() == "yes"
case "DEPLOYMENT_MODE":
if val not in VALID_DEPLOYMENT_MODES:
die(
f"Invalid DEPLOYMENT_MODE={val}. Valid: {', '.join(VALID_DEPLOYMENT_MODES)}"
)
config.deployment_mode = val
case "LOG_LEVEL":
if val not in VALID_LOG_LEVELS:
die(f"Invalid LOG_LEVEL={val}. Valid: {', '.join(VALID_LOG_LEVELS)}")
config.log_level = val
case "TIMEOUT":
try:
config.timeout = int(val)
except ValueError:
die(f"Invalid TIMEOUT={val}. Must be an integer.")
case "PROFILER":
config.profiler = val.lower() == "yes"
case "TIMESTAMP_MSG":
config.timestamp_msg = val.lower() == "yes"
case "WHP":
config.whp = val.lower() == "yes"
case "HOST_CPU":
config.host_cpu = val
case "IMAGE":
config.image = val
case "MEMORY_SIZE":
try:
mb = int(val)
if mb <= 0:
die(
f"Invalid MEMORY_SIZE={val}. Must be a positive integer (megabytes)."
)
except ValueError:
die(
f"Invalid MEMORY_SIZE={val}. Must be a positive integer (megabytes)."
)
config.memory_size = val
case "MESSAGE_FORMAT":
if val not in VALID_MESSAGE_FORMATS:
die(
f"Invalid MESSAGE_FORMAT={val}. Valid: {', '.join(VALID_MESSAGE_FORMATS)}"
)
config.message_format = val
case "SYSROOT_DIR":
config.sysroot_dir = val
case "VERBOSE":
config.verbose = val.lower() == "yes"
case "SCCACHE" | "MAKE_NO_PRINT" | "VERUS_EXECUTABLE_DIR" | "CLH_DIR":
pass # Passed through to Make verbatim; no z.py-side effect.
def parse_cli(argv: Sequence[str]) -> tuple[str, BuildConfig]:
"""Parse command-line arguments into (command, config).
Arguments after the command are either recognized options (--profile, --release,
--toolchain-dir) or make arguments (targets and KEY=VALUE pairs). The ``--`` separator
is optional: the first unrecognized non-option argument starts the make_args section.
This allows PowerShell callers to omit ``--`` (PowerShell strips it in interactive mode).
"""
if not argv:
return "help", BuildConfig()
argv_list = list(argv)
config = BuildConfig()
command = ""
make_args_start = len(argv_list)
i = 0
while i < len(argv_list):
arg = argv_list[i]
if not command:
command = arg
i += 1
continue
if arg == "--":
# Explicit separator: everything after this is make_args.
make_args_start = i + 1
break
elif arg == "--profile":
config.profile = True
config.release = True
config.profiler = True
elif arg == "--release":
config.release = True
elif arg == "--nanvix-sdk":
config.nanvix_sdk = True
elif arg == "--l2-deployment":
config.l2_deployment = True
elif arg == "--verus":
config.verus = True
elif arg == "--toolchain-dir":
i += 1
if i >= len(argv_list):
die("--toolchain-dir requires a path argument.")
config.toolchain_dir = argv_list[i]
config._user_set_toolchain_dir = True
elif arg.startswith("--"):
die(f"Unknown option: {arg}")
else:
# First non-option argument: this and everything after is make_args.
make_args_start = i
break
i += 1
if not command:
return "help", config
# Store raw make_args (everything after --).
config.make_args = argv_list[make_args_start:]
# Extract known KEY=VALUE pairs into config for z.py's own decision-making.
# The raw args are still passed through to Make verbatim.
for arg in config.make_args:
if "=" in arg:
key, val = arg.split("=", 1)
if key in KNOWN_MAKE_VARS:
_parse_make_var(config, key, val)
return command, config
# ==================================================================================================
# Environment Validation
# ==================================================================================================
def validate_git_context() -> Path:
"""Validate git worktree and return the repo root path."""
try:
result = subprocess.run(
["git", "rev-parse", "--is-inside-work-tree"],
capture_output=True,
text=True,
check=True,
)
if result.stdout.strip() != "true":
die("Not inside a git work tree.")
except (subprocess.CalledProcessError, FileNotFoundError):
die(
"Not inside a git repository. Ensure git is installed and this is a valid repo."
)
try:
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
check=True,
)
git_root = Path(result.stdout.strip())
except subprocess.CalledProcessError:
die("Failed to determine repository root.")
cwd = Path.cwd()
try:
same_location = cwd.samefile(git_root)
except (OSError, NotImplementedError):
same_location = (
str(cwd.resolve()).casefold() == str(git_root.resolve()).casefold()
)
if not same_location:
die(f"Must run from repo root ({git_root.resolve()}), not {cwd.resolve()}.")
# Return the caller's cwd (not the canonicalized git path) so that
# substituted drives on Windows (e.g. `subst N: C:\path`) are preserved.
# Resolving would expand the alias and cause Make's CURDIR to become a
# long path, which can blow past cmd.exe's 8191-char command-line limit.
return cwd
def check_filesystem_support(directory: str) -> bool:
"""Check if directory filesystem supports xattr (Linux only). Returns True if OK."""
if not shutil.which("findmnt"):
print_warning("Cannot detect file system type (findmnt not available).")
return False
# Walk up to find the first existing parent.
parent = Path(directory)
while not parent.exists():
if parent == parent.parent:
break
parent = parent.parent
try:
result = subprocess.run(
["findmnt", "-n", "-o", "FSTYPE", "--target", str(parent)],
capture_output=True,
text=True,
)
if result.returncode != 0:
print_warning(
f"Cannot detect file system type for '{directory}' "
f"(findmnt exited with status {result.returncode})."
)
return False
fstype = result.stdout.strip()
if not fstype:
print_warning(
f"Cannot detect file system type for '{directory}' "
f"(no output from findmnt)."
)
return False
if fstype not in ("ext3", "ext4", "overlay"):
print_warning(
f"Unsupported file system '{fstype}' for toolchain "
f"directory '{directory}'.\n"
f" Only ext3/ext4/overlay support extended attributes "
f"(needed for setcap).\n"
f" Consider moving the toolchain to a supported partition."
)
return False
except Exception:
print_warning(f"Cannot detect file system type for '{directory}'.")
return False
return True
def validate_toolchain_dir_location(toolchain_dir: str, repo_root: Path) -> None:
"""Ensure toolchain directory is not inside the repository."""
tc = Path(toolchain_dir).resolve()
repo = repo_root.resolve()
if tc == repo or str(tc).startswith(str(repo) + os.sep):
die(
f"Toolchain directory must not be inside the repository.\n"
f" Toolchain: {tc}\n"
f" Repo root: {repo}\n"
f" Hint: use '--toolchain-dir' to specify a different location."
)
# ==================================================================================================
# Windows Pre-Build Steps
# ==================================================================================================
def restore_git_symlinks(repo_root: Path) -> None:
"""Restore git symlinks that appear as text stubs on Windows."""
try:
result = subprocess.run(
["git", "ls-files", "-s"],
capture_output=True,
text=True,
check=True,
cwd=str(repo_root),
)
except subprocess.CalledProcessError:
return
for line in result.stdout.splitlines():
# git ls-files -s format: "<mode> <hash> <stage>\t<path>".
if "\t" not in line:
continue
meta, rel_path = line.split("\t", 1)
meta_parts = meta.split()
if len(meta_parts) < 3 or meta_parts[0] != "120000":
continue
symlink_path = repo_root / rel_path
if not symlink_path.exists() or symlink_path.is_symlink():
continue
try:
content = symlink_path.read_text(encoding="utf-8").strip()
# Sanity check: real text stubs are short relative paths.
if not content or len(content) > 500:
continue
target_path = (symlink_path.parent / content).resolve()
if target_path.exists() and target_path.is_file():
shutil.copy2(str(target_path), str(symlink_path))
elif target_path.exists() and target_path.is_dir():
print_warning(f"Cannot restore directory symlink as copy: {rel_path}")
except Exception:
pass
# ==================================================================================================
# Make Invocation
# ==================================================================================================
def _prepend_path(directory: str) -> None:
"""Add directory to the start of PATH if not already present."""
entries = os.environ.get("PATH", "").split(os.pathsep)
if not any(e.casefold() == directory.casefold() for e in entries):
os.environ["PATH"] = directory + os.pathsep + os.environ.get("PATH", "")
def _append_path(directory: str) -> None:
"""Add directory to the end of PATH if not already present."""
entries = os.environ.get("PATH", "").split(os.pathsep)
if not any(e.casefold() == directory.casefold() for e in entries):
os.environ["PATH"] = os.environ.get("PATH", "") + os.pathsep + directory
def find_make(plat: PlatformInfo) -> str | None:
"""Find the GNU Make binary. Returns path or None."""
make = shutil.which("make")
if make:
return make
if plat.is_windows:
local_app_data = os.environ.get("LOCALAPPDATA", "")
if local_app_data:
winget_dir = Path(local_app_data) / "Microsoft" / "WinGet" / "Packages"
if winget_dir.exists():
for make_dir in winget_dir.glob("*make*"):
for candidate in make_dir.rglob("make.exe"):
_prepend_path(str(candidate.parent))
return str(candidate)
return None
def _require_make(plat: PlatformInfo) -> str:
"""Find Make or die."""
make = find_make(plat)
if make:
return make
if plat.is_windows:
hint = "Run 'z.ps1 setup' to install it."
else:
hint = "Run './z setup' to install it."
die(f"GNU Make not found on PATH. {hint}")
def setup_windows_make_env(plat: PlatformInfo) -> None:
"""Set up the environment for running Make on Windows."""
# HOME must use forward slashes for Make recipes that reference
# $(HOME)/.cargo/bin/cargo. Git may set HOME with backslashes, and sh.exe
# interprets those as escape sequences (e.g., C:\Users → C:Users).
home = os.environ.get("HOME", os.environ.get("USERPROFILE", ""))
os.environ["HOME"] = home.replace("\\", "/")
# Add Git-for-Windows usr/bin to PATH (provides sh.exe and coreutils for Make recipes).
git_exe = shutil.which("git")
if git_exe:
git_root = Path(git_exe).resolve().parent.parent
git_usr_bin = git_root / "usr" / "bin"
if git_usr_bin.exists():
_append_path(str(git_usr_bin))
# Add Python scripts dir to PATH (for codespell etc.).
# In a venv, sys.executable is already in the Scripts/ directory alongside
# codespell.exe, so we add the executable's parent directly. For a system
# Python install, scripts live in a Scripts/ subdirectory.
exe_dir = Path(sys.executable).parent
_append_path(str(exe_dir))
scripts_subdir = exe_dir / "Scripts"
if scripts_subdir.is_dir():
_append_path(str(scripts_subdir))
# When invoked via git hooks the venv may not be activated, so also check
# the repo-local .venv/Scripts directory where codespell etc. are installed.
repo_venv_scripts = plat.repo_root / ".venv" / "Scripts"
if repo_venv_scripts.is_dir():
_append_path(str(repo_venv_scripts))
def invoke_make(
plat: PlatformInfo,
*,
injected_vars: list[str] | None = None,
raw_args: list[str] | None = None,
targets: list[str] | None = None,
verbose: bool = False,
) -> int:
"""Invoke GNU Make.
Args:
plat: Platform information.
injected_vars: VAR=VALUE strings z.py injects (e.g., RELEASE).
raw_args: Raw user arguments from after -- (targets and KEY=VALUE pairs).
targets: Explicit Make targets to append.
verbose: Print the full command line.
Returns:
Make exit code.
"""
make_bin = _require_make(plat)
if plat.is_windows:
setup_windows_make_env(plat)
cmd: list[str] = [make_bin]
if injected_vars:
cmd.extend(injected_vars)
if raw_args:
cmd.extend(raw_args)
if targets:
cmd.extend(targets)
if verbose:
print_info(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, cwd=str(plat.repo_root))
return result.returncode
# ==================================================================================================
# Build Argument Assembly
# ==================================================================================================
def _assemble_build_make_args(
plat: PlatformInfo,
config: BuildConfig,
) -> tuple[list[str], list[str]]:
"""Assemble injected Make variables and filtered user args.
z.py injects only the variables it needs to add or override. All other user-supplied
KEY=VALUE pairs and targets are passed through verbatim.
Returns (injected_vars, filtered_user_args).
"""
injected: list[str] = []
user_args = list(config.make_args)
# --profile: force RELEASE=yes, add PROFILER=yes, strip user-provided RELEASE=.
if config.profile:
user_args = [a for a in user_args if not a.startswith("RELEASE=")]
injected.append("RELEASE=yes")
injected.append("PROFILER=yes")
elif config.release:
if not any(a.startswith("RELEASE=") for a in user_args):
injected.append("RELEASE=yes")
# Windows platform defaults.
if plat.is_windows:
if not any(a.startswith("DEPLOYMENT_MODE=") for a in user_args):
injected.append("DEPLOYMENT_MODE=standalone")
if config.machine == "microvm" and not any(
a.startswith("WHP=") for a in user_args
):
injected.append("WHP=yes")
return injected, user_args
# ==================================================================================================
# Subcommand: build
# ==================================================================================================
def cmd_build(plat: PlatformInfo, config: BuildConfig) -> int:
"""Execute the build subcommand."""
# Windows pre-build steps.
if plat.is_windows:
restore_git_symlinks(plat.repo_root)
injected, user_args = _assemble_build_make_args(plat, config)
print_info(f"Build parameters: {' '.join(injected + user_args)}")
rc = invoke_make(
plat, injected_vars=injected, raw_args=user_args, verbose=config.verbose
)
if rc == 0:
print_success("Build complete.")
else:
print_error("Build failed.")
return rc
# ==================================================================================================
# Subcommand: clean / distclean
# ==================================================================================================
def cmd_clean(plat: PlatformInfo, config: BuildConfig) -> int:
"""Execute the clean subcommand."""
print_info("Running quick cleanup...")
rc = invoke_make(plat, targets=["clean"])
if rc == 0:
print_success("Quick clean complete.")
else:
print_error("Quick clean failed.")
return rc
def cmd_distclean(plat: PlatformInfo, config: BuildConfig) -> int:
"""Execute the distclean subcommand."""
print_info("Running full cleanup...")
rc = invoke_make(plat, targets=["distclean"])
# Windows-specific extra cleanup.
if plat.is_windows:
venv_dir = plat.repo_root / ".venv"
if venv_dir.exists():
try:
shutil.rmtree(str(venv_dir))
except Exception:
subprocess.run(
["cmd", "/c", "rmdir", "/s", "/q", str(venv_dir)],
capture_output=True,
check=False,
)
print_info("Removed .venv/")
if rc == 0:
print_success("Full cleanup complete.")
else:
print_error("Full cleanup failed.")
return rc
# ==================================================================================================
# Subcommand: test
# ==================================================================================================
def cmd_test(plat: PlatformInfo, config: BuildConfig) -> int:
"""Execute the test subcommand."""
if plat.is_windows:
restore_git_symlinks(plat.repo_root)
injected, user_args = _assemble_build_make_args(plat, config)
rc = invoke_make(
plat,
injected_vars=injected,
raw_args=user_args,
targets=["test"],
verbose=config.verbose,
)
if rc == 0:
print_success("Tests passed.")
else:
print_error("Tests failed.")
return rc
# ==================================================================================================
# Subcommand: verify
# ==================================================================================================
def cmd_verify(plat: PlatformInfo, config: BuildConfig) -> int:
"""Execute the verify subcommand (Verus formal verification)."""
if plat.is_windows:
restore_git_symlinks(plat.repo_root)
injected, user_args = _assemble_build_make_args(plat, config)
# If the user did not supply explicit Make goals after `--`, default to the
# top-level `verify` target. Otherwise, rely solely on the user-specified
# goals and do not prepend `verify`. Variable assignments (KEY=VALUE) are
# not Make goals, so they must not suppress the default target.
has_goals = any("=" not in a for a in user_args)
targets: list[str] = ["verify"] if not has_goals else []
rc = invoke_make(
plat,
injected_vars=injected,
raw_args=user_args,
targets=targets,
verbose=config.verbose,
)
if rc == 0:
print_success("Verification complete.")
else:
print_error("Verification failed.")
return rc
# ==================================================================================================
# Subcommand: run
# ==================================================================================================
def cmd_run(plat: PlatformInfo, config: BuildConfig) -> int:
"""Execute the run subcommand."""
# Parse -program from make_args.
program = DEFAULT_RUN_PROGRAM
remaining_args: list[str] = []
i = 0
while i < len(config.make_args):
if config.make_args[i] == "-program" and i + 1 < len(config.make_args):
program = config.make_args[i + 1]
i += 2
else:
remaining_args.append(config.make_args[i])
i += 1
if plat.is_windows:
# Run nanvixd.exe directly in standalone mode.
nanvixd = plat.repo_root / "bin" / "nanvixd.exe"
if not nanvixd.exists():
die("nanvixd.exe not found in bin/. Run 'z.ps1 build -- all' first.")
cmd = [str(nanvixd), "--", program]
print_info(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, cwd=str(plat.repo_root))
return result.returncode
else:
# Linux: delegate to make run. Use remaining_args (with -program
# stripped) instead of config.make_args to avoid duplicating args.
injected, _ = _assemble_build_make_args(plat, config)
return invoke_make(
plat,
injected_vars=injected,
raw_args=remaining_args,
targets=["run"],
verbose=config.verbose,
)
# ==================================================================================================
# Subcommand: bench
# ==================================================================================================
def cmd_bench(plat: PlatformInfo, config: BuildConfig) -> int:
"""Execute the bench subcommand."""
ext = ".exe" if plat.is_windows else ".elf"
bench_bin = plat.repo_root / "bin" / f"nanvix-bench{ext}"
if not bench_bin.exists():
hint = (
"z.ps1 build -- nanvix-bench"
if plat.is_windows
else "./z build -- all-nanvix-bench"
)
die(f"nanvix-bench{ext} not found in bin/. Build it first:\n {hint}")
cmd = [str(bench_bin)] + config.make_args
print_info(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, cwd=str(plat.repo_root))
return result.returncode
# ==================================================================================================
# Subcommand: help
# ==================================================================================================
HELP_TEXT = """\
Utility for building Nanvix.
Usage:
z <command> [options] [-- [targets] [PARAM=VALUE ...]]
Commands:
build Build Nanvix components.
test Run tests.
verify Run Verus formal verification on annotated crates.
clean Remove build artifacts (quick clean).
distclean Remove everything (full clean).
setup Install development prerequisites.
run Run nanvixd.
bench Run benchmarks.
help Show this help message.
Options:
--profile Enable profiling (implies --release, passes PROFILER=yes).
--release Build in release mode.
--nanvix-sdk Build the Nanvix cross-compilation toolchain (setup only, Linux).
--l2-deployment Build Cloud Hypervisor for L2 deployment (setup only, Linux).
--toolchain-dir DIR Toolchain directory (setup only, Linux, default: ~/toolchain).
Build Parameters (after --):
MACHINE=microvm Target machine (default: microvm).
RELEASE=yes|no Release mode.
DEPLOYMENT_MODE=MODE standalone|single-process|multi-process|l2.
LOG_LEVEL=LEVEL trace|debug|info|warn|error|panic.
PROFILER=yes|no Enable profiling.
TIMEOUT=SECONDS Execution timeout (default: 600).
WHP=yes|no Windows Hypervisor Platform.
HOST_CPU=CPU Target CPU for host builds.
MEMORY_SIZE=MB Memory size in megabytes (default: 128).
TIMESTAMP_MSG=yes|no Enable message timestamping.
Run Options (after --):
-program <path> Path to guest binary (default: bin/hello-rust-nostd.elf).