Skip to content

NSPathUtilities: Replace mktemp(3) with mkstemp(3) #2927

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 3, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 26 additions & 9 deletions Sources/Foundation/NSPathUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -760,17 +760,34 @@ internal func _NSCreateTemporaryFile(_ filePath: String) throws -> (Int32, Strin
// Don't close h, fd is transferred ownership
let fd = _open_osfhandle(intptr_t(bitPattern: h), 0)
#else
let maxLength = Int(PATH_MAX) + 1
var buf = [Int8](repeating: 0, count: maxLength)
let _ = template._nsObject.getFileSystemRepresentation(&buf, maxLength: maxLength)
guard let name = mktemp(&buf) else {
throw _NSErrorWithErrno(errno, reading: false, path: filePath)
var filename = template.utf8CString

let result = filename.withUnsafeMutableBufferPointer { (ptr: inout UnsafeMutableBufferPointer<CChar>) -> (Int32, String)? in
// filename is updated with the temp file name on success.
let fd = mkstemp(ptr.baseAddress!)
if fd == -1 {
return nil
} else {
guard let fname = String(utf8String: ptr.baseAddress!) else {
// Couldnt convert buffer back to filename.
close(fd)
errno = ENOENT
return nil
}
return (fd, fname)
}
}

guard let (fd, pathResult) = result else {
throw _NSErrorWithErrno(errno, reading: false, path: template)
}
let fd = open(name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
if fd == -1 {
throw _NSErrorWithErrno(errno, reading: false, path: filePath)

// Set the file mode to match macOS
guard fchmod(fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) != -1 else {
let _errno = errno
close(fd)
throw _NSErrorWithErrno(_errno, reading: false, path: pathResult)
}
let pathResult = FileManager.default.string(withFileSystemRepresentation: buf, length: Int(strlen(buf)))
#endif
return (fd, pathResult)
}
Expand Down