Skip to content

Commit 4dcbb8b

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 4615aa0 commit 4dcbb8b

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

Sources/Foundation/Process.swift

+29-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,27 @@ 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+
let previousDirectoryPath: String?
963+
if useFallbackChdir {
964+
let fileManager = FileManager()
965+
previousDirectoryPath = fileManager.currentDirectoryPath
966+
if let dir = currentDirectoryURL?.path, !fileManager.changeCurrentDirectoryPath(dir) {
967+
throw _NSErrorWithErrno(errno, reading: true, url: currentDirectoryURL)
968+
}
969+
} else {
970+
previousDirectoryPath = nil
971+
}
972+
973+
defer {
974+
if let previousDirectoryPath {
975+
// Reset the previous working directory path.
976+
let fileManager = FileManager()
977+
_ = fileManager.changeCurrentDirectoryPath(previousDirectoryPath)
978+
}
979+
}
980+
953981
// Launch
954982
var pid = pid_t()
955983

0 commit comments

Comments
 (0)