Skip to content

Commit 8cf5bae

Browse files
committed
Foundation: dynamically allocate temporary path
Query the desired buffer size and allocate an appropriate buffer for the temporary path query. This should prevent a truncated path from being given.
1 parent 9d46a38 commit 8cf5bae

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

Foundation/NSPathUtilities.swift

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,14 @@ import CoreFoundation
1111

1212
public func NSTemporaryDirectory() -> String {
1313
#if os(macOS) || os(iOS)
14-
var buf = [Int8](repeating: 0, count: 100)
15-
let r = confstr(_CS_DARWIN_USER_TEMP_DIR, &buf, buf.count)
16-
if r != 0 && r < buf.count {
17-
return String(cString: buf, encoding: .utf8)!
18-
}
14+
var length: Int = confstr(_CS_DARWIN_USER_TEMP_DIR, nil, 0)
15+
guard length > 0 else { return "/tmp" }
16+
17+
var buffer: [Int8] = Array<Int8>(repeating: 0, count: length)
18+
length = confstr(_CS_DARWIN_USER_TEMP_DIR, &buffer, buffer.count)
19+
precondition(length > 0 && length < buffer.count,
20+
"_CS_DARWIN_USER_TEMP_DIR mutation race")
21+
return String(cString: buffer, encoding: .utf8)!
1922
#elseif os(Windows)
2023
var cchLength: DWORD = GetTempPathW(0, nil)
2124
var wszPath: UnsafeMutableBufferPointer = UnsafeMutableBufferPointer<WCHAR>.allocate(capacity: Int(cchLength + 1))

0 commit comments

Comments
 (0)