Skip to content

Commit bd94bcd

Browse files
committed
Restore thread-unsafe fallback for setting the Process working directory
Swift still needs to support Amazon Linux 2 until it EoLs in mid-2025. So restore the thread-unsafe fallback for systems with glibc older than version 2.29, which was removed in #4981.
1 parent 465203c commit bd94bcd

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

Sources/Foundation/Process.swift

+26-1
Original file line numberDiff line numberDiff line change
@@ -925,8 +925,15 @@ open class Process: NSObject, @unchecked Sendable {
925925
for fd in addclose.filter({ $0 >= 0 }) {
926926
try _throwIfPosixError(_CFPosixSpawnFileActionsAddClose(fileActions, fd))
927927
}
928+
let useFallbackChdir: Bool
928929
if let dir = currentDirectoryURL?.path {
929-
try _throwIfPosixError(_CFPosixSpawnFileActionsChdir(fileActions, dir))
930+
let chdirResult = _CFPosixSpawnFileActionsChdir(fileActions, dir)
931+
useFallbackChdir = chdirResult == ENOSYS
932+
if !useFallbackChdir {
933+
try _throwIfPosixError(chdirResult)
934+
}
935+
} else {
936+
useFallbackChdir = false
930937
}
931938

932939
#if canImport(Darwin) || os(Android) || os(OpenBSD)
@@ -950,6 +957,24 @@ open class Process: NSObject, @unchecked Sendable {
950957
}
951958
#endif
952959

960+
// Unsafe fallback for systems missing posix_spawn_file_actions_addchdir[_np]
961+
// This includes Glibc versions older than 2.29 such as on Amazon Linux 2
962+
if useFallbackChdir {
963+
let fileManager = FileManager()
964+
let previousDirectoryPath = fileManager.currentDirectoryPath
965+
if let dir = currentDirectoryURL?.path, !fileManager.changeCurrentDirectoryPath(dir) {
966+
throw _NSErrorWithErrno(errno, reading: true, url: currentDirectoryURL)
967+
}
968+
}
969+
970+
defer {
971+
if useFallbackChdir {
972+
// Reset the previous working directory path.
973+
let fileManager = FileManager()
974+
_ = fileManager.changeCurrentDirectoryPath(previousDirectoryPath)
975+
}
976+
}
977+
953978
// Launch
954979
var pid = pid_t()
955980

0 commit comments

Comments
 (0)