-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathvmware_module_builder.py
More file actions
executable file
·2155 lines (1834 loc) · 94.1 KB
/
Copy pathvmware_module_builder.py
File metadata and controls
executable file
·2155 lines (1834 loc) · 94.1 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
"""
VMware Module Builder
Rebuilds vmmon, vmnet and fixes vmci for the current running kernel.
Applies kernel compatibility patches from the local Hyphaed repo.
Resolves "/dev/vmci: No such file or directory" and objtool build errors.
"""
import subprocess
import sys
import os
import re
import hashlib
import tarfile
import tempfile
import shutil
import xml.etree.ElementTree as ET
from pathlib import Path
# ─────────────────────────────────────────────────────────────────────────────
# Local patch repo — all patches sourced from here, no internet needed
# ─────────────────────────────────────────────────────────────────────────────
SCRIPT_DIR = Path(__file__).resolve().parent
PATCHES_DIR = SCRIPT_DIR / "patches"
UPSTREAM_616_DIR = PATCHES_DIR / "upstream/6.16.x"
VMWARE_MOD_DIR = Path("/usr/lib/vmware/modules/source")
BACKUP_DIR_PREFIX = VMWARE_MOD_DIR / "backup"
# VMware Workstation 25 does not ship vmci source; the kernel provides it
# as 'vmw_vmci' (in-kernel driver, already signed by the kernel build key).
VMCI_MODULE = "vmw_vmci"
# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────
def banner(text: str):
width = 62
print("╔" + "═" * width + "╗")
for line in text.strip().splitlines():
print("║" + line.center(width) + "║")
print("╚" + "═" * width + "╝")
def section(title: str):
print(f"\n{'─'*62}")
print(f" {title}")
print(f"{'─'*62}")
def ok(msg: str): print(f" ✅ {msg}")
def info(msg: str): print(f" ℹ️ {msg}")
def warn(msg: str): print(f" ⚠️ {msg}", file=sys.stderr)
def err(msg: str): print(f" ❌ {msg}", file=sys.stderr)
def run(cmd: list, check=False, capture=True, cwd=None, timeout=None) -> subprocess.CompletedProcess:
"""Run a command, always printing it. Returns CompletedProcess."""
print(f" $ {' '.join(str(c) for c in cmd)}")
try:
result = subprocess.run(
cmd,
capture_output=capture,
text=True,
check=False,
cwd=cwd,
timeout=timeout,
)
except subprocess.TimeoutExpired:
warn(f"Command timed out after {timeout}s: {' '.join(str(c) for c in cmd)}")
return subprocess.CompletedProcess(cmd, returncode=1, stdout="", stderr="timeout")
if capture and result.stdout:
for line in result.stdout.splitlines():
print(f" {line}")
if capture and result.stderr:
for line in result.stderr.splitlines():
print(f" {line}", file=sys.stderr)
if check and result.returncode != 0:
raise subprocess.CalledProcessError(result.returncode, cmd,
result.stdout, result.stderr)
return result
# ─────────────────────────────────────────────────────────────────────────────
# Phase 2a — Robust kernel version parsing
# ─────────────────────────────────────────────────────────────────────────────
class KernelVersion:
"""Parse kernel version strings robustly, handling distro suffixes.
Handles: 7.0.0-7-generic, 6.17.11+deb14-amd64, 6.16.8+kali-amd64,
6.6.35-1-MANJARO, 6.11.0-1014-aws, 6.12.6_1 (Void), etc.
"""
def __init__(self, raw: str):
self.raw = raw
m = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', raw)
if not m:
raise ValueError(f"Cannot parse kernel version: {raw!r}")
self.major = int(m.group(1))
self.minor = int(m.group(2))
self.patch = int(m.group(3) or 0)
def at_least(self, major: int, minor: int) -> bool:
return (self.major, self.minor) >= (major, minor)
def needs_base_616_patches(self) -> bool:
return self.at_least(6, 16)
def needs_objtool_patches(self) -> bool:
return self.major >= 7 or (self.major == 6 and self.minor >= 17)
def is_supported(self) -> bool:
return self.at_least(6, 16)
def __str__(self) -> str:
return self.raw
def get_kernel_version() -> KernelVersion:
result = subprocess.run(["uname", "-r"], capture_output=True, text=True, check=True)
return KernelVersion(result.stdout.strip())
# ─────────────────────────────────────────────────────────────────────────────
# Phase 2b — Distro detection
# ─────────────────────────────────────────────────────────────────────────────
class Distro:
"""
Detect the Linux distribution from /etc/os-release and available package
managers. Provides the correct kernel-headers package name and install
command for the running kernel.
"""
# Maps ID / ID_LIKE values to a canonical family name
_FAMILY_MAP = {
"ubuntu": "debian", "debian": "debian", "linuxmint": "debian",
"pop": "debian", "elementary": "debian", "kali": "debian",
"raspbian": "debian", "parrot": "debian", "mx": "debian",
"fedora": "fedora", "rhel": "fedora", "centos": "fedora",
"almalinux": "fedora", "rocky": "fedora", "ol": "fedora",
"amzn": "fedora",
"opensuse": "suse", "suse": "suse", "opensuse-leap": "suse",
"opensuse-tumbleweed": "suse",
"arch": "arch", "manjaro": "arch", "endeavouros": "arch",
"garuda": "arch", "artix": "arch",
"gentoo": "gentoo",
"alpine": "alpine",
"void": "void",
"nixos": "nixos",
"slackware": "slackware",
}
def __init__(self):
self.id = ""
self.id_like = []
self.name = ""
self.version_id = ""
self.family = "unknown"
osrel = Path("/etc/os-release")
if osrel.exists():
for line in osrel.read_text().splitlines():
if "=" not in line:
continue
key, _, val = line.partition("=")
val = val.strip().strip('"')
if key == "ID":
self.id = val.lower()
elif key == "ID_LIKE":
self.id_like = [x.lower() for x in val.split()]
elif key == "NAME":
self.name = val
elif key == "VERSION_ID":
self.version_id = val
# Resolve family: check ID first, then ID_LIKE
for candidate in [self.id] + self.id_like:
if candidate in self._FAMILY_MAP:
self.family = self._FAMILY_MAP[candidate]
break
# Detect available package managers (ground truth over family heuristic)
self._pm = self._detect_pm()
def _detect_pm(self) -> str:
for pm in ("apt-get", "dnf", "yum", "pacman", "zypper", "emerge", "apk", "xbps-install", "nix-env"):
if shutil.which(pm):
return pm
return ""
@property
def pm(self) -> str:
return self._pm
def headers_pkg(self, kver: KernelVersion) -> list[str]:
"""Return the package name(s) that provide kernel headers for kver."""
k = kver.raw
pm = self._pm
if pm == "apt-get":
return [f"linux-headers-{k}"]
if pm in ("dnf", "yum"):
# Fedora/RHEL: kernel-devel matches the running kernel automatically
return ["kernel-devel", f"kernel-devel-{k}"]
if pm == "pacman":
# Arch: derive from kernel flavour (linux, linux-lts, linux-zen, etc.)
flavour = self._arch_kernel_flavour(k)
return [f"{flavour}-headers"]
if pm == "zypper":
return [f"kernel-default-devel={k}", "kernel-default-devel"]
if pm == "emerge":
return [f"sys-kernel/linux-headers"]
if pm == "apk":
return ["linux-headers"]
if pm == "xbps-install":
return [f"kernel-headers-{k}"]
# Fallback
return [f"linux-headers-{k}"]
def _arch_kernel_flavour(self, raw: str) -> str:
"""Guess the Arch package name from the uname -r suffix."""
# e.g. 6.6.35-1-MANJARO → linux-manjaro; 6.6.35-arch1-1 → linux
m = re.search(r'-(\w+)$', raw)
suffix = m.group(1).lower() if m else ""
if "lts" in suffix:
return "linux-lts"
if "zen" in suffix:
return "linux-zen"
if "hardened" in suffix:
return "linux-hardened"
if "rt" in suffix:
return "linux-rt"
if "manjaro" in suffix:
return "linux-manjaro" if shutil.which("mhwd") else "linux"
return "linux"
def install_cmd(self, packages: list[str]) -> list[str]:
"""Return the full install command for given packages."""
pm = self._pm
if pm == "apt-get":
return ["apt-get", "install", "-y"] + packages
if pm == "dnf":
return ["dnf", "install", "-y"] + packages
if pm == "yum":
return ["yum", "install", "-y"] + packages
if pm == "pacman":
return ["pacman", "-S", "--noconfirm"] + packages
if pm == "zypper":
return ["zypper", "--non-interactive", "install"] + packages
if pm == "emerge":
return ["emerge", "--ask=n"] + packages
if pm == "apk":
return ["apk", "add"] + packages
if pm == "xbps-install":
return ["xbps-install", "-y"] + packages
return []
def summary(self) -> str:
pm_str = self._pm or "unknown"
return f"{self.name or self.id} (family={self.family}, pm={pm_str})"
def detect_distro() -> Distro:
return Distro()
# ─────────────────────────────────────────────────────────────────────────────
# Phase 7 — Secure Boot detection
# ─────────────────────────────────────────────────────────────────────────────
def detect_secure_boot() -> bool:
"""Return True if Secure Boot is currently enabled."""
# Try mokutil first
result = subprocess.run(["mokutil", "--sb-state"], capture_output=True, text=True)
if result.returncode == 0:
return "enabled" in result.stdout.lower()
# Fallback: read EFI variable directly
sb_var = Path("/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c")
if sb_var.exists():
try:
data = sb_var.read_bytes()
# Last byte: 1 = enabled, 0 = disabled (first 4 bytes are attributes)
return len(data) >= 5 and data[4] == 1
except Exception:
pass
return False
def print_secure_boot_signing_instructions(kernel_version: str):
warn("Secure Boot is ENABLED.")
warn("Unsigned modules will be rejected by the kernel ('Key was rejected by service').")
print()
info("To sign the modules, run the following commands with your MOK key:")
print()
mok_dir = "/var/lib/shim-signed/mok"
sign_tool = f"/usr/src/linux-headers-{kernel_version}/scripts/sign-file"
for mod in ["vmmon", "vmnet"]:
ko = f"/lib/modules/{kernel_version}/misc/{mod}.ko"
print(f" sudo {sign_tool} sha256 \\")
print(f" {mok_dir}/MOK.priv {mok_dir}/MOK.der \\")
print(f" {ko}")
print()
info(f"Note: '{VMCI_MODULE}' is the in-kernel driver, signed by the kernel build key.")
info(f" It does NOT need MOK signing and will load automatically.")
print()
info("If your MOK key has a passphrase, prefix with:")
print(" sudo KBUILD_SIGN_PIN='your_passphrase' ...")
print()
info("If you haven't created a MOK key yet:")
print(" sudo mokutil --import /path/to/MOK.der")
print()
# ─────────────────────────────────────────────────────────────────────────────
# Phase 5 — Smart backup system
# ─────────────────────────────────────────────────────────────────────────────
def md5_files(*paths: Path) -> str:
h = hashlib.md5()
for p in sorted(paths):
if p.exists():
h.update(p.read_bytes())
return h.hexdigest()
def get_or_create_backup() -> Path:
"""
Find the original (oldest) backup of vmmon.tar + vmnet.tar.
If none exists, create one. Returns the backup directory path.
Always extracts from the clean backup, never from potentially-patched live files.
"""
tars = ["vmmon.tar", "vmnet.tar"]
current_hash = md5_files(*[VMWARE_MOD_DIR / t for t in tars])
# Find existing backups, oldest first
existing = sorted(VMWARE_MOD_DIR.glob("backup-*"))
for backup in existing:
backup_hash = md5_files(*[backup / t for t in tars])
if backup_hash == current_hash:
ok(f"Using existing original backup: {backup.name} (hash verified)")
return backup
# If the oldest backup has a different hash, warn but still use it as base
if existing:
oldest = existing[0]
warn(f"Existing backup {oldest.name} has different hash than current modules.")
warn("Current modules may have been previously patched.")
info("Using oldest backup as clean source.")
return oldest
# No backup exists — create one now
import datetime
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
backup_path = VMWARE_MOD_DIR / f"backup-{stamp}"
info(f"Creating first backup at: {backup_path}")
run(["sudo", "mkdir", "-p", str(backup_path)], check=True)
for t in tars:
run(["sudo", "cp", str(VMWARE_MOD_DIR / t), str(backup_path / t)], check=True)
ok(f"Backup created: {backup_path.name}")
return backup_path
# ─────────────────────────────────────────────────────────────────────────────
# Phase 3 — Dynamic autopatch system
#
# Philosophy: every patch function probes the actual file content at runtime.
# It applies the fix only when the problem signature is present AND the fix is
# not already there. This makes the system kernel-version agnostic, VMware-
# source-version agnostic, and fully idempotent (safe to re-run).
#
# Probe helpers return True if applied, False if skipped (already fixed or
# condition does not apply). They never raise on a missing target — they warn
# and continue so a single incompatibility never blocks the whole build.
# ─────────────────────────────────────────────────────────────────────────────
def _read(path: Path) -> str:
return path.read_text(encoding="utf-8", errors="replace")
def _write(path: Path, content: str):
path.write_text(content, encoding="utf-8")
def _kernel_header_has(symbol: str, kver: KernelVersion) -> bool:
"""Return True if `symbol` appears in the running kernel's include tree."""
build = Path(f"/lib/modules/{kver.raw}/build/include")
if not build.exists():
return False
result = subprocess.run(
["grep", "-r", "--include=*.h", "-l", "-m1", symbol, str(build)],
capture_output=True, text=True,
)
return result.returncode == 0
def _patch_insert_after(path: Path, anchor: str, insertion: str, label: str) -> bool:
"""
Insert `insertion` immediately after the first occurrence of `anchor`.
Uses the first non-blank, non-comment line of `insertion` as an
idempotency marker — skips silently if already present.
"""
text = _read(path)
marker = next(
(ln for ln in insertion.splitlines()
if ln.strip() and not ln.strip().startswith(("#", "/*", " *", "//"))),
insertion[:60],
)
if marker in text:
info(f" {label} — already present, skipped")
return False
if anchor not in text:
warn(f" {label} — anchor not found in {path.name}, skipping")
return False
_write(path, text.replace(anchor, anchor + insertion, 1))
ok(f" {label}")
return True
def _patch_replace(path: Path, old: str, new: str, label: str) -> bool:
"""Replace `old` with `new`; skip if `old` absent (already fixed or n/a)."""
text = _read(path)
if old not in text:
if new.strip() in text:
info(f" {label} — already applied, skipped")
else:
info(f" {label} — target not present in {path.name}, skipping")
return False
_write(path, text.replace(old, new, 1))
ok(f" {label}")
return True
def _patch_replace_all(path: Path, old: str, new: str, label: str) -> bool:
"""Replace all occurrences of `old` with `new`."""
text = _read(path)
if old not in text:
info(f" {label} — not present in {path.name}, skipping")
return False
count = text.count(old)
_write(path, text.replace(old, new))
ok(f" {label} ({count} occurrence(s))")
return True
# ── Upstream source overlay ───────────────────────────────────────────────────
def copy_upstream_source(module: str, dest_dir: Path):
"""Copy the pre-patched 6.16.x upstream source tree over the extracted tarball."""
src = UPSTREAM_616_DIR / f"{module}-only"
dst = dest_dir / f"{module}-only"
if not src.exists():
raise FileNotFoundError(f"Upstream patch source not found: {src}")
info(f" Overlaying 6.16.x patched source onto {module}-only/")
shutil.copytree(str(src), str(dst), dirs_exist_ok=True)
ok(f" {module}: base 6.16.x source applied (ccflags-y, timer/MSR API, module_init)")
# ═══════════════════════════════════════════════════════════════════════════════
# AUTOPATCH CATALOGUE
#
# Each entry documents:
# Problem — what breaks and on which kernel/VMware version
# Probe — how the script detects whether the fix is needed
# Fix — what text transformation is applied
# ═══════════════════════════════════════════════════════════════════════════════
# ── [AP-01] objtool: OBJECT_FILES_NON_STANDARD (kernel >= 6.17 / 7.x) ────────
#
# Problem: objtool validates stack frames in all compiled .o files.
# vmmon's phystrack.c and task.c use VMware custom asm constructs
# that confuse objtool, causing build failures on 6.17+.
# Probe: Check for the marker in Makefile.kernel.
# Fix: Add OBJECT_FILES_NON_STANDARD_* directives after the obj-y list.
def _find_obj_y_anchor(text: str, module: str) -> str | None:
"""
Find the line that ends the $(DRIVER)-y object list, after which we can
safely insert OBJECT_FILES_NON_STANDARD directives.
Handles all known VMware Makefile.kernel variants.
"""
if module == "vmmon":
patterns = [
"$(SRCROOT)/linux/*.c $(SRCROOT)/common/*.c \\\n\t\t$(SRCROOT)/bootstrap/*.c)))",
"$(wildcard $(SRCROOT)/linux/*.c $(SRCROOT)/common/*.c",
"$(wildcard $(SRCROOT)/*.c)",
]
else:
patterns = [
"$(wildcard $(SRCROOT)/*.c)",
]
# vmnet flat list: find last continuation of $(DRIVER)-y
if "driver.o hub.o userif.o" in text:
idx = text.index("driver.o hub.o userif.o")
end = text.find("\n", idx)
# Walk past line continuations
while text[end - 1:end] == "\\" and end < len(text):
end = text.find("\n", end + 1)
return text[idx:end]
return next((p for p in patterns if p in text), None)
def _autopatch_objtool_vmmon(vmmon_dir: Path):
mk = vmmon_dir / "Makefile.kernel"
if not mk.exists():
warn(f" vmmon Makefile.kernel not found: {mk}")
return
text = _read(mk)
anchor = _find_obj_y_anchor(text, "vmmon")
if not anchor or anchor not in text:
warn(" vmmon Makefile.kernel: cannot locate obj-y anchor for objtool markers")
return
_patch_insert_after(mk, anchor,
"\n\n# Disable objtool for files using non-standard asm (kernel 6.17+)\n"
"OBJECT_FILES_NON_STANDARD_common/phystrack.o := y\n"
"OBJECT_FILES_NON_STANDARD_common/task.o := y\n"
"OBJECT_FILES_NON_STANDARD := y",
"vmmon Makefile: OBJECT_FILES_NON_STANDARD (objtool bypass)")
def _autopatch_objtool_vmnet(vmnet_dir: Path):
mk = vmnet_dir / "Makefile.kernel"
if not mk.exists():
warn(f" vmnet Makefile.kernel not found: {mk}")
return
text = _read(mk)
anchor = _find_obj_y_anchor(text, "vmnet")
if not anchor or anchor not in text:
warn(" vmnet Makefile.kernel: cannot locate anchor for objtool markers")
return
_patch_insert_after(mk, anchor,
"\n\n# Disable objtool for files using non-standard asm (kernel 6.17+)\n"
"OBJECT_FILES_NON_STANDARD_userif.o := y\n"
"OBJECT_FILES_NON_STANDARD := y",
"vmnet Makefile: OBJECT_FILES_NON_STANDARD (objtool bypass)")
# ── [AP-02] objtool: bare return; at end of void functions (kernel >= 6.17) ──
#
# Problem: objtool in kernel 6.17+ rejects void functions that end with an
# explicit bare `return;` (treated as dead code after a RET insn).
# Probe: Regex-scan phystrack.c for `<ws>return;\n<ws>}` pattern.
# Fix: Remove the redundant `return;` line.
def _autopatch_phystrack_bare_returns(vmmon_dir: Path):
src = vmmon_dir / "common" / "phystrack.c"
if not src.exists():
info(" phystrack.c not found — skipping bare-return removal")
return
text = _read(src)
pattern = re.compile(r'[ \t]+return;\n([ \t]*\})')
matches = list(pattern.finditer(text))
if not matches:
info(" phystrack.c: no bare return; statements — skipped")
return
for m in reversed(matches):
text = text[:m.start()] + m.group(1) + text[m.end():]
_write(src, text)
ok(f" phystrack.c: removed {len(matches)} bare return; statement(s)")
# ── [AP-03] netif_napi_add 4-arg → 3-arg (kernel >= 6.1) ────────────────────
#
# Problem: Linux 6.1 removed the `weight` parameter from netif_napi_add(),
# making it a 3-argument function. VMware's compat_netdevice.h
# still wraps it with 4 arguments via compat_netif_napi_add().
# On kernel 6.1+ this causes a compile error.
# Probe: Check whether netif_napi_add in the kernel headers takes 3 args
# (absence of a 4th `weight` parameter in the declaration).
# Fix: Add a LINUX_VERSION_CODE >= 6.1 guard that redefines
# compat_netif_napi_add to drop the weight argument.
def _autopatch_napi_add_compat(vmnet_dir: Path, kver: KernelVersion):
"""
Fix netif_napi_add 4-arg → 3-arg for kernel >= 6.1.
Three variants of compat_netdevice.h exist in the wild:
A) Modern VMware 25.x: flat `#define compat_netif_napi_add(...) netif_napi_add(..., quota)`
with no version guard at all.
B) Older VMware / 6.16.x overlay: versioned guards using LINUX_VERSION_CODE.
C) Already fixed: has "kernel 6.1+" comment or KERNEL_VERSION(6, 1, 0) guard.
"""
compat = vmnet_dir / "compat_netdevice.h"
if not compat.exists():
return
if not kver.at_least(6, 1):
info(" compat_netdevice.h: kernel < 6.1, napi_add compat not needed")
return
text = _read(compat)
# Already fixed?
if "KERNEL_VERSION(6, 1" in text or "[autopatch]" in text:
info(" compat_netdevice.h: napi_add already fixed — skipped")
return
# Is the 4-arg form present at all?
needs_fix = (
"netif_napi_add(dev, napi, poll, quota)" in text or
"netif_napi_add(dev, napi, poll, weight)" in text or
# also catch the simpler flat define in real VMware 25.x source
(re.search(r'define\s+compat_netif_napi_add\s*\(', text) and
"netif_napi_add_weight" not in text)
)
if not needs_fix:
info(" compat_netdevice.h: no 4-arg napi_add form found — skipped")
return
override = (
"\n/* [autopatch] kernel 6.1+ dropped the weight param from netif_napi_add */\n"
"#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 1, 0)\n"
"# ifdef compat_netif_napi_add\n"
"# undef compat_netif_napi_add\n"
"# endif\n"
"# define compat_netif_napi_add(dev, napi, poll, quota) \\\n"
" netif_napi_add((dev), (napi), (poll))\n"
"#endif\n"
)
# Append before the closing include guard (variant B) or at end of file (variant A)
closing = next(
(g for g in ("#endif /* __COMPAT_NETDEVICE_H__ */",
"#endif /* _COMPAT_NETDEVICE_H_ */",
"#endif\n")
if g in text),
None,
)
if closing:
_patch_replace(compat, closing, override + closing,
"compat_netdevice.h: netif_napi_add 3-arg fix (kernel 6.1+)")
else:
# No closing guard — just append
if "autopatch" not in text:
_write(compat, text + override)
ok(" compat_netdevice.h: netif_napi_add 3-arg fix appended (kernel 6.1+)")
# ── [AP-04] vm_check_build missing from Makefile.kernel (all versions) ───────
#
# Problem: vmnet's Makefile.kernel uses `$(call vm_check_build, ...)` to
# detect kernel API availability at compile time. However,
# vm_check_build is only defined in Makefile.normal (used for
# direct make invocations) and is NOT available in Makefile.kernel
# (used by the kernel build system via kbuild).
# When kbuild calls Makefile.kernel, the $(call vm_check_build,…)
# expands to an empty string, silently disabling the detection.
# Probe: Check if vm_check_build is defined in Makefile.kernel.
# Fix: Inject the vm_check_build definition into Makefile.kernel.
def _autopatch_vmcheck_build(vmnet_dir: Path):
"""
Inject the vm_check_build macro into vmnet/Makefile.kernel.
The macro is defined in Makefile.normal but not in Makefile.kernel;
without it, $(call vm_check_build, ...) silently expands to nothing.
Handles both CC_OPTS and EXTRA_CFLAGS Makefile styles.
"""
mk = vmnet_dir / "Makefile.kernel"
if not mk.exists():
return
text = _read(mk)
if "vm_check_build" not in text:
info(" vmnet Makefile.kernel: vm_check_build not referenced — skipped")
return
if "vm_check_build =" in text or "vm_check_build :=" in text:
info(" vmnet Makefile.kernel: vm_check_build already defined — skipped")
return
# Pick the cflags variable that's actually used
cflags_var = "$(ccflags-y)" if "ccflags-y" in text else "$(EXTRA_CFLAGS)"
definition = (
"\n# vm_check_build: compile-test a C snippet; yields flag2 on success, flag3 on error\n"
f"vm_check_build = $(shell if $(CC) {cflags_var} -Werror -S -o /dev/null -xc $(1) \\\n"
" > /dev/null 2>&1; then echo \"$(2)\"; else echo \"$(3)\"; fi)\n"
)
anchor = next(
(a for a in ("INCLUDE := -I$(SRCROOT)", "ccflags-y +=", "EXTRA_CFLAGS :=")
if a in text),
None,
)
if not anchor:
warn(" vmnet Makefile.kernel: cannot locate anchor for vm_check_build")
return
_patch_insert_after(mk, anchor, definition,
"vmnet Makefile.kernel: inject vm_check_build")
# ── [AP-05] vmnet Makefile.kernel: add vm_check_build NAPI single-param flag ─
#
# Problem: compat_netdevice.h uses VMW_NETIF_SINGLE_NAPI_PARM to select the
# 3-arg netif_napi_add at build time. This flag is set via
# vm_check_build in Makefile.normal, but Makefile.kernel does not
# set it, even when vm_check_build is defined.
# Probe: Check if VMW_NETIF_SINGLE_NAPI_PARM is already set in Makefile.kernel.
# Fix: Add the vm_check_build call for a synthetic probe file.
def _autopatch_vmnet_napi_flag(vmnet_dir: Path, kver: KernelVersion):
mk = vmnet_dir / "Makefile.kernel"
if not mk.exists():
return
# Only relevant on kernel >= 6.1
if (kver.major, kver.minor) < (6, 1):
return
text = _read(mk)
if "VMW_NETIF_SINGLE_NAPI_PARM" in text:
info(" vmnet Makefile.kernel: VMW_NETIF_SINGLE_NAPI_PARM already set — skipped")
return
# Anchor: after the last ccflags-y line.
# 6.16.x overlay uses 'ccflags-y :='; 25H2u1 uses 'ccflags-y +=' — handle both.
if "ccflags-y :=" in text or "ccflags-y +=" in text:
idx = text.rindex("ccflags-y")
end = text.find("\n", idx)
anchor = text[idx:end]
else:
warn(" vmnet Makefile.kernel: cannot locate ccflags-y anchor for NAPI flag")
return
insertion = (
"\n# Detect 3-arg netif_napi_add (kernel 6.1+ dropped the weight param)\n"
"ccflags-y += $(call vm_check_build, $(SRCROOT)/netif_napi_add_check.c,"
"-DVMW_NETIF_SINGLE_NAPI_PARM, )\n"
)
# Also create the probe file that vm_check_build will try to compile
probe_src = vmnet_dir / "netif_napi_add_check.c"
if not probe_src.exists():
probe_content = (
"/* autopatch probe: detect 3-arg netif_napi_add (kernel 6.1+) */\n"
"#include <linux/netdevice.h>\n"
"static int dummy_poll(struct napi_struct *n, int b) { return 0; }\n"
"void test(struct net_device *dev, struct napi_struct *napi) {\n"
" netif_napi_add(dev, napi, dummy_poll);\n"
"}\n"
)
_write(probe_src, probe_content)
ok(" vmnet: created netif_napi_add_check.c probe file")
_patch_insert_after(mk, anchor, insertion,
"vmnet Makefile.kernel: VMW_NETIF_SINGLE_NAPI_PARM detection (kernel 6.1+)")
# ── [AP-06] vmnet compat_netdevice.h: VMW_NETIF_SINGLE_NAPI_PARM guard ───────
#
# Problem: Even when VMW_NETIF_SINGLE_NAPI_PARM is set by the Makefile, the
# compat_netdevice.h guard only applies to the compat_napi_complete /
# compat_napi_schedule wrappers but NOT to compat_netif_napi_add
# itself on kernel >= 6.1.
# Probe: Check if the 6.1 override is present in compat_netdevice.h.
# Fix: Append an unconditional 6.1 guard (see AP-03 above — same file,
# AP-03 and AP-06 are intentionally combined).
# (Handled in _autopatch_napi_add_compat — AP-03)
# ── [AP-07] hostif.c: get_current_state → READ_ONCE(task->__state) ────────────
#
# Problem: On kernel >= 5.14, task->state was renamed to task->__state and
# direct reads require READ_ONCE(). VMware's hostif.c defines a
# get_task_state() macro that correctly handles this, but only if
# LINUX_VERSION_CODE >= 5.15.0 is detected. The check is already
# present in the 6.16.x upstream source — this autopatch verifies it.
# Probe: Look for the guard in hostif.c; warn if absent.
# Fix: Add the guard if it's missing.
def _autopatch_hostif_task_state(vmmon_dir: Path):
src = vmmon_dir / "linux" / "hostif.c"
if not src.exists():
return
text = _read(src)
# The fix is already in the 6.16.x upstream source. Verify it's present;
# if not (e.g. a different VMware source version), inject it.
marker = "get_task_state(task) READ_ONCE"
if marker in text:
info(" hostif.c: task->__state guard already present — skipped")
return
# Try to inject after the first #include block
anchor = "#include \"hostif.h\""
if anchor not in text:
anchor = "#include <linux/sched.h>"
if anchor not in text:
warn(" hostif.c: cannot locate anchor for task state guard")
return
insertion = (
"\n\n/* [autopatch] kernel 5.14+ renamed task->state to task->__state */\n"
"#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) || defined(get_current_state)\n"
"#define get_task_state(task) READ_ONCE((task)->__state)\n"
"#else\n"
"#define get_task_state(task) ((task)->state)\n"
"#endif"
)
_patch_insert_after(src, anchor, insertion,
"hostif.c: task->__state compat guard (kernel 5.14+)")
# ── [AP-08] vmnet bridge.c: do_gettimeofday removed (kernel >= 5.0) ──────────
#
# Problem: do_gettimeofday() was removed in kernel 5.0. vmnet/bridge.c calls
# it, but ONLY inside `#if LOGLEVEL >= 4` debug blocks. Since LOGLEVEL
# is not set at compile time in production builds, this is harmless in
# practice — but if someone enables LOGLEVEL the build will fail.
# Probe: Detect do_gettimeofday() outside of a LINUX_VERSION_CODE < 5.0 guard.
# Fix: Wrap the usages with a LINUX_VERSION_CODE guard and provide a
# ktime_get_real_ts64() fallback.
def _autopatch_bridge_gettimeofday(vmnet_dir: Path, kver: KernelVersion):
src = vmnet_dir / "bridge.c"
if not src.exists():
return
if (kver.major, kver.minor) < (5, 0):
info(" bridge.c: kernel < 5.0, do_gettimeofday still available — skipped")
return
text = _read(src)
if "do_gettimeofday" not in text:
info(" bridge.c: do_gettimeofday not present — skipped")
return
if "ktime_get_real_ts64" in text or "LINUX_VERSION_CODE < KERNEL_VERSION(5, 0" in text:
info(" bridge.c: do_gettimeofday already guarded — skipped")
return
# Replace the static vnetTime variable with a compat definition.
# 25H2u1 bridge.c wraps the declaration in #if LOGLEVEL >= 4; the 6.16.x overlay
# does not. Try the LOGLEVEL-wrapped form first (25H2u1), fall back to bare form.
replaced_vnettime = _patch_replace(src,
"#if LOGLEVEL >= 4\n"
"static struct timeval vnetTime;\n"
"#endif",
"#if LOGLEVEL >= 4\n"
"# if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)\n"
"static struct timeval vnetTime;\n"
"# else\n"
"static struct timespec64 vnetTime;\n"
"# endif\n"
"#endif",
"bridge.c: vnetTime timeval → timespec64 inside LOGLEVEL guard (25H2u1, kernel 5.0+)")
if not replaced_vnettime:
# Older source (6.16.x overlay): bare declaration without LOGLEVEL guard
_patch_replace(src,
"static struct timeval vnetTime;",
"/* [autopatch] do_gettimeofday removed in kernel 5.0 */\n"
"#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)\n"
"static struct timeval vnetTime;\n"
"#else\n"
"static struct timespec64 vnetTime;\n"
"#endif",
"bridge.c: vnetTime timeval → timespec64 (kernel 5.0+)")
# Replace `do_gettimeofday(&vnetTime)` with compat
_patch_replace_all(src,
"do_gettimeofday(&vnetTime)",
"/* [autopatch] */\\\n"
"#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)\n"
" do_gettimeofday(&vnetTime)\n"
"#else\n"
" ktime_get_real_ts64(&vnetTime)\n"
"#endif",
"bridge.c: do_gettimeofday(&vnetTime) → ktime_get_real_ts64 (kernel 5.0+)")
# The `struct timeval now;` local + `do_gettimeofday(&now)` pattern
_patch_replace(src,
"struct timeval now;\n do_gettimeofday(&now);",
"#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)\n"
" struct timeval now;\n"
" do_gettimeofday(&now);\n"
"#else\n"
" struct timespec64 now;\n"
" ktime_get_real_ts64(&now);\n"
"#endif",
"bridge.c: local timeval now → timespec64 (kernel 5.0+)")
# ── [AP-09] vmmon hostif.c: get_user_pages_fast FOLL_WRITE→0 for read mappings
#
# Problem: hostif.c calls get_user_pages_fast() with flags=0 (read-only)
# for guest-physical to host-physical page mapping. On kernel >= 5.9
# the signature changed: the third argument is now `unsigned int gup_flags`
# (was `int write`). The value 0 is compatible in both cases, but
# an explicit flag check can catch misuse.
# Probe: Verify the call signature matches current kernel expectations.
# (get_user_pages_fast still exists in 7.x with same int API — no fix needed.)
# Status: No-op — current kernel 7.x headers show same `int` API. Logged for
# awareness.
def _autopatch_hostif_gup(vmmon_dir: Path, kver: KernelVersion):
src = vmmon_dir / "linux" / "hostif.c"
if not src.exists():
return
text = _read(src)
if "get_user_pages_fast" not in text:
return
# Kernel 7.x still exports get_user_pages_fast with same prototype — OK
info(" hostif.c: get_user_pages_fast — API compatible, no fix needed")
# ── [AP-10] vmmon/vmnet: strncpy → strscpy (kernel 6.8+ W=1 deprecation) ─────
#
# Problem: Kernel 6.8 made strncpy() emit a deprecation warning under W=1.
# While not a build error by default, it clutters the build output
# and may become an error in future kernels.
# Probe: Search for strncpy() calls where strscpy() is a safe drop-in.
# Fix: Replace strncpy(dst, src, n) with strscpy(dst, src, n) where
# the destination size is the third argument (safe substitution).
# Only applied on kernel >= 6.8 where strscpy is guaranteed present.
def _autopatch_strncpy_to_strscpy(module_dir: Path, kver: KernelVersion):
if (kver.major, kver.minor) < (6, 8):
return
c_files = list(module_dir.rglob("*.c"))
replaced_files = 0
for f in c_files:
text = _read(f)
if "strncpy(" not in text:
continue
# Only replace patterns where strscpy is a safe drop-in:
# strncpy(dst, src, sizeof(dst)) or strncpy(dst, src, N)
new_text = re.sub(r'\bstrncpy\b\s*\(', 'strscpy(', text)
if new_text != text:
_write(f, new_text)
replaced_files += 1
if replaced_files:
ok(f" {module_dir.name}: strncpy → strscpy in {replaced_files} file(s) (kernel 6.8+)")
else:
info(f" {module_dir.name}: no strncpy replacements needed")
# ── [AP-11] vmnet/userif.c: get_user_pages_fast FOLL_WRITE flag ──────────────
#
# Problem: userif.c calls get_user_pages_fast(addr, 1, FOLL_WRITE, &page).
# FOLL_WRITE was introduced in 4.9 as the replacement for the old
# `int write` parameter. This is already correct for kernel >= 4.9.
# No fix needed — documented for completeness.
def _autopatch_userif_gup(_vmnet_dir: Path, _kver: KernelVersion):
info(" userif.c: get_user_pages_fast(FOLL_WRITE) — API compatible, no fix needed")
# ── [AP-12] vmmon: MODULE_IMPORT_NS for kernel lockdown (kernel >= 5.15) ──────
#
# Problem: On some kernels with lockdown or symbol namespaces enabled, modules
# must declare MODULE_IMPORT_NS(VMWCORE) or similar. Absence causes
# a taint or refusal to load. This is distribution-specific.
# Probe: Check if the kernel uses symbol namespaces for vmmon symbols.
# Fix: Add MODULE_IMPORT_NS if the kernel headers require it.
# (This is a best-effort; most distros don't enforce namespaces here.)
def _autopatch_module_import_ns(vmmon_dir: Path, kver: KernelVersion):
if (kver.major, kver.minor) < (5, 15):
return
driver = vmmon_dir / "linux" / "driver.c"
if not driver.exists():
return
text = _read(driver)
if "MODULE_IMPORT_NS" in text:
info(" driver.c: MODULE_IMPORT_NS already present — skipped")
return
# Only add if MODULE_LICENSE is present (sanity check)
if "MODULE_LICENSE" not in text:
return
# Check if kernel enforces namespaces for any exported symbol we use
# This is a heuristic — check for EXPORT_SYMBOL_NS in kernel headers
build_include = Path(f"/lib/modules/{kver.raw}/build/include")
if build_include.exists():
r = subprocess.run(
["grep", "-r", "-l", "-m1", "EXPORT_SYMBOL_NS", str(build_include)],
capture_output=True, text=True,
)
if r.returncode != 0:
info(" driver.c: kernel does not use symbol namespaces — skipped")
return
_patch_replace(driver,
"MODULE_LICENSE(",
"MODULE_IMPORT_NS(\"VMWCORE\");\nMODULE_LICENSE(",
"driver.c: MODULE_IMPORT_NS (kernel symbol namespace, 5.15+)")