Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

The bundled Python leads the PATH only when it is the chosen interpreter, and runs without the user site

v0lumehif09f2b3754c8
diff --git a/frontend/Sources/NSPortBuilder/BundledTools.swift b/frontend/Sources/NSPortBuilder/BundledTools.swift
index b7a41aaf..c6fdf72f 100644
--- a/frontend/Sources/NSPortBuilder/BundledTools.swift
+++ b/frontend/Sources/NSPortBuilder/BundledTools.swift
@@ -36,12 +36,20 @@ enum BundledTools {
return url.path
}
- /// A PATH for the processes that run the build: the bundled tools first, then the bundled Python's folder (so that a script that
- /// starts `python3` by name gets this one and not the system's 3.9), then `base`. `base` unchanged when there is no bundle.
- nonisolated static func path(_ base: String, in resources: URL? = resources) -> String {
+ /// Environment variables for a process that runs `python` (empty unless it is the bundled interpreter): no user site, so that
+ /// packages in ~/Library/Python or ~/.local cannot shadow the pinned ones, and no .pyc, which would be written into the signed app.
+ nonisolated static func environment(for python: String, in resources: URL? = resources) -> [String: String] {
+ guard let bundled = Self.python(in: resources), bundled == python else { return [:] }
+ return ["PYTHONNOUSERSITE": "1", "PYTHONDONTWRITEBYTECODE": "1"]
+ }
+
+ /// A PATH for the processes that run the build: the bundled tools first, then the folder of the interpreter the build uses when it
+ /// is the bundled one (so that a script that starts `python3` by name gets this one and not the system's 3.9; a bundled Python that
+ /// was rejected, or a different one chosen, stays off the PATH), then `base`. `base` unchanged when there is no bundle.
+ nonisolated static func path(_ base: String, python: String?, in resources: URL? = resources) -> String {
var dirs: [String] = []
if let bin = binDirectory(in: resources) { dirs.append(bin) }
- if let py = python(in: resources) { dirs.append((py as NSString).deletingLastPathComponent) }
+ if let py = python, py == Self.python(in: resources) { dirs.append((py as NSString).deletingLastPathComponent) }
return (dirs + [base]).joined(separator: ":")
}
}
diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift
index 8396f132..59dd54cd 100644
--- a/frontend/Sources/NSPortBuilder/ContentView.swift
+++ b/frontend/Sources/NSPortBuilder/ContentView.swift
@@ -366,8 +366,8 @@ final class BuildModel: ObservableObject {
/// The PATH of the processes that run the build, installing packages and writing the RomFS image: the bundled tools in front of
/// `base` (BundledTools.swift), which is Homebrew's folders and the system's. One place, so that no environment forgets the bundle.
- nonisolated static func toolPath(_ base: String = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin") -> String {
- BundledTools.path(base)
+ nonisolated static func toolPath(_ base: String = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin", python: String? = nil) -> String {
+ BundledTools.path(base, python: python)
}
/// Run a command with all output captured (no streaming; fetch / rev-list / pull print little).
@@ -1106,8 +1106,8 @@ final class BuildModel: ObservableObject {
if compressed, !Self.runOK(py, ["-c", "import nsz"]) {
say(t("msg.installingNsz"))
let r = Self.runCaptured([py, "-m", "pip", "install", "nsz"],
- env: ["PATH": Self.toolPath(),
- "HOME": NSHomeDirectory()]) { line in
+ env: ["PATH": Self.toolPath(python: py),
+ "HOME": NSHomeDirectory()].merging(BundledTools.environment(for: py)) { $1 }) { line in
DispatchQueue.main.async { self.append(line + "\n") }
}
if !r {
@@ -1162,7 +1162,7 @@ final class BuildModel: ObservableObject {
// (NuGet-Migrations) under $TMPDIR/.dotnet/shm, and with no TMPDIR it stats "" and dies with
// 'NuGet-Migrations' + lstat("") == ENOENT before any project is read. NSTemporaryDirectory()
// is the per-user temp folder whether or not the app's own environment carries one.
- var denv: [String: String] = ["PATH": Self.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"),
+ var denv: [String: String] = ["PATH": Self.toolPath("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", python: py),
"USER": NSUserName(), "HOME": NSHomeDirectory(), "LANG": "en_US.UTF-8",
"TMPDIR": NSTemporaryDirectory()]
if let droot = Self.dotnetRoot(for: dotnetPath.isEmpty ? "dotnet" : dotnetPath) {
@@ -1170,8 +1170,8 @@ final class BuildModel: ObservableObject {
denv["DOTNET_ROOT_ARM64"] = droot
}
// The bundled Python lives inside the signed app: a .pyc written there would change what the signature seals
- // (the packages are compiled at bundle time).
- if py == BundledTools.python() { denv["PYTHONDONTWRITEBYTECODE"] = "1" }
+ // (the packages are compiled at bundle time), and a user site must not shadow its pinned packages.
+ denv.merge(BundledTools.environment(for: py)) { $1 }
p.environment = denv
Self.inOwnGroup(p, python: py)
let pipe = Pipe()
@@ -1604,7 +1604,9 @@ final class BuildModel: ObservableObject {
p.executableURL = URL(fileURLWithPath: pythonPath.isEmpty ? "/usr/bin/python3" : pythonPath)
// dest/romfs.img: one file, which main.m's per-game lookup takes before any folder.
p.arguments = [repoPath + "/" + Self.romfsImageTool, "--reuse", romfs, dest + "/romfs.img"]
- p.environment = ["PATH": Self.toolPath("/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin"), "PYTHONPATH": repoPath + "/dm/tools"]
+ let romfsPy = p.executableURL!.path
+ p.environment = ["PATH": Self.toolPath("/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin", python: romfsPy), "PYTHONPATH": repoPath + "/dm/tools"]
+ .merging(BundledTools.environment(for: romfsPy)) { $1 }
Self.inOwnGroup(p, python: p.executableURL!.path)
let pipe = Pipe(); p.standardOutput = pipe; p.standardError = pipe
pipe.fileHandleForReading.readabilityHandler = { [weak self] h in
@@ -1947,7 +1949,9 @@ final class BuildModel: ObservableObject {
nonisolated static func venvPython() -> String { venvDir + "/bin/python3" }
- nonisolated static func importsOK(_ py: String) -> Bool { runOK(py, ["-c", importProbe]) }
+ nonisolated static func importsOK(_ py: String) -> Bool {
+ runOK(py, ["-c", importProbe], env: ProcessInfo.processInfo.environment.merging(BundledTools.environment(for: py)) { $1 })
+ }
/// backports.zstd declares Python < 3.14, so it is only installed where it is needed.
/// nsz is always installed: NSZ / XCZ dumps are accepted by the pipeline now, and a player who
@@ -1966,7 +1970,7 @@ final class BuildModel: ObservableObject {
let p = Process(); p.executableURL = URL(fileURLWithPath: exe); p.arguments = args
let out = Pipe(), err = Pipe()
p.standardOutput = out; p.standardError = err; p.standardInput = FileHandle.nullDevice
- p.environment = ["PATH": toolPath(), "HOME": NSHomeDirectory()]
+ p.environment = ["PATH": toolPath(python: base), "HOME": NSHomeDirectory()].merging(BundledTools.environment(for: base)) { $1 }
do { try p.run() } catch { log += "could not start \(exe): \(error.localizedDescription)\n"; return false }
// both pipes are drained on this thread (before waitUntilExit, so the child cannot
// block on a full pipe), and the log string keeps a single owner
@@ -1994,6 +1998,7 @@ final class BuildModel: ObservableObject {
let p = Process()
p.executableURL = URL(fileURLWithPath: path)
p.arguments = ["-c", "import sys; print('%d.%d' % sys.version_info[:2])"]
+ p.environment = ProcessInfo.processInfo.environment.merging(BundledTools.environment(for: path)) { $1 }
let pipe = Pipe()
p.standardOutput = pipe; p.standardError = Pipe()
p.standardInput = FileHandle.nullDevice
diff --git a/frontend/Tests/NSPortBuilderTests/BundledToolsTests.swift b/frontend/Tests/NSPortBuilderTests/BundledToolsTests.swift
index 0eada97b..4d3a7720 100644
--- a/frontend/Tests/NSPortBuilderTests/BundledToolsTests.swift
+++ b/frontend/Tests/NSPortBuilderTests/BundledToolsTests.swift
@@ -60,20 +60,38 @@ final class BundledToolsTests: XCTestCase {
// ---- PATH ----
func testPathWithoutBundleIsTheBaseUnchanged() {
- XCTAssertEqual(BundledTools.path("/usr/bin:/bin", in: nil), "/usr/bin:/bin")
- XCTAssertEqual(BundledTools.path("/usr/bin:/bin", in: root), "/usr/bin:/bin")
+ XCTAssertEqual(BundledTools.path("/usr/bin:/bin", python: nil, in: nil), "/usr/bin:/bin")
+ XCTAssertEqual(BundledTools.path("/usr/bin:/bin", python: nil, in: root), "/usr/bin:/bin")
}
func testPathPutsTheBundledToolsFirstThenItsPython() throws {
try install("tools/bin/zstd")
- try install("python/bin/python3")
- XCTAssertEqual(BundledTools.path("/opt/homebrew/bin:/usr/bin", in: root),
+ let py = try install("python/bin/python3")
+ XCTAssertEqual(BundledTools.path("/opt/homebrew/bin:/usr/bin", python: py, in: root),
root.path + "/tools/bin:" + root.path + "/python/bin:/opt/homebrew/bin:/usr/bin")
}
+ func testPathKeepsARejectedOrOtherPythonOff() throws {
+ // review of #154: the bundled interpreter that findPython rejected must not lead the PATH, nor must it when another was chosen
+ try install("tools/bin/zstd")
+ try install("python/bin/python3")
+ let expected = root.path + "/tools/bin:/usr/bin"
+ XCTAssertEqual(BundledTools.path("/usr/bin", python: "/opt/homebrew/bin/python3", in: root), expected)
+ XCTAssertEqual(BundledTools.path("/usr/bin", python: nil, in: root), expected)
+ }
+
+ func testOnlyTheBundledPythonGetsTheIsolatedEnvironment() throws {
+ let py = try install("python/bin/python3")
+ let env = BundledTools.environment(for: py, in: root)
+ XCTAssertEqual(env["PYTHONNOUSERSITE"], "1")
+ XCTAssertEqual(env["PYTHONDONTWRITEBYTECODE"], "1")
+ XCTAssertTrue(BundledTools.environment(for: "/opt/homebrew/bin/python3", in: root).isEmpty)
+ XCTAssertTrue(BundledTools.environment(for: py, in: nil).isEmpty)
+ }
+
func testPathWithToolsButNoPython() throws {
try install("tools/bin/zstd")
- XCTAssertEqual(BundledTools.path("/usr/bin", in: root), root.path + "/tools/bin:/usr/bin")
+ XCTAssertEqual(BundledTools.path("/usr/bin", python: nil, in: root), root.path + "/tools/bin:/usr/bin")
}
func testBuildToolPathKeepsTheHomebrewBaseWithoutABundle() {