Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

feat(native-launch): np-native keeps Steam's overlay, adds our shims and prefers arm64

raymondchinsc286d132f98b
diff --git a/Makefile b/Makefile
index f9f75db..166263c 100644
--- a/Makefile
+++ b/Makefile
@@ -636,3 +636,24 @@ rebuild: clean all
-include $(DEPS)
FORCE:
+
+# np-native: Steam launch-option wrapper for native macOS games (arm64
+# preferred, Steam's DYLD_INSERT_LIBRARIES kept). Installed later to
+# ~/.notproton/np-native.
+NP_NATIVE := $(OUT_DIR)/np-native/np-native
+NP_NATIVE_SRC := native-launch/np-native.c
+
+.PHONY: np-native np-native-tests
+
+np-native: $(NP_NATIVE)
+
+$(NP_NATIVE): $(NP_NATIVE_SRC)
+ @mkdir -p $(dir $@)
+ $(CC) -arch arm64 -arch x86_64 -mmacosx-version-min=11.0 -std=c17 -O2 \
+ -Wall -Wextra -Werror $< -o $@
+ codesign -s - -f $@
+ @echo "==> Built $@ ($$(lipo -archs $@))"
+
+np-native-tests: $(NP_NATIVE)
+ @if [ ! -f native-launch/tests/run.sh ]; then $(call SKIP,np-native-tests,native-launch/tests/run.sh); exit 0; fi; \
+ sh native-launch/tests/run.sh $(NP_NATIVE)
diff --git a/native-launch/apply-launch-options.py b/native-launch/apply-launch-options.py
new file mode 100644
index 0000000..ca5ef53
--- /dev/null
+++ b/native-launch/apply-launch-options.py
@@ -0,0 +1,243 @@
+#!/usr/bin/env python3
+"""Point the native macOS games' Steam launch options at np-native.
+
+ python3 native-launch/apply-launch-options.py [--dry-run] <localconfig.vdf>
+
+For each app id in GAMES the LaunchOptions value becomes
+
+ ~/.notproton/np-native NP_PAD_MODE=<mode> [SDL_JOYSTICK_MFI=0] \
+ MTL_HUD_ENABLED=1 [other VAR=VALUE kept from the old prefix] \
+ %command% <game flags that followed %command%>
+
+The old prefix may be the `/usr/bin/arch ... -e VAR=VALUE` form, a
+`/usr/bin/env VAR=VALUE` form, plain `VAR=VALUE` tokens or an earlier np-native
+line; anything else is reported and that app is left untouched. Running it
+twice changes nothing the second time.
+
+Steam rewrites localconfig.vdf on exit, so the script refuses to run while
+steam_osx is up. --allow-running exists for tests on a copy and is refused
+for files inside the Steam folder. A timestamped backup is written next to
+the file before the first change.
+"""
+import argparse
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+NP_NATIVE = os.path.join(os.path.expanduser("~"), ".notproton", "np-native")
+STEAM_DIR = os.path.join(os.path.expanduser("~"), "Library", "Application Support", "Steam")
+
+# app id -> pad mode (from the per-game research in native-games.json)
+GAMES = {
+ "1049410": "hid", # Superliminal
+ "1091500": "gc", # Cyberpunk 2077
+ "1145350": "hid", # Hades II
+ "1145360": "hid", # Hades
+ "1703340": "hid", # The Stanley Parable Ultra Deluxe
+ "239140": "hid", # Dying Light
+ "250900": "hid", # The Binding of Isaac Rebirth
+ "274190": "hid", # Broforce
+ "275850": "gc", # No Man's Sky
+ "286160": "hid", # Tabletop Simulator
+ "49520": "hid", # Borderlands 2
+ "570": "hid", # Dota 2
+ "728880": "hid", # Overcooked! 2
+ "870780": "gc", # Control
+ "934700": "gc", # Dead Island 2
+ "3978510": "hid", # Chained Beasts Demo
+}
+# SDL builds with their own MFi backend would see the pad twice
+NO_MFI = {"1145350", "570"}
+
+MANAGED = {"DYLD_INSERT_LIBRARIES", "NP_PAD_MODE", "SDL_JOYSTICK_MFI", "MTL_HUD_ENABLED"}
+ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
+NP_NAME = re.compile(r"^[A-Z_][A-Z0-9_]*$") # what np-native accepts
+WRAPPERS = {"/usr/bin/arch", "/usr/bin/env", "arch", "env", NP_NATIVE}
+ARCH_FLAGS = {"-arm64", "-x86_64", "-arm64e", "-i386"}
+
+LINE = re.compile(r'^(?P<ind>\s*)"(?P<key>(?:[^"\\]|\\.)*)"(?:(?P<sep>\s+)"(?P<val>(?:[^"\\]|\\.)*)")?\s*$')
+
+
+def vdf_unescape(s):
+ return re.sub(r"\\(.)", lambda m: {"n": "\n", "t": "\t"}.get(m.group(1), m.group(1)), s)
+
+
+def vdf_escape(s):
+ return s.replace("\\", "\\\\").replace('"', '\\"')
+
+
+def new_options(appid, old):
+ """Returns (new value, None) or (None, reason it was skipped)."""
+ if "%command%" in old:
+ pre, post = old.split("%command%", 1)
+ else:
+ pre, post = "", old # Steam appends bare options to the command
+ flags = post.strip()
+ try:
+ toks = shlex.split(pre)
+ except ValueError as e:
+ return None, "cannot parse prefix (%s)" % e
+ extras = []
+ i = 0
+ while i < len(toks):
+ t = toks[i]
+ if t == "-e" and i + 1 < len(toks):
+ i += 1
+ t = toks[i]
+ if not ASSIGN.match(t):
+ return None, "unexpected '-e %s' in prefix" % t
+ if ASSIGN.match(t):
+ name = t.split("=", 1)[0]
+ if name not in MANAGED:
+ if not NP_NAME.match(name):
+ return None, "np-native only takes [A-Z_][A-Z0-9_]* names, not %r" % name
+ extras.append(t)
+ elif t in WRAPPERS or t in ARCH_FLAGS or t == "--":
+ pass
+ else:
+ return None, "unknown token %r before %%command%%" % t
+ i += 1
+ parts = [NP_NATIVE, "NP_PAD_MODE=" + GAMES[appid]]
+ if appid in NO_MFI:
+ parts.append("SDL_JOYSTICK_MFI=0")
+ parts.append("MTL_HUD_ENABLED=1")
+ parts += [shlex.quote(e) for e in extras]
+ parts.append("%command%")
+ if flags:
+ parts.append(flags)
+ return " ".join(parts), None
+
+
+def in_apps(path):
+ """True for the key path <root>/Software/Valve/Steam/apps."""
+ return len(path) == 5 and all(path) and \
+ [k.lower() for k in path[1:]] == ["software", "valve", "steam", "apps"]
+
+
+def rewrite(text):
+ """Returns (new text, report lines, number of changed apps)."""
+ lines = text.splitlines(keepends=True)
+ stack = [] # key path of open blocks
+ pending = None # key waiting for its "{"
+ apps = {} # appid -> dict(open=idx of "{", close=idx, opt=idx, indent)
+ for idx, raw in enumerate(lines):
+ s = raw.strip()
+ if s == "{":
+ stack.append(pending)
+ pending = None
+ if in_apps(stack[:-1]) and stack[-1] in GAMES:
+ apps[stack[-1]] = {"open": idx, "opt": None,
+ "indent": re.match(r"\s*", raw).group(0)}
+ continue
+ if s == "}":
+ if not stack:
+ raise SystemExit("malformed vdf: unbalanced '}' at line %d" % (idx + 1))
+ closed = stack.pop()
+ if closed in apps and in_apps(stack):
+ apps[closed]["close"] = idx
+ continue
+ if not s:
+ continue
+ m = LINE.match(raw.rstrip("\r\n"))
+ if not m:
+ raise SystemExit("malformed vdf at line %d: %r" % (idx + 1, s[:80]))
+ if m.group("val") is None:
+ pending = vdf_unescape(m.group("key"))
+ continue
+ if m.group("key").lower() == "launchoptions" and stack[-1:] and stack[-1] in apps \
+ and in_apps(stack[:-1]):
+ apps[stack[-1]]["opt"] = idx
+ if stack:
+ raise SystemExit("malformed vdf: %d unclosed block(s)" % len(stack))
+
+ report, changed, inserts = [], 0, []
+ for appid in GAMES:
+ a = apps.get(appid)
+ if a is None:
+ report.append("%-8s MISSING (no app block in Software/Valve/Steam/apps)" % appid)
+ continue
+ if a["opt"] is not None:
+ m = LINE.match(lines[a["opt"]].rstrip("\r\n"))
+ old = vdf_unescape(m.group("val"))
+ else:
+ old = ""
+ new, why = new_options(appid, old)
+ if new is None:
+ report.append("%-8s SKIPPED: %s\n old: %s" % (appid, why, old))
+ continue
+ if new == old:
+ report.append("%-8s unchanged: %s" % (appid, old))
+ continue
+ changed += 1
+ report.append("%-8s before: %s\n after: %s" % (appid, old or "(none)", new))
+ if a["opt"] is not None:
+ raw = lines[a["opt"]]
+ eol = raw[len(raw.rstrip("\r\n")):]
+ m = LINE.match(raw.rstrip("\r\n"))
+ lines[a["opt"]] = '%s"%s"%s"%s"%s' % (m.group("ind"), m.group("key"),
+ m.group("sep"), vdf_escape(new), eol)
+ else:
+ raw = lines[a["open"]]
+ eol = raw[len(raw.rstrip("\r\n")):] or "\n"
+ inserts.append((a["open"] + 1,
+ '%s\t"LaunchOptions"\t\t"%s"%s' % (a["indent"], vdf_escape(new), eol)))
+ for pos, line in sorted(inserts, reverse=True):
+ lines.insert(pos, line)
+ return "".join(lines), report, changed
+
+
+def steam_running():
+ try:
+ return subprocess.run(["/usr/bin/pgrep", "-x", "steam_osx"],
+ stdout=subprocess.DEVNULL).returncode == 0
+ except OSError:
+ return True # cannot tell: assume it is
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("vdf", help="path to userdata/<id>/config/localconfig.vdf")
+ ap.add_argument("--dry-run", action="store_true", help="print the changes, write nothing")
+ ap.add_argument("--allow-running", action="store_true",
+ help="skip the Steam check (only for copies outside the Steam folder)")
+ args = ap.parse_args()
+
+ path = os.path.realpath(args.vdf)
+ in_steam = path.startswith(os.path.realpath(STEAM_DIR) + os.sep)
+ if args.allow_running and in_steam:
+ sys.exit("refusing --allow-running for a file inside the Steam folder: %s" % path)
+ if not args.allow_running and not args.dry_run and steam_running():
+ sys.exit("Steam is running (steam_osx); quit Steam first, it rewrites %s on exit"
+ % os.path.basename(path))
+
+ with open(path, encoding="utf-8", newline="") as f:
+ text = f.read()
+ new, report, changed = rewrite(text)
+ print("\n".join(report))
+ if not changed:
+ print("==> nothing to change")
+ return
+ if args.dry_run:
+ print("==> %d app(s) would change (dry run)" % changed)
+ return
+ backup = "%s.bak-np-native-%s" % (path, time.strftime("%Y%m%d-%H%M%S"))
+ shutil.copy2(path, backup)
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".localconfig.")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as f:
+ f.write(new)
+ shutil.copymode(path, tmp)
+ os.replace(tmp, path)
+ except BaseException:
+ os.unlink(tmp)
+ raise
+ print("==> %d app(s) changed; backup at %s" % (changed, backup))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/native-launch/np-native.c b/native-launch/np-native.c
new file mode 100644
index 0000000..d0c61ca
--- /dev/null
+++ b/native-launch/np-native.c
@@ -0,0 +1,443 @@
+/*
+ * np-native: Steam launch-option wrapper for native macOS games.
+ *
+ * np-native [VAR=VALUE ...] [--] %command% [game args]
+ *
+ * Steam on Apple Silicon is an x86_64 process, so a native game it spawns
+ * inherits Rosetta unless something re-execs it with arm64 preferred. The
+ * system `arch` tool does that but is SIP protected, so dyld strips every
+ * DYLD_* variable Steam set (its overlay injection included) before the game
+ * starts. This launcher is a plain, non-system binary: it sees Steam's
+ * DYLD_INSERT_LIBRARIES, merges our shims in front of it and replaces itself
+ * with the game (POSIX_SPAWN_SETEXEC keeps the pid Steam is tracking).
+ *
+ * Environment sources, highest precedence first:
+ * 1. VAR=VALUE launch-option arguments
+ * 2. ~/Library/Application Support/notproton/gamefixes/native/<appid>.conf
+ * 3. ~/Library/Application Support/notproton/gamefixes/native-default.conf
+ * 4. the environment Steam passed in
+ *
+ * DYLD_INSERT_LIBRARIES is composed, never replaced:
+ * gamepad shim (~/.notproton/libnp_gamepad.dylib, unless NP_PAD_MODE=off)
+ * overlay shim (only when NOTPROTON_FRAMEGEN is set and not 0/off)
+ * DYLD_INSERT_LIBRARIES given through the sources above
+ * DYLD_INSERT_LIBRARIES and STEAM_DYLD_INSERT_LIBRARIES received from Steam
+ * de-duplicated, ours first. STEAM_DYLD_INSERT_LIBRARIES is set to the same
+ * list because Valve's launch scripts (e.g. dota.sh) run under SIP-protected
+ * /bin/bash and restore DYLD_INSERT_LIBRARIES from it.
+ *
+ * Fail open: a malformed conf line, an unreadable conf, a missing shim or any
+ * other problem outside the command line is warned about on stderr and the
+ * game still starts. Only an unusable command line (no program, an invalid
+ * NAME=VALUE token) or a failed exec exits 127. A library that does not exist
+ * is never put into DYLD_INSERT_LIBRARIES, since dyld would abort the game.
+ */
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <mach/machine.h>
+#include <pwd.h>
+#include <spawn.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+extern char **environ;
+
+#define FAIL_EXIT 127
+#define PAD_SHIM_REL "/.notproton/libnp_gamepad.dylib"
+#define OVERLAY_SHIM_REL "/Library/Application Support/notproton/overlay-shim.dylib"
+#define CONF_DIR_REL "/Library/Application Support/notproton/gamefixes"
+#define MAX_LIBS 64
+
+static void die(const char *fmt, ...) __attribute__((noreturn, format(printf, 1, 2)));
+static void die(const char *fmt, ...)
+{
+ va_list ap;
+ fputs("np-native: ", stderr);
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fputc('\n', stderr);
+ exit(FAIL_EXIT);
+}
+
+static void warn(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
+static void warn(const char *fmt, ...)
+{
+ va_list ap;
+ fputs("np-native: warning: ", stderr);
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fputc('\n', stderr);
+}
+
+static char *xstrdup(const char *s)
+{
+ char *d = strdup(s);
+ if (!d)
+ die("out of memory");
+ return d;
+}
+
+static char *join3(const char *a, const char *b, const char *c)
+{
+ size_t n = strlen(a) + strlen(b) + strlen(c) + 1;
+ char *d = malloc(n);
+ if (!d)
+ die("out of memory");
+ snprintf(d, n, "%s%s%s", a, b, c);
+ return d;
+}
+
+/* NAME as [A-Z_][A-Z0-9_]* */
+static int valid_name(const char *s, size_t len)
+{
+ if (len == 0 || !(isupper((unsigned char)s[0]) || s[0] == '_'))
+ return 0;
+ for (size_t i = 1; i < len; i++)
+ if (!(isupper((unsigned char)s[i]) || isdigit((unsigned char)s[i]) || s[i] == '_'))
+ return 0;
+ return 1;
+}
+
+static const char *home_dir(void)
+{
+ const char *h = getenv("HOME");
+ if (h && h[0] == '/')
+ return h;
+ struct passwd *pw = getpwuid(getuid());
+ if (pw && pw->pw_dir && pw->pw_dir[0] == '/')
+ return pw->pw_dir;
+ warn("cannot determine the home directory; skipping conf files and shims");
+ return NULL;
+}
+
+/* Expands a leading "~/" and every "$HOME" / "${HOME}" in a conf value. */
+static char *expand_home(const char *v, const char *home)
+{
+ size_t cap = strlen(v) * (strlen(home) + 1) + 2, o = 0;
+ char *d = malloc(cap);
+ if (!d)
+ die("out of memory");
+ if (v[0] == '~' && (v[1] == '/' || v[1] == '\0')) {
+ o += (size_t)snprintf(d, cap, "%s", home);
+ v++;
+ }
+ while (*v) {
+ size_t skip = 0;
+ if (strncmp(v, "${HOME}", 7) == 0)
+ skip = 7;
+ else if (strncmp(v, "$HOME", 5) == 0 &&
+ !(isalnum((unsigned char)v[5]) || v[5] == '_'))
+ skip = 5;
+ if (skip) {
+ o += (size_t)snprintf(d + o, cap - o, "%s", home);
+ v += skip;
+ } else {
+ d[o++] = *v++;
+ }
+ }
+ d[o] = '\0';
+ return d;
+}
+
+/* One override layer: parallel name/value arrays. */
+struct layer {
+ const char *src;
+ char *names[256];
+ char *values[256];
+ int n;
+};
+
+static void layer_put(struct layer *l, const char *name, size_t nlen, const char *value)
+{
+ for (int i = 0; i < l->n; i++)
+ if (strlen(l->names[i]) == nlen && strncmp(l->names[i], name, nlen) == 0) {
+ free(l->values[i]);
+ l->values[i] = xstrdup(value);
+ return;
+ }
+ if (l->n >= 256) {
+ if (strcmp(l->src, "launch options") == 0)
+ die("%s: too many variables", l->src);
+ warn("%s: too many variables, ignoring the rest", l->src);
+ return;
+ }
+ l->names[l->n] = strndup(name, nlen);
+ l->values[l->n] = xstrdup(value);
+ if (!l->names[l->n] || !l->values[l->n])
+ die("out of memory");
+ l->n++;
+}
+
+static const char *layer_get(const struct layer *l, const char *name)
+{
+ for (int i = 0; i < l->n; i++)
+ if (strcmp(l->names[i], name) == 0)
+ return l->values[i];
+ return NULL;
+}
+
+static char *trim(char *s)
+{
+ while (isspace((unsigned char)*s))
+ s++;
+ char *e = s + strlen(s);
+ while (e > s && isspace((unsigned char)e[-1]))
+ *--e = '\0';
+ return s;
+}
+
+/* Missing file is fine; unreadable files and malformed lines are warned about
+ * and skipped. */
+static void load_conf(struct layer *l, const char *path, const char *home)
+{
+ l->src = path;
+ FILE *f = fopen(path, "r");
+ if (!f) {
+ if (errno != ENOENT && errno != ENOTDIR)
+ warn("cannot read %s: %s; skipped", path, strerror(errno));
+ return;
+ }
+ char *line = NULL;
+ size_t cap = 0;
+ int lineno = 0;
+ while (getline(&line, &cap, f) >= 0) {
+ lineno++;
+ char *s = trim(line);
+ if (*s == '\0' || *s == '#')
+ continue;
+ if (strncmp(s, "export ", 7) == 0)
+ s = trim(s + 7);
+ char *eq = strchr(s, '=');
+ if (!eq) {
+ warn("%s:%d: expected KEY=VALUE, got \"%s\"; line skipped", path, lineno, s);
+ continue;
+ }
+ *eq = '\0';
+ char *name = trim(s), *val = trim(eq + 1);
+ if (!valid_name(name, strlen(name))) {
+ warn("%s:%d: invalid variable name \"%s\"; line skipped", path, lineno, name);
+ continue;
+ }
+ size_t vl = strlen(val);
+ if (vl >= 2 && (val[0] == '"' || val[0] == '\'') && val[vl - 1] == val[0]) {
+ val[vl - 1] = '\0';
+ val++;
+ }
+ char *ex = expand_home(val, home);
+ layer_put(l, name, strlen(name), ex);
+ free(ex);
+ }
+ if (ferror(f))
+ warn("error reading %s: %s; using the lines read so far", path, strerror(errno));
+ free(line);
+ fclose(f);
+}
+
+static int is_off(const char *v)
+{
+ return v && (strcmp(v, "0") == 0 || strcasecmp(v, "off") == 0 ||
+ strcasecmp(v, "false") == 0 || strcasecmp(v, "no") == 0);
+}
+
+static int file_exists(const char *p)
+{
+ struct stat st;
+ return stat(p, &st) == 0 && S_ISREG(st.st_mode);
+}
+
+struct libs {
+ char *v[MAX_LIBS];
+ int n;
+};
+
+static void libs_add(struct libs *L, const char *p)
+{
+ if (!p || !*p)
+ return;
+ for (int i = 0; i < L->n; i++)
+ if (strcmp(L->v[i], p) == 0)
+ return;
+ if (!file_exists(p)) {
+ warn("%s does not exist; left out of DYLD_INSERT_LIBRARIES", p);
+ return;
+ }
+ if (L->n >= MAX_LIBS) {
+ warn("too many DYLD_INSERT_LIBRARIES entries; dropping %s", p);
+ return;
+ }
+ L->v[L->n++] = xstrdup(p);
+}
+
+static void libs_add_list(struct libs *L, const char *list)
+{
+ if (!list)
+ return;
+ char *copy = xstrdup(list), *save = NULL;
+ for (char *t = strtok_r(copy, ":", &save); t; t = strtok_r(NULL, ":", &save))
+ libs_add(L, t);
+ free(copy);
+}
+
+static char *libs_join(const struct libs *L)
+{
+ size_t n = 1;
+ for (int i = 0; i < L->n; i++)
+ n += strlen(L->v[i]) + 1;
+ char *d = calloc(1, n);
+ if (!d)
+ die("out of memory");
+ for (int i = 0; i < L->n; i++) {
+ if (i)
+ strcat(d, ":");
+ strcat(d, L->v[i]);
+ }
+ return d;
+}
+
+static int valid_appid(const char *s)
+{
+ if (!s || !*s || strlen(s) > 20)
+ return 0;
+ for (; *s; s++)
+ if (!isdigit((unsigned char)*s))
+ return 0;
+ return 1;
+}
+
+static void xsetenv(const char *name, const char *value)
+{
+ if (setenv(name, value, 1) != 0)
+ die("setenv %s: %s", name, strerror(errno));
+}
+
+int main(int argc, char **argv)
+{
+ const char *home = home_dir();
+ static struct layer args_l = {.src = "launch options"};
+ static struct layer app_l, def_l;
+
+ /* 1. leading VAR=VALUE assignments, then the program */
+ int i = 1;
+ for (; i < argc; i++) {
+ const char *a = argv[i];
+ if (strcmp(a, "--") == 0) {
+ i++;
+ break;
+ }
+ const char *eq = strchr(a, '=');
+ if (!eq)
+ break;
+ size_t nlen = (size_t)(eq - a);
+ if (memchr(a, '/', nlen))
+ break; /* a path that happens to contain '=' */
+ if (!valid_name(a, nlen))
+ die("invalid variable name in \"%s\" (want [A-Z_][A-Z0-9_]*=VALUE)", a);
+ layer_put(&args_l, a, nlen, eq + 1);
+ }
+ if (i >= argc || argv[i][0] == '\0')
+ die("no program to run; usage: np-native [VAR=VALUE ...] %%command%% [args]");
+ char *const *prog_argv = &argv[i];
+ const char *prog = argv[i];
+
+ /* Steam's own injection, captured before any override touches it */
+ const char *steam_dyld = getenv("DYLD_INSERT_LIBRARIES");
+ const char *steam_dyld2 = getenv("STEAM_DYLD_INSERT_LIBRARIES");
+ char *steam_dyld_c = steam_dyld ? xstrdup(steam_dyld) : NULL;
+ char *steam_dyld2_c = steam_dyld2 ? xstrdup(steam_dyld2) : NULL;
+
+ /* 2. conf files */
+ const char *appid = getenv("SteamAppId");
+ if (!valid_appid(appid))
+ appid = getenv("SteamGameId");
+ if (home) {
+ char *conf_dir = join3(home, CONF_DIR_REL, "");
+ char *def_path = join3(conf_dir, "/native-default.conf", "");
+ load_conf(&def_l, def_path, home);
+ if (valid_appid(appid)) {
+ char *app_path = join3(conf_dir, "/native/", appid);
+ char *app_conf = join3(app_path, ".conf", "");
+ load_conf(&app_l, app_conf, home);
+ }
+ }
+
+ /* user-supplied DYLD_INSERT_LIBRARIES (highest layer that sets one) */
+ const char *user_dyld = layer_get(&args_l, "DYLD_INSERT_LIBRARIES");
+ if (!user_dyld)
+ user_dyld = layer_get(&app_l, "DYLD_INSERT_LIBRARIES");
+ if (!user_dyld)
+ user_dyld = layer_get(&def_l, "DYLD_INSERT_LIBRARIES");
+ char *user_dyld_c = user_dyld ? xstrdup(user_dyld) : NULL;
+
+ /* apply lowest precedence first so higher layers win */
+ struct layer *order[] = {&def_l, &app_l, &args_l};
+ for (int k = 0; k < 3; k++)
+ for (int j = 0; j < order[k]->n; j++)
+ xsetenv(order[k]->names[j], order[k]->values[j]);
+
+ /* 3. compose DYLD_INSERT_LIBRARIES */
+ struct libs L = {.n = 0};
+ const char *pad_mode = getenv("NP_PAD_MODE");
+ if (home && !is_off(pad_mode)) {
+ char *pad_shim = join3(home, PAD_SHIM_REL, "");
+ /* no NP_PAD_MODE and no shim installed: nothing was asked for */
+ if (file_exists(pad_shim) || (pad_mode && *pad_mode))
+ libs_add(&L, pad_shim); /* warns and skips when missing */
+ }
+ const char *framegen = getenv("NOTPROTON_FRAMEGEN");
+ if (home && framegen && *framegen && !is_off(framegen))
+ libs_add(&L, join3(home, OVERLAY_SHIM_REL, ""));
+ libs_add_list(&L, user_dyld_c);
+ libs_add_list(&L, steam_dyld_c);
+ libs_add_list(&L, steam_dyld2_c);
+ char *dyld = libs_join(&L);
+ if (L.n) {
+ xsetenv("DYLD_INSERT_LIBRARIES", dyld);
+ xsetenv("STEAM_DYLD_INSERT_LIBRARIES", dyld);
+ } else {
+ unsetenv("DYLD_INSERT_LIBRARIES");
+ }
+
+ const char *log = getenv("NP_NATIVE_LOG");
+ int logging = log && *log && !is_off(log);
+ if (logging) {
+ fprintf(stderr, "np-native: appid=%s\n", valid_appid(appid) ? appid : "(none)");
+ fprintf(stderr, "np-native: DYLD_INSERT_LIBRARIES=%s\n", L.n ? dyld : "(unset)");
+#if defined(__arm64__)
+ const char *self_arch = "arm64";
+#else
+ const char *self_arch = "x86_64";
+#endif
+ fprintf(stderr, "np-native: launcher arch %s; arch preference: arm64, x86_64\n", self_arch);
+ fprintf(stderr, "np-native: program: %s\n", prog);
+ }
+
+ /* 4. replace ourselves with the program, arm64 preferred */
+ posix_spawnattr_t attr;
+ int rc = posix_spawnattr_init(&attr);
+ if (rc)
+ die("posix_spawnattr_init: %s", strerror(rc));
+ cpu_type_t pref[2] = {CPU_TYPE_ARM64, CPU_TYPE_X86_64};
+ size_t ocount = 0;
+ rc = posix_spawnattr_setbinpref_np(&attr, 2, pref, &ocount);
+ if (rc || ocount != 2)
+ die("posix_spawnattr_setbinpref_np failed: %s", strerror(rc ? rc : EINVAL));
+ rc = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETEXEC);
+ if (rc)
+ die("posix_spawnattr_setflags: %s", strerror(rc));
+
+ fflush(NULL);
+ pid_t pid;
+ if (strchr(prog, '/'))
+ rc = posix_spawn(&pid, prog, NULL, &attr, prog_argv, environ);
+ else
+ rc = posix_spawnp(&pid, prog, NULL, &attr, prog_argv, environ);
+ /* only reached on failure */
+ die("cannot exec %s: %s", prog, strerror(rc));
+}
diff --git a/native-launch/tests/marker.c b/native-launch/tests/marker.c
new file mode 100644
index 0000000..6958b0c
--- /dev/null
+++ b/native-launch/tests/marker.c
@@ -0,0 +1,11 @@
+/* Tiny injectable dylib: reports that dyld loaded it. */
+#include <stdio.h>
+
+#ifndef MARKER
+#define MARKER "marker"
+#endif
+
+__attribute__((constructor)) static void np_marker_loaded(void)
+{
+ fprintf(stderr, "loaded:%s\n", MARKER);
+}
diff --git a/native-launch/tests/probe.c b/native-launch/tests/probe.c
new file mode 100644
index 0000000..3d4877b
--- /dev/null
+++ b/native-launch/tests/probe.c
@@ -0,0 +1,28 @@
+/* Test program: prints its running arch, pid, argv and the env vars named by
+ * NP_PROBE_VARS (colon separated). */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+int main(int argc, char **argv)
+{
+#if defined(__arm64__)
+ printf("arch=arm64\n");
+#else
+ printf("arch=x86_64\n");
+#endif
+ printf("pid=%d\n", (int)getpid());
+ for (int i = 1; i < argc; i++)
+ printf("arg%d=%s\n", i, argv[i]);
+ const char *vars = getenv("NP_PROBE_VARS");
+ if (vars) {
+ char *copy = strdup(vars), *save = NULL;
+ for (char *t = strtok_r(copy, ":", &save); t; t = strtok_r(NULL, ":", &save)) {
+ const char *v = getenv(t);
+ printf("%s=%s\n", t, v ? v : "(unset)");
+ }
+ free(copy);
+ }
+ return 0;
+}
diff --git a/native-launch/tests/run.sh b/native-launch/tests/run.sh
new file mode 100644
index 0000000..9147b53
--- /dev/null
+++ b/native-launch/tests/run.sh
@@ -0,0 +1,228 @@
+#!/bin/sh
+# Tests for native-launch/np-native.c.
+#
+# sh native-launch/tests/run.sh [path/to/np-native]
+#
+# Without an argument the launcher is built into the temp dir. The probe
+# program, the x86_64-only probe and the marker dylibs are always built here.
+set -u
+
+here=$(cd "$(dirname "$0")" && pwd)
+src=$here/..
+tmp=$(mktemp -d "${TMPDIR:-/tmp}/np-native-tests.XXXXXX") || exit 1
+trap 'rm -rf "$tmp"' EXIT INT TERM
+
+CC=${CC:-clang}
+UNI="-arch arm64 -arch x86_64 -mmacosx-version-min=11.0 -O2 -Wall -Wextra -Werror"
+
+fail=0
+pass=0
+ok() { pass=$((pass + 1)); echo " ok $1"; }
+bad() { fail=$((fail + 1)); echo " FAIL $1" >&2; }
+
+# shellcheck disable=SC2086
+build() { "$CC" $UNI "$@" || { echo "==> np-native-tests: build failed: $*" >&2; exit 1; }; }
+
+if [ $# -ge 1 ]; then
+ launcher=$1
+else
+ launcher=$tmp/np-native
+ build "$src/np-native.c" -o "$launcher"
+ codesign -s - -f "$launcher" 2>/dev/null
+fi
+[ -x "$launcher" ] || { echo "==> np-native-tests: no launcher at $launcher" >&2; exit 1; }
+
+probe=$tmp/probe
+build "$here/probe.c" -o "$probe"
+"$CC" -arch x86_64 -mmacosx-version-min=11.0 -O2 "$here/probe.c" -o "$tmp/probe-x86" ||
+ { echo "==> np-native-tests: x86_64 probe build failed" >&2; exit 1; }
+
+# fake HOME with real tiny dylibs where the launcher looks for them
+H=$tmp/home
+mkdir -p "$H/.notproton" "$H/Library/Application Support/notproton/gamefixes/native" "$tmp/libs"
+pad=$H/.notproton/libnp_gamepad.dylib
+ov="$H/Library/Application Support/notproton/overlay-shim.dylib"
+steamlib=$tmp/libs/steamoverlay.dylib
+build -dynamiclib -DMARKER='"pad"' "$here/marker.c" -o "$pad"
+build -dynamiclib -DMARKER='"overlay"' "$here/marker.c" -o "$ov"
+build -dynamiclib -DMARKER='"steam"' "$here/marker.c" -o "$steamlib"
+build -dynamiclib -DMARKER='"user"' "$here/marker.c" -o "$tmp/libs/user.dylib"
+for f in "$launcher" "$probe" "$tmp/probe-x86" "$pad" "$ov" "$steamlib" "$tmp/libs/user.dylib"; do
+ codesign -s - -f "$f" 2>/dev/null
+done
+confdir="$H/Library/Application Support/notproton/gamefixes"
+
+# run: clean env (env -i) with HOME pointing at the fake home; extra
+# NAME=VALUE pairs before "--" go into the parent environment
+run() {
+ envs=""
+ while [ $# -gt 0 ] && [ "$1" != "--" ]; do
+ envs="$envs
+$1"
+ shift
+ done
+ [ $# -gt 0 ] && shift
+ (
+ IFS='
+'
+ # shellcheck disable=SC2086
+ exec env -i HOME="$H" PATH=/usr/bin:/bin $envs "$launcher" "$@"
+ ) >"$tmp/out" 2>"$tmp/err"
+ rc=$?
+}
+
+has() { grep -qxF -- "$1" "$tmp/out" "$tmp/err" 2>/dev/null; }
+expect() { # name, line...
+ name=$1
+ shift
+ for line; do
+ if ! grep -qxF -- "$line" "$tmp/out" && ! grep -qxF -- "$line" "$tmp/err"; then
+ bad "$name: missing \"$line\""
+ sed 's/^/ | /' "$tmp/out" "$tmp/err" >&2
+ return
+ fi
+ done
+ ok "$name"
+}
+expect_rc() { # name, rc
+ if [ "$rc" -eq "$2" ]; then ok "$1"; else
+ bad "$1: exit $rc, want $2"
+ sed 's/^/ | /' "$tmp/out" "$tmp/err" >&2
+ fi
+}
+
+echo "==> np-native-tests"
+
+# --- VAR=VALUE parsing ---------------------------------------------------
+mv "$pad" "$pad.off"
+run NP_PROBE_VARS=FOO:BAZ:EMPTY -- FOO=bar BAZ="a b=c" EMPTY= "$probe" -novid "x y"
+expect_rc "assignments: exit 0" 0
+expect "assignments: values and game args" "FOO=bar" "BAZ=a b=c" "EMPTY=" "arg1=-novid" "arg2=x y"
+run NP_PROBE_VARS=FOO -- FOO=1 -- "$probe" BAR=2
+expect "assignments: -- ends assignments, later VAR=x stays an arg" "FOO=1" "arg1=BAR=2"
+mv "$pad.off" "$pad"
+
+# --- conf precedence -------------------------------------------------------
+cat >"$confdir/native-default.conf" <<'EOF'
+# defaults
+A=def
+B=def
+C=def
+P="$HOME/x"
+EOF
+cat >"$confdir/native/4242.conf" <<'EOF'
+B=app
+ C = app
+EOF
+run SteamAppId=4242 NP_PAD_MODE=off A=env D=env NP_PROBE_VARS=A:B:C:D:P -- C=arg "$probe"
+expect_rc "conf: exit 0" 0
+expect "conf: args > per-app > default > env" "A=def" "B=app" "C=arg" "D=env" "P=$H/x"
+run SteamGameId=4242 NP_PAD_MODE=off NP_PROBE_VARS=B -- "$probe"
+expect "conf: SteamGameId fallback" "B=app"
+run SteamAppId=9999 NP_PAD_MODE=off NP_PROBE_VARS=B -- "$probe"
+expect "conf: other appid only gets default" "B=def"
+run SteamAppId=../4242 NP_PAD_MODE=off NP_PROBE_VARS=B -- "$probe"
+expect "conf: non-numeric appid ignored" "B=def"
+rm -f "$confdir/native-default.conf" "$confdir/native/4242.conf"
+
+# --- DYLD composition ------------------------------------------------------
+V=NP_PROBE_VARS=DYLD_INSERT_LIBRARIES:STEAM_DYLD_INSERT_LIBRARIES
+run "$V" "DYLD_INSERT_LIBRARIES=$steamlib" -- NP_PAD_MODE=hid NOTPROTON_FRAMEGEN=1 "$probe"
+expect_rc "dyld: exit 0" 0
+expect "dyld: ours first, Steam's kept, all loaded" \
+ "DYLD_INSERT_LIBRARIES=$pad:$ov:$steamlib" \
+ "STEAM_DYLD_INSERT_LIBRARIES=$pad:$ov:$steamlib" \
+ "loaded:pad" "loaded:overlay" "loaded:steam"
+run "$V" "DYLD_INSERT_LIBRARIES=$pad:$steamlib" "STEAM_DYLD_INSERT_LIBRARIES=$steamlib" -- "$probe"
+expect "dyld: de-duplicated, pad by default when shim exists" \
+ "DYLD_INSERT_LIBRARIES=$pad:$steamlib"
+run "$V" "STEAM_DYLD_INSERT_LIBRARIES=$steamlib" -- NP_PAD_MODE=off NOTPROTON_FRAMEGEN=0 "$probe"
+expect "dyld: pad off, framegen 0, STEAM_DYLD_ only (SIP-stripped parent)" \
+ "DYLD_INSERT_LIBRARIES=$steamlib" "loaded:steam"
+if has "loaded:pad" || has "loaded:overlay"; then bad "dyld: off shims still loaded"; else ok "dyld: off shims not loaded"; fi
+run "$V" "DYLD_INSERT_LIBRARIES=$steamlib" -- DYLD_INSERT_LIBRARIES="$tmp/libs/user.dylib" NP_PAD_MODE=gc "$probe"
+expect "dyld: user list between ours and Steam's" \
+ "DYLD_INSERT_LIBRARIES=$pad:$tmp/libs/user.dylib:$steamlib" "loaded:user"
+run "$V" -- NP_PAD_MODE=off "$probe"
+expect "dyld: nothing to inject leaves it unset" "DYLD_INSERT_LIBRARIES=(unset)"
+
+# shell-script games (dota.sh): SIP strips DYLD_* in /bin/sh, the script
+# restores it from STEAM_DYLD_INSERT_LIBRARIES
+cat >"$tmp/game.sh" <<'EOF'
+#!/bin/sh
+echo "script DYLD=${DYLD_INSERT_LIBRARIES:-}"
+echo "script STEAM_DYLD=${STEAM_DYLD_INSERT_LIBRARIES:-}"
+EOF
+chmod +x "$tmp/game.sh"
+run "DYLD_INSERT_LIBRARIES=$steamlib" -- NP_PAD_MODE=hid "$tmp/game.sh"
+expect_rc "script: exit 0" 0
+expect "script: STEAM_DYLD_ carries the composed list" "script STEAM_DYLD=$pad:$steamlib"
+
+# --- architecture ----------------------------------------------------------
+(exec env -i HOME="$H" PATH=/usr/bin:/bin NP_NATIVE_LOG=1 NP_PAD_MODE=hid \
+ "DYLD_INSERT_LIBRARIES=$steamlib" \
+ /usr/bin/arch -x86_64 "$launcher" "$probe") >"$tmp/out" 2>"$tmp/err"
+rc=$?
+expect_rc "arch: exit 0 from x86_64 parent" 0
+expect "arch: launcher ran x86_64, game runs arm64" \
+ "np-native: launcher arch x86_64; arch preference: arm64, x86_64" "arch=arm64" \
+ "loaded:pad"
+run NP_PAD_MODE=off -- "$tmp/probe-x86"
+expect_rc "arch: x86_64-only program exit 0" 0
+expect "arch: x86_64-only program runs" "arch=x86_64"
+run NP_PAD_MODE=hid -- "$tmp/probe-x86"
+expect "arch: x86_64-only program gets universal shim" "arch=x86_64" "loaded:pad"
+
+# --- pid is kept (POSIX_SPAWN_SETEXEC) --------------------------------------
+(exec env -i HOME="$H" PATH=/usr/bin:/bin NP_PAD_MODE=off \
+ "$launcher" /bin/sh -c 'echo "shpid=$$"') >"$tmp/out" 2>"$tmp/err" &
+bg=$!
+wait "$bg"
+expect "pid: program replaces the launcher" "shpid=$bg"
+
+# --- errors -> 127 ---------------------------------------------------------
+run -- FOO=1
+expect_rc "error: no program" 127
+run -- lower=1 "$probe"
+expect_rc "error: invalid variable name" 127
+run -- "$tmp/does-not-exist"
+expect_rc "error: missing program" 127
+run -- "$tmp"
+expect_rc "error: program is a directory" 127
+# --- fail open: problems outside the command line warn and still launch -----
+V=NP_PROBE_VARS=DYLD_INSERT_LIBRARIES:STEAM_DYLD_INSERT_LIBRARIES
+mv "$pad" "$pad.off"
+run "$V" -- NP_PAD_MODE=hid "$probe"
+expect_rc "fail open: NP_PAD_MODE set, shim missing: exit 0" 0
+expect "fail open: missing pad shim warned and left out" \
+ "np-native: warning: $pad does not exist; left out of DYLD_INSERT_LIBRARIES" \
+ "arch=arm64" "DYLD_INSERT_LIBRARIES=(unset)"
+run NP_PROBE_VARS=X -- X=1 "$probe"
+expect_rc "no shim, NP_PAD_MODE unset: exit 0" 0
+if grep -q warning "$tmp/err"; then bad "no shim, NP_PAD_MODE unset: unexpected warning"; else ok "no shim, NP_PAD_MODE unset: silent"; fi
+mv "$pad.off" "$pad"
+mv "$ov" "$ov.off"
+run "$V" -- NP_PAD_MODE=off NOTPROTON_FRAMEGEN=1 "$probe"
+expect_rc "fail open: framegen requested, overlay shim missing: exit 0" 0
+expect "fail open: missing overlay shim warned and left out" \
+ "np-native: warning: $ov does not exist; left out of DYLD_INSERT_LIBRARIES" \
+ "DYLD_INSERT_LIBRARIES=(unset)"
+mv "$ov.off" "$ov"
+# (dyld reads DYLD_INSERT_LIBRARIES for the launcher itself, so the dead path
+# arrives through STEAM_DYLD_INSERT_LIBRARIES, which only np-native reads)
+run "$V" "DYLD_INSERT_LIBRARIES=$steamlib" "STEAM_DYLD_INSERT_LIBRARIES=$tmp/libs/gone.dylib:$steamlib" -- NP_PAD_MODE=hid "$probe"
+expect_rc "fail open: nonexistent Steam library: exit 0" 0
+expect "fail open: nonexistent Steam library dropped" \
+ "np-native: warning: $tmp/libs/gone.dylib does not exist; left out of DYLD_INSERT_LIBRARIES" \
+ "DYLD_INSERT_LIBRARIES=$pad:$steamlib" "loaded:pad" "loaded:steam"
+printf 'GOOD=1\nthis line is junk\nbad-name=2\nLATER=3\n' >"$confdir/native-default.conf"
+run NP_PROBE_VARS=GOOD:LATER -- NP_PAD_MODE=off "$probe"
+expect_rc "fail open: malformed conf: exit 0" 0
+expect "fail open: bad conf lines warned (file:line), good lines applied" \
+ "np-native: warning: $confdir/native-default.conf:2: expected KEY=VALUE, got \"this line is junk\"; line skipped" \
+ "np-native: warning: $confdir/native-default.conf:3: invalid variable name \"bad-name\"; line skipped" \
+ "GOOD=1" "LATER=3" "arch=arm64"
+rm -f "$confdir/native-default.conf"
+
+echo "==> np-native-tests: $pass passed, $fail failed"
+[ "$fail" -eq 0 ]
diff --git a/scripts/build-local.sh b/scripts/build-local.sh
index 91d0ccd..f0820dc 100755
--- a/scripts/build-local.sh
+++ b/scripts/build-local.sh
@@ -228,7 +228,7 @@ if [ "$run_checks" -eq 1 ]; then
start=$(date +%s)
for target in sigcheck callscheck webpatch-fixtures peicon-fixtures panel-behavior \
spawn-env compatcheck compatsvc-check launch-shell envcheck buildcheck \
- settingscheck routecheck bridgecheck gamedrivecheck seedcheck padcheck app-tests; do
+ settingscheck routecheck bridgecheck gamedrivecheck seedcheck padcheck np-native-tests app-tests; do
echo "==> [check] make -s $target" | tee -a "$check_log"
[ "$target" != app-tests ] || link_test_sparkle >>"$check_log" 2>&1 || true
if make -s "$target" >>"$check_log" 2>&1; then