Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
fix(game-mode): preserve game identity through Wine re-exec
sn0wst0rmba6d75080bd8
diff --git a/Makefile b/Makefileindex a9460c4..0c7d797 100644--- a/Makefile+++ b/Makefile@@ -471,7 +471,27 @@ $(APPINFO): helpers/appinfo.swiftswiftc -O -target $(ARCH)-apple-macos$(MIN_VER) -o $@ $<@echo "==> Built $@"-helpers-install: $(ICONMAKER) $(APPINFO)+GAME_HOST := $(OUT_DIR)/game-host.dylib+GAME_METADATA := $(OUT_DIR)/prepare-game-loader++$(GAME_HOST): helpers/game-host.c+ @mkdir -p $(OUT_DIR)+ $(CC) -dynamiclib -arch arm64 -arch x86_64 -mmacosx-version-min=$(MIN_VER) -O2 -Wall -Wextra $< -o $@+ codesign -f -s - --identifier com.notproton.game-host $@++$(GAME_METADATA): helpers/prepare-game-loader.swift+ @mkdir -p $(OUT_DIR)+ swiftc -O -target $(ARCH)-apple-macos$(MIN_VER) $< -o $@+ codesign -f -s - --identifier com.notproton.game-metadata $@++.PHONY: game-host-check+game-host-check: $(GAME_HOST) $(GAME_METADATA)+ python3 helpers/tests/game-host.py+ python3 helpers/tests/game-metadata.py $(GAME_METADATA)++helpers-install: $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(GAME_METADATA)+ $(call install_atomically,$(GAME_HOST),$(SUPPORT_DIR)/game-host.dylib)+ $(call install_atomically,$(GAME_METADATA),$(SUPPORT_DIR)/prepare-game-loader)$(call install_atomically,$(ICONMAKER),$(SUPPORT_DIR)/iconmaker)$(call install_atomically,$(APPINFO),$(SUPPORT_DIR)/appinfo)@echo "==> Installed: $(SUPPORT_DIR)/{iconmaker,appinfo}"@@ -545,8 +565,9 @@ bridge:fonts:fonts/build.sh-app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO)+app-payload: $(TARGET) $(OVERLAY_SHIM) $(ICONMAKER) $(APPINFO) $(GAME_HOST) $(GAME_METADATA)@mkdir -p "$(APP_PAYLOAD)/signatures/macos.arm64"+ cp -f $(GAME_HOST) $(GAME_METADATA) "$(APP_PAYLOAD)/"@mkdir -p "$(APP_PAYLOAD)/bridge"cp -f $(TARGET) "$(APP_PAYLOAD)/notproton.dylib"cp -f $(OVERLAY_SHIM) "$(APP_PAYLOAD)/overlay-shim.dylib"diff --git a/app/Sources/NotProtonApp/Model/DeploymentContent.swift b/app/Sources/NotProtonApp/Model/DeploymentContent.swiftindex 182fa1b..08541ab 100644--- a/app/Sources/NotProtonApp/Model/DeploymentContent.swift+++ b/app/Sources/NotProtonApp/Model/DeploymentContent.swift@@ -156,6 +156,10 @@ enum DeploymentContent {File(source: payload.iconmaker, destination: iconmaker, name: "iconmaker", executable: true),File(source: payload.appinfo, destination: appinfo, name: "appinfo", executable: true),]+ files += payload.runtime.sorted { $0.key < $1.key }.map { name, source in+ File(source: source, destination: iconmaker.deletingLastPathComponent().appending(path: name),+ name: name, executable: !name.hasSuffix(".dylib"))+ }files += payload.signatures.map {File(source: $0, destination: signatures.appending(path: $0.lastPathComponent),name: "signatures/\($0.lastPathComponent)")diff --git a/app/Sources/NotProtonApp/Model/InstallPayload.swift b/app/Sources/NotProtonApp/Model/InstallPayload.swiftindex b5d0d0e..3237749 100644--- a/app/Sources/NotProtonApp/Model/InstallPayload.swift+++ b/app/Sources/NotProtonApp/Model/InstallPayload.swift@@ -5,7 +5,10 @@ import Foundationenum InstallPayload {static let step = String(localized: "Find NotProton's components")+ static let runtimeFiles = ["prepare-game-loader", "game-host.dylib"]+struct Located: Sendable {+ var runtime: [String: URL] = [:]let dylib: URLlet overlayShim: URLlet iconmaker: URL@@ -73,6 +76,9 @@ enum InstallPayload {)) ?? []).filter { $0.pathExtension == "json" }.sorted { $0.lastPathComponent < $1.lastPathComponent }if signatures.isEmpty { missing.append("signatures/macos.arm64/*.json") }+ for name in runtimeFiles where !files.fileExists(atPath: root.appending(path: name).path) {+ missing.append(name)+ }let fontsRoot = root.appending(path: "fonts")let fonts = (files.subpaths(atPath: fontsRoot.path(percentEncoded: false)) ?? [])@@ -89,6 +95,7 @@ enum InstallPayload {let gamefixes = try locateGamefixes(in: root)return Located(+ runtime: Dictionary(uniqueKeysWithValues: runtimeFiles.map { ($0, root.appending(path: $0)) }),dylib: dylib, overlayShim: shim, iconmaker: iconmaker,appinfo: appinfo, run: run, builtAt: builtAt, signatures: signatures,fontsRoot: fontsRoot, fonts: fonts,diff --git a/app/Tests/NotProtonAppTests/InstallPayloadTests.swift b/app/Tests/NotProtonAppTests/InstallPayloadTests.swiftindex 6698ecc..859f1e0 100644--- a/app/Tests/NotProtonAppTests/InstallPayloadTests.swift+++ b/app/Tests/NotProtonAppTests/InstallPayloadTests.swift@@ -14,6 +14,11 @@ struct InstallPayloadTests {if shim { try Data("shim".utf8).write(to: root.appending(path: "overlay-shim.dylib")) }if iconmaker { try Data("iconmaker".utf8).write(to: root.appending(path: "iconmaker")) }if appinfo { try Data("appinfo".utf8).write(to: root.appending(path: "appinfo")) }+ for name in InstallPayload.runtimeFiles {+ let file = root.appending(path: name)+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data("runtime fixture".utf8).write(to: file)+ }try Data("#!/bin/sh\nexit 0\n".utf8).write(to: root.appending(path: "run"))try Data("100\n".utf8).write(to: root.appending(path: "build-time"))for name in signatures {@@ -90,6 +95,26 @@ struct InstallPayloadTests {}}+ @Test("Runtime helpers are required and included in the located payload")+ func requiresRuntimeHelpers() throws {+ let root = try scratchDirectory("runtime-payload")+ defer { try? FileManager.default.removeItem(at: root) }+ try stage(root)+ let located = try InstallPayload.locate(root: root)+ #expect(Set(located.runtime.keys) == Set(InstallPayload.runtimeFiles))+ for name in InstallPayload.runtimeFiles {+ let path = root.appending(path: name)+ try FileManager.default.removeItem(at: path)+ do {+ _ = try InstallPayload.locate(root: root)+ Issue.record("payload accepted without \(name)")+ } catch let failure as StepFailure {+ #expect(failure.detail.contains(name))+ }+ try Data("runtime fixture".utf8).write(to: path)+ }+ }+@Test("An empty payload names every missing artifact")func reportsEverythingMissing() throws {let root = try scratchDirectory("payload")diff --git a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift b/app/Tests/NotProtonAppTests/SteamInstallerTests.swiftindex 0674056..acaaf91 100644--- a/app/Tests/NotProtonAppTests/SteamInstallerTests.swift+++ b/app/Tests/NotProtonAppTests/SteamInstallerTests.swift@@ -42,6 +42,11 @@ struct SteamInstallerTests {let appinfo = root.appending(path: "appinfo")try FileManager.default.copyItem(at: dylib, to: appinfo)+ for name in InstallPayload.runtimeFiles {+ let file = root.appending(path: name)+ try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)+ try Data("runtime fixture".utf8).write(to: file)+ }try Data("#!/bin/sh\nexit 0\n".utf8).write(to: root.appending(path: "run"))try Data("100\n".utf8).write(to: root.appending(path: "build-time"))diff --git a/docs/game-mode-host.md b/docs/game-mode-host.mdnew file mode 100644index 0000000..e1f04f9--- /dev/null+++ b/docs/game-mode-host.md@@ -0,0 +1,29 @@+# Game app identity under Wine++Wine may re-execute a GUI process through a temporary hardlink outside the+game's app bundle. The generated app already has the game's name and icon,+but the executable has Wine's embedded bundle identity. Declaring Game Mode+support only in the external Info.plist is therefore insufficient on the+tested macOS system.++The native `prepare-game-loader` helper updates the embedded metadata in a+separate staged copy, preserves entitlements, signs it, and replaces the+staged loader atomically.+`game-host.dylib` redirects Wine's temporary `execv` only when the executable+argument resolves inside `STEAM_COMPAT_INSTALL_PATH`. Other Wine services and+external launchers retain their original identities. This avoids assigning+the game icon to every service in the prefix.++Both helpers are built and included in the normal app payload. Installation+and integrity checks cover them, and removing NotProton removes them with its+support directory.++This declares eligibility and preserves application identity. macOS still+decides when to activate Game Mode. Fullscreen behavior and process layouts+vary between games. The original implementation was validated on an Apple+Silicon Mac with macOS 27 and CrossOver 26.3 Rosetta; other combinations need+hardware verification before claiming universal compatibility.++Run `make game-host-check` for executable scoping, hardlink isolation,+metadata, code signature, malformed-input and idempotency tests. Existing+launcher routing and environment tests must also pass.diff --git a/dylib/feats/compat_run.sh b/dylib/feats/compat_run.shindex 62d5d0a..8759b1c 100755--- a/dylib/feats/compat_run.sh+++ b/dylib/feats/compat_run.sh@@ -1985,6 +1985,7 @@ cat > "$loader_contents/Info.plist" <<PLIST<key>CFBundlePackageType</key><string>APPL</string><key>CFBundleInfoDictionaryVersion</key><string>6.0</string><key>LSApplicationCategoryType</key><string>public.app-category.games</string>+ <key>LSSupportsGameMode</key><true/><key>NSHighResolutionCapable</key><true/><key>NSPrincipalClass</key><string>NSApplication</string><key>NSMicrophoneUsageDescription</key><string>This game would like to access your microphone.</string>@@ -2006,7 +2007,13 @@ for f in "$wine_unix"/*; doln -sfn "$f" "$loader_macos/$base"doneln "$WINELOADER" "$loader_macos/wine" 2>/dev/null || cp "$WINELOADER" "$loader_macos/wine"+game_host=""if [ -x "$loader_macos/wine" ]; then+ if "$np_support/prepare-game-loader" "$loader_macos/wine" "$loader_contents/Info.plist" >> "$log" 2>&1; then+ game_host="$np_support/game-host.dylib"+ else+ echo "embedded loader metadata unsupported; keeping original launcher behavior" >> "$log" 2>&1 || true+ fiWINELOADER="$loader_app/Contents/MacOS/wine"echo "loader staged in bundle for game mode" >> "$log" 2>&1 || trueelse@@ -2031,6 +2038,10 @@ elif [ -f "\$shim" ] && [ "\${NOTPROTON_FRAMEGEN:-0}" != 0 ] && [ "\$NOTPROTON_Fexport DYLD_INSERT_LIBRARIES="\$shim"export NOTPROTON_OVERLAY_SHIM="\$shim"fi+export NOTPROTON_GAME_LOADER="$WINELOADER"+if [ -n "$game_host" ]; then+ export DYLD_INSERT_LIBRARIES="$game_host\${DYLD_INSERT_LIBRARIES:+:\$DYLD_INSERT_LIBRARIES}"+fi[ -n "\$NOTPROTON_GAME_CWD" ] && cd "\$NOTPROTON_GAME_CWD""$WINELOADER" "\$@"exit \$?diff --git a/helpers/game-host.c b/helpers/game-host.cnew file mode 100644index 0000000..ae3a696--- /dev/null+++ b/helpers/game-host.c@@ -0,0 +1,107 @@+// Keep Wine child processes in the game's existing signed app bundle.+// CrossOver normally execs a renamed temporary hardlink outside that bundle;+// LaunchServices then has no bundle identity for the actual game window.+#include <unistd.h>+#include <stdlib.h>+#include <string.h>+#include <stdio.h>+#include <ctype.h>+#include <limits.h>++// Resolve the executable, not arbitrary command-line arguments. Services and+// launchers outside the Steam install directory keep their normal Wine host.+static int is_game_executable(const char *argument) {+ const char *root = getenv("STEAM_COMPAT_INSTALL_PATH");+ const char *prefix = getenv("WINEPREFIX");+ char normalized[PATH_MAX], candidate[PATH_MAX], real_root[PATH_MAX], real_exe[PATH_MAX];+ if (!argument || !root || !realpath(root, real_root)) {+ return 0;+ }+ if (strlcpy(normalized, argument, sizeof(normalized)) >= sizeof(normalized)) {+ return 0;+ }+ for (char *p = normalized; *p; p++) {+ if (*p == '\\') {+ *p = '/';+ }+ }+ const char *exe = normalized;+ // Normalize NT object-manager and Win32 extended path prefixes.+ if (!strncmp(exe, "/\?\?/", 4) || !strncmp(exe, "//?/", 4)) {+ exe += 4;+ }+ if (isalpha((unsigned char)exe[0]) && exe[1] == ':' && exe[2] == '/') {+ if (!prefix ||+ snprintf(candidate, sizeof(candidate), "%s/dosdevices/%c:%s", prefix,+ tolower((unsigned char)exe[0]), exe + 2) >= (int)sizeof(candidate)) {+ return 0;+ }+ } else {+ if (strlcpy(candidate, exe, sizeof(candidate)) >= sizeof(candidate)) {+ return 0;+ }+ }+ if (!realpath(candidate, real_exe)) {+ return 0;+ }+ size_t root_length = strlen(real_root), executable_length = strlen(real_exe);+ return executable_length > root_length + 4 && !strncmp(real_exe, real_root, root_length) &&+ real_exe[root_length] == '/' && !strcasecmp(real_exe + executable_length - 4, ".exe");+}++static const char *game_loader_for(const char *path, char *const argv[]) {+ const char *loader = getenv("NOTPROTON_GAME_LOADER");+ const char *tmp = getenv("TMPDIR");+ const char *noexec = getenv("WINELOADERNOEXEC");+ if (!path || !loader || !tmp || !noexec || strcmp(noexec, "1")) {+ return NULL;+ }+ // TMPDIR may end in '/'. Match its next component, not a string prefix+ // such as /tmp/game-other, and only Wine's immediate winetemp directory.+ size_t temporary_length = strlen(tmp);+ while (temporary_length > 1 && tmp[temporary_length - 1] == '/') {+ --temporary_length;+ }+ if (!temporary_length || strncmp(path, tmp, temporary_length) ||+ (temporary_length > 1 && path[temporary_length] != '/')) {+ return NULL;+ }+ // CrossOver appends /winetemp to a directory that may already end in '/'.+ const char *next_component = path + temporary_length;+ while (*next_component == '/') {+ ++next_component;+ }+ if (strncmp(next_component, "winetemp-", 9)) {+ return NULL;+ }+ const char *loader_suffix = ".app/Contents/MacOS/wine";+ size_t loader_length = strlen(loader), suffix_length = strlen(loader_suffix);+ if (!strstr(loader, "/Application Support/notproton/launchers/") ||+ loader_length < suffix_length ||+ strcmp(loader + loader_length - suffix_length, loader_suffix)) {+ return NULL;+ }+ if (access(loader, X_OK)) {+ return NULL;+ }+ if (!argv || !argv[0] || !is_game_executable(argv[1])) {+ return NULL;+ }+ return loader;+}++static int game_execv(const char *path, char *const argv[]) {+ const char *loader = game_loader_for(path, argv);+ if (loader) {+ fprintf(stderr, "NotProton Game Host: game executable stays inside game app (%s)\n",+ strrchr(path, '/') + 1);+ return execv(loader, argv);+ }+ return execv(path, argv);+}+#ifndef GAME_HOST_TEST+__attribute__((used)) static const struct {+ const void *new_fn, *old_fn;+} interpose_execv __attribute__((section("__DATA,__interpose"))) = {(const void *)game_execv,+ (const void *)execv};+#endifdiff --git a/helpers/prepare-game-loader.swift b/helpers/prepare-game-loader.swiftnew file mode 100644index 0000000..46f4bba--- /dev/null+++ b/helpers/prepare-game-loader.swift@@ -0,0 +1,174 @@+// Give the staged Wine loader its game app identity by atomically replacing+// a private copy, preserving the shared runner inode.+import Darwin+import Foundation++enum PrepareError: Error { case invalid(String) }++// Sizes and offsets below are from mach_header_64, segment_command_64 and section_64.+private enum MachOLayout {+ static let magic64: UInt64 = 0xfeed_facf+ static let segment64: UInt64 = 0x19+ static let headerSize = 32+ static let segmentSize = 72+ static let sectionSize = 80+}++func readLittleEndianInteger(_ data: Data, _ offset: Int, _ size: Int) throws -> UInt64 {+ guard offset >= 0, (1...8).contains(size), offset <= data.count - size else {+ throw PrepareError.invalid("Truncated Mach-O")+ }+ return (0..<size).reduce(0) { $0 | UInt64(data[offset + $1]) << ($1 * 8) }+}++func embeddedPlistSection(_ data: Data) throws -> Range<Int>? {+ guard try readLittleEndianInteger(data, 0, 4) == MachOLayout.magic64 else {+ throw PrepareError.invalid("Expected a thin 64-bit Wine loader")+ }+ let count = Int(try readLittleEndianInteger(data, 16, 4))+ let commandBytes = Int(try readLittleEndianInteger(data, 20, 4))+ guard data.count >= MachOLayout.headerSize,+ commandBytes <= data.count - MachOLayout.headerSize,+ count <= commandBytes / 8+ else {+ throw PrepareError.invalid("Invalid Mach-O load command table")+ }+ let commandsEnd = MachOLayout.headerSize + commandBytes+ var position = MachOLayout.headerSize+ var plist: Range<Int>?+ for _ in 0..<count {+ guard position <= commandsEnd - 8 else {+ throw PrepareError.invalid("Truncated Mach-O load command")+ }+ let command = try readLittleEndianInteger(data, position, 4)+ let size = Int(try readLittleEndianInteger(data, position + 4, 4))+ guard size >= 8, size % 8 == 0, size <= commandsEnd - position else {+ throw PrepareError.invalid("Invalid Mach-O load command size")+ }+ if command == MachOLayout.segment64 {+ guard size >= MachOLayout.segmentSize else {+ throw PrepareError.invalid("Truncated Mach-O segment")+ }+ let sections = Int(try readLittleEndianInteger(data, position + 64, 4))+ guard sections <= (size - MachOLayout.segmentSize) / MachOLayout.sectionSize else {+ throw PrepareError.invalid("Invalid section table")+ }+ for index in 0..<sections {+ let entry = position + MachOLayout.segmentSize + index * MachOLayout.sectionSize+ let name = String(+ decoding: data[entry..<entry + 16].prefix { $0 != 0 }, as: UTF8.self)+ let segment = String(+ decoding: data[entry + 16..<entry + 32].prefix { $0 != 0 }, as: UTF8.self)+ if name == "__info_plist" && segment == "__TEXT" {+ let length = try readLittleEndianInteger(data, entry + 40, 8)+ let start = Int(try readLittleEndianInteger(data, entry + 48, 4))+ guard plist == nil, start >= commandsEnd, start <= data.count,+ length <= UInt64(data.count - start)+ else {+ throw PrepareError.invalid("Invalid embedded plist section")+ }+ plist = start..<start + Int(length)+ }+ }+ }+ position += size+ }+ guard position == commandsEnd else {+ throw PrepareError.invalid("Mach-O command count does not match its table")+ }+ return plist+}++func runCodesign(_ arguments: [String]) throws -> Data {+ let process = Process()+ let output = Pipe()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/codesign")+ process.arguments = arguments+ process.standardOutput = output+ try process.run()+ let data = output.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()+ guard process.terminationStatus == 0 else { throw PrepareError.invalid("codesign failed") }+ return data+}++func prepare(_ target: URL, _ info: URL) throws {+ let original = try Data(contentsOf: target)+ guard let section = try embeddedPlistSection(original) else {+ print("Game Mode: no embedded plist; keeping app metadata")+ return+ }+ var bytes = original.subdata(in: section)+ while bytes.last == 0 || bytes.last == 32 { bytes.removeLast() }+ guard+ let old = try PropertyListSerialization.propertyList(from: bytes, format: nil)+ as? [String: Any],+ let app = try PropertyListSerialization.propertyList(+ from: Data(contentsOf: info), format: nil) as? [String: Any],+ let identity = app["CFBundleIdentifier"] as? String,+ identity.hasPrefix("com.notproton.launcher."),+ let name = app["CFBundleName"] as? String,+ target.lastPathComponent == "wine"+ else {+ throw PrepareError.invalid("Not a staged NotProton game loader")+ }+ var updated = old.filter {+ [+ "CFBundleAllowMixedLocalizations", "CFBundleDevelopmentRegion",+ "CFBundleInfoDictionaryVersion", "CFBundleShortVersionString", "CFBundleVersion",+ ].contains($0.key)+ }+ updated.merge([+ "CFBundleIdentifier": identity, "CFBundleName": name,+ "CFBundleExecutable": "wine", "CFBundlePackageType": "APPL",+ "NSPrincipalClass": "WineApplication",+ "NSHighResolutionCapable": true, "LSApplicationCategoryType": "public.app-category.games",+ "LSSupportsGameMode": true,+ ]) { _, new in new }+ let xml = try PropertyListSerialization.data(+ fromPropertyList: updated, format: .xml, options: 0)+ let compact = Data(+ String(decoding: xml, as: UTF8.self).split(separator: "\n")+ .map { $0.trimmingCharacters(in: .whitespaces) }.joined().utf8)+ guard compact.count <= section.count else {+ throw PrepareError.invalid("Game metadata exceeds reserved section")+ }+ var replacement = original+ replacement.replaceSubrange(+ section, with: compact + Data(repeating: 32, count: section.count - compact.count))+ if replacement == original { return }+ let files = FileManager.default+ let temporary = target.deletingLastPathComponent().appendingPathComponent(+ ".game-loader-" + UUID().uuidString)+ try files.createDirectory(at: temporary, withIntermediateDirectories: false)+ defer { try? files.removeItem(at: temporary) }+ let staged = temporary.appendingPathComponent("wine")+ try replacement.write(to: staged)+ let attributes = try files.attributesOfItem(atPath: target.path)+ try files.setAttributes(+ [.posixPermissions: attributes[.posixPermissions] ?? 0o755], ofItemAtPath: staged.path)+ let entitlements = try runCodesign(["-d", "--entitlements", ":-", target.path])+ var arguments = ["--force", "--sign", "-", "--identifier", identity, "--options", "runtime"]+ if !entitlements.isEmpty {+ _ = try PropertyListSerialization.propertyList(from: entitlements, format: nil)+ let file = temporary.appendingPathComponent("entitlements.plist")+ try entitlements.write(to: file)+ arguments += ["--entitlements", file.path]+ }+ _ = try runCodesign(arguments + [staged.path])+ _ = try runCodesign(["--verify", "--strict", staged.path])+ guard rename(staged.path, target.path) == 0 else {+ throw PrepareError.invalid("Atomic replacement failed: \(errno)")+ }+ print("Game Mode: staged Wine metadata updated for \(identity)")+}++do {+ guard CommandLine.arguments.count == 3 else { exit(64) }+ try prepare(+ URL(fileURLWithPath: CommandLine.arguments[1]),+ URL(fileURLWithPath: CommandLine.arguments[2]))+} catch {+ fputs("Game Mode: \(error)\n", stderr)+ exit(1)+}diff --git a/helpers/tests/game-host.py b/helpers/tests/game-host.pynew file mode 100644index 0000000..bbd0745--- /dev/null+++ b/helpers/tests/game-host.py@@ -0,0 +1,125 @@+"""Game child identity must not spread to Wine/Ubisoft helper processes."""++from pathlib import Path+import os, subprocess, tempfile++root = Path(__file__).resolve().parent.parent+with tempfile.TemporaryDirectory(prefix="dsb-host-") as tmp:+ t = Path(tmp)+ game = t / "Games" / "Example Game"+ game.mkdir(parents=True)+ sibling = t / "Games" / "Example Game Tools"+ sibling.mkdir()+ prefix = t / "prefix"+ (prefix / "dosdevices").mkdir(parents=True)+ (prefix / "drive_c/windows/system32").mkdir(parents=True)+ (prefix / "drive_c/Program Files/Ubisoft").mkdir(parents=True)+ (prefix / "dosdevices/s:").symlink_to(t / "Games", target_is_directory=True)+ (prefix / "dosdevices/c:").symlink_to("../drive_c", target_is_directory=True)+ (prefix / "dosdevices/z:").symlink_to("/", target_is_directory=True)+ loader = t / "Application Support/notproton/launchers/999/Game.app/Contents/MacOS/wine"+ loader.parent.mkdir(parents=True)+ loader.write_text("")+ loader.chmod(0o755)+ exe = game / "Binaries/Win64/game.exe"+ exe.parent.mkdir(parents=True)+ exe.touch()+ service = prefix / "drive_c/windows/system32/winedevice.exe"+ service.touch()+ launcher = prefix / "drive_c/Program Files/Ubisoft/upc.exe"+ launcher.touch()+ other = sibling / "tool.exe"+ other.touch()+ (game / "escape.exe").symlink_to(service)+ (t / "Steam").symlink_to(game, target_is_directory=True)+ probe = t / "probe.c"+ probe.write_text(+ '#define GAME_HOST_TEST\n#include "'+ + str(root / "game-host.c")+ + '"\nint main(int argc,char **argv){char *child[]={argv[1],argc>2?argv[2]:NULL,argc>3?argv[3]:NULL,NULL};puts(game_loader_for(argv[1],child)?"game":"original");}\n'+ )+ subprocess.run(+ [+ "clang",+ "-O2",+ "-Wall",+ "-Wextra",+ "-Wno-unused-function",+ str(probe),+ "-o",+ str(t / "probe"),+ ],+ check=True,+ )+ env = dict(+ os.environ,+ NOTPROTON_GAME_LOADER=str(loader),+ WINEPREFIX=str(prefix),+ WINELOADERNOEXEC="1",+ STEAM_COMPAT_INSTALL_PATH=str(t / "Steam"),+ )+ temp_loader = os.environ["TMPDIR"].rstrip("/") + "/winetemp-123/game.exe"+ cases = [+ ("S:\\Example Game\\Binaries\\Win64\\game.exe", True),+ ("\\??\\s:\\Example Game\\Binaries\\Win64\\game.exe", True),+ ("\\\\?\\S:\\Example Game\\Binaries\\Win64\\game.exe", True),+ (str(exe), True),+ ("Binaries/Win64/game.exe", True),+ ("C:\\windows\\system32\\winedevice.exe", False),+ ("C:\\Program Files\\Ubisoft\\upc.exe", False),+ (str(other), False),+ (str(game / "escape.exe"), False),+ ("S:\\Example Game\\missing.exe", False),+ ("game.exe", False),+ ("", False),+ ]+ for argument, expected in cases:+ got = subprocess.check_output(+ [str(t / "probe"), temp_loader, argument], env=env, cwd=game, text=True+ ).strip()+ assert got == ("game" if expected else "original"), (argument, got)+ for args in (+ [str(t / "probe"), "/tmp/unrelated-wine", str(exe)],+ [str(t / "probe"), temp_loader, str(launcher), str(exe)],+ [str(t / "probe"), temp_loader],+ ):+ assert subprocess.check_output(args, env=env, text=True).strip() == "original"+ # A similarly named temporary directory or executable is not a Wine re-exec.+ temp_root = os.environ["TMPDIR"].rstrip("/")+ for candidate in (+ temp_root + "-other/winetemp-123/game.exe",+ temp_root + "/unrelated/winetemp-123/game.exe",+ temp_root + "//unrelated/winetemp-123/game.exe",+ ):+ assert (+ subprocess.check_output(+ [str(t / "probe"), candidate, str(exe)], env=env, text=True+ ).strip()+ == "original"+ )+ # CrossOver appends /winetemp to confstr's already slash-terminated directory.+ for separators in ("/", "//", "///"):+ candidate = temp_root + separators + "winetemp-123/game.exe"+ for temporary_root in (temp_root, temp_root + "/"):+ assert (+ subprocess.check_output(+ [str(t / "probe"), candidate, str(exe)],+ env=dict(env, TMPDIR=temporary_root),+ text=True,+ ).strip()+ == "game"+ ), (candidate, temporary_root)+ other_loader = loader.with_name("wine-other")+ other_loader.touch()+ other_loader.chmod(0o755)+ assert (+ subprocess.check_output(+ [str(t / "probe"), temp_loader, str(exe)],+ env=dict(env, NOTPROTON_GAME_LOADER=str(other_loader)),+ text=True,+ ).strip()+ == "original"+ )+ print(+ "PASS: only actual game executables retain game identity; services, launcher, escapes and argument-only matches excluded"+ )diff --git a/helpers/tests/game-metadata.py b/helpers/tests/game-metadata.pynew file mode 100644index 0000000..8fdf1bc--- /dev/null+++ b/helpers/tests/game-metadata.py@@ -0,0 +1,85 @@+"""Validate identity, signing and hardlink isolation on a synthetic Wine loader."""++import os, pathlib, plistlib, struct, subprocess, sys, tempfile++tool = pathlib.Path(sys.argv[1]).resolve()+with tempfile.TemporaryDirectory(prefix="np-game-metadata-") as folder:+ root = pathlib.Path(folder)+ old = {+ "CFBundleIdentifier": "com.codeweavers.CrossOver.wineloader",+ "CFBundleName": "Wine",+ "CFBundleVersion": "1",+ }+ embedded = root / "embedded.plist"+ embedded.write_bytes(plistlib.dumps(old).ljust(4096, b" "))+ c = root / "fixture.c"+ c.write_text("int main(void) { return 0; }\n")+ runner = root / "runner"+ subprocess.run(+ [+ "clang",+ str(c),+ "-Wl,-sectcreate,__TEXT,__info_plist," + str(embedded),+ "-o",+ str(runner),+ ],+ check=True,+ )+ subprocess.run(["codesign", "-s", "-", str(runner)], check=True)+ wine = root / "wine"+ os.link(runner, wine)+ before = runner.read_bytes()+ info = root / "Info.plist"+ info.write_bytes(+ plistlib.dumps(+ {"CFBundleIdentifier": "com.notproton.launcher.999", "CFBundleName": "Example Game"}+ )+ )+ subprocess.run([str(tool), str(wine), str(info)], check=True)+ assert runner.read_bytes() == before, "shared runner inode was modified"+ assert runner.stat().st_ino != wine.stat().st_ino+ subprocess.run(["codesign", "--verify", "--strict", str(wine)], check=True)+ blob = wine.read_bytes()+ assert b"com.notproton.launcher.999" in blob and b"LSSupportsGameMode" in blob+ subprocess.run([str(tool), str(wine), str(info)], check=True)+ assert wine.read_bytes() == blob, "second preparation is not idempotent"+ info.write_bytes(plistlib.dumps({"CFBundleIdentifier": "unrelated.app", "CFBundleName": "Bad"}))+ assert subprocess.run([str(tool), str(wine), str(info)], capture_output=True).returncode != 0+ assert wine.read_bytes() == blob+ info.write_bytes(+ plistlib.dumps(+ {"CFBundleIdentifier": "com.notproton.launcher.999", "CFBundleName": "Example Game"}+ )+ )+ command_offset = 32+ plist_section = None+ for _ in range(struct.unpack_from("<I", before, 16)[0]):+ command, size = struct.unpack_from("<II", before, command_offset)+ if command == 0x19:+ for index in range(struct.unpack_from("<I", before, command_offset + 64)[0]):+ section = command_offset + 72 + index * 80+ if before[section : section + 16].rstrip(b"\0") == b"__info_plist":+ plist_section = section+ command_offset += size+ assert plist_section is not None++ def reject(label, data):+ wine.write_bytes(data)+ result = subprocess.run([str(tool), str(wine), str(info)], capture_output=True)+ assert result.returncode != 0, label+ assert wine.read_bytes() == data, "failed parse must not modify " + label++ reject("non Mach-O", b"not a Mach-O")+ for label, offset, value in (+ ("commands beyond file", 20, len(before) + 4096),+ ("command count mismatch", 16, struct.unpack_from("<I", before, 16)[0] + 1),+ ("short segment", 36, 8),+ ("section overlaps header", plist_section + 48, 8),+ ("section outside file", plist_section + 48, len(before) + 1),+ ):+ malformed = bytearray(before)+ struct.pack_into("<I", malformed, offset, value)+ reject(label, malformed)+ print(+ "PASS metadata: scoped identity, valid signature, unchanged runner, idempotency, invalid input rejection"+ )