From 85de4e51e22070056e89dfbc396f23131bb711a5 Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Wed, 20 Mar 2024 17:10:30 +0000 Subject: [PATCH] Use the proper temporary directory on Darwin. It seems we can get the temporary directory from confstr(). rdar://125087707 --- Sources/System/FilePath/FilePathTemp.swift | 26 +++++++++++++++++++ Sources/System/Internals/Syscalls.swift | 12 +++++++++ .../FilePathTests/FilePathTempTest.swift | 9 +++++++ 3 files changed, 47 insertions(+) diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index 9aa65ff..0028671 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -111,7 +111,33 @@ internal func recursiveRemove(at path: FilePath) throws { #else internal func getTemporaryDirectory() throws -> FilePath { + #if SYSTEM_PACKAGE_DARWIN + var capacity = 1024 + while true { + let path: FilePath? = withUnsafeTemporaryAllocation( + of: CInterop.PlatformChar.self, + capacity: 1024) { buffer in + let len = system_confstr(SYSTEM_CS_DARWIN_USER_TEMP_DIR, + buffer.baseAddress!, + buffer.count) + if len == 0 { + // Fall back to "/tmp" if we can't read the temp directory + return "/tmp" + } + // If it was truncated, increase capaciy and try again + if len > buffer.count { + capacity = len + return nil + } + return FilePath(SystemString(platformString: buffer.baseAddress!)) + } + if let path = path { + return path + } + } + #else return "/tmp" + #endif } internal func recursiveRemove(at path: FilePath) throws { diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 4669141..cec8413 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -173,6 +173,18 @@ internal func system_rmdir( return rmdir(path) } +#if SYSTEM_PACKAGE_DARWIN +internal let SYSTEM_CS_DARWIN_USER_TEMP_DIR = _CS_DARWIN_USER_TEMP_DIR + +internal func system_confstr( + _ name: CInt, + _ buf: UnsafeMutablePointer, + _ len: Int +) -> Int { + return confstr(name, buf, len) +} +#endif + #if !os(Windows) internal let SYSTEM_AT_REMOVE_DIR = AT_REMOVEDIR internal let SYSTEM_DT_DIR = DT_DIR diff --git a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift index 0948f78..b2b1fa2 100644 --- a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift @@ -16,6 +16,15 @@ import System #endif final class TemporaryPathTest: XCTestCase { + #if SYSTEM_PACKAGE_DARWIN + func testNotInSlashTmp() throws { + try withTemporaryPath(basename: "NotInSlashTmp") { path in + // We shouldn't be using "/tmp" on Darwin + XCTAssertNotEqual(path.components.first!, "tmp") + } + } + #endif + func testUnique() throws { try withTemporaryPath(basename: "test") { path in let strPath = String(decoding: path)