mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Use a thread-safe strerror in Errno.description
strerror(3) isn't guaranteed to be thread-safe: for an unknown error number, it may format the message into a static buffer shared by all threads, so concurrent calls to Errno.description could return each other's text. Add a csystem_strerror_r shim to CSystem that writes into a caller-provided buffer. It hides the difference between the XSI strerror_r (Darwin, BSDs, musl, WASI) and the GNU variant that glibc and bionic provide under _GNU_SOURCE, and uses strerror_s on Windows. Errno.description now formats into a stack buffer through this shim. Also add tests for Errno.description, which were a TODO. Fixes #156
This commit is contained in:
1 parent
d1b4ed40f2
commit
013178c00e
6 files changed
+143
-9
No files matched your search
@@ -12,3 +12,17 @@ extern int csystem_posix_pipe2(int fildes[2], int flag);
|
||||
#endif
|
||||
|
||||
extern int csystem_posix_dup3(int fildes, int fildes2, int flag);
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
// Thread-safe replacement for strerror(3).
|
||||
//
|
||||
// Writes the message for `errnum` into `buf`, which holds `buflen` bytes, and
|
||||
// always NUL-terminates it if `buflen` is not zero. Returns 0 on success, or an
|
||||
// error number (e.g. EINVAL for an unknown `errnum`, ERANGE if the message was
|
||||
// truncated). Even on failure, `buf` may contain a message such as
|
||||
// "Unknown error 1234".
|
||||
//
|
||||
// This hides the differences between the XSI and GNU variants of strerror_r,
|
||||
// and uses strerror_s on Windows.
|
||||
extern int csystem_strerror_r(int errnum, char *buf, size_t buflen);
|
||||
@@ -41,6 +41,47 @@ unsigned long long _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; }
|
||||
#endif
|
||||
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <CSystemShared.h>
|
||||
|
||||
extern int csystem_strerror_r(int errnum, char *buf, size_t buflen) {
|
||||
if (buf == NULL || buflen == 0) {
|
||||
return ERANGE;
|
||||
}
|
||||
buf[0] = '\0';
|
||||
#if defined(_WIN32)
|
||||
return strerror_s(buf, buflen, errnum);
|
||||
#elif defined(_GNU_SOURCE) && \
|
||||
(defined(__GLIBC__) || (defined(__ANDROID__) && __ANDROID_API__ >= 23))
|
||||
// With _GNU_SOURCE (defined above on Linux), glibc and bionic provide the
|
||||
// GNU variant, which returns a pointer to the message. That pointer is
|
||||
// either `buf` or an immutable static string, so copying from it is safe.
|
||||
const char *message = strerror_r(errnum, buf, buflen);
|
||||
if (message == NULL) {
|
||||
return EINVAL;
|
||||
}
|
||||
if (message != buf) {
|
||||
size_t length = strlen(message);
|
||||
if (length >= buflen) {
|
||||
memcpy(buf, message, buflen - 1);
|
||||
buf[buflen - 1] = '\0';
|
||||
return ERANGE;
|
||||
}
|
||||
memcpy(buf, message, length + 1);
|
||||
}
|
||||
return 0;
|
||||
#else
|
||||
// XSI variant (Darwin, FreeBSD, OpenBSD, musl, WASI). Some implementations
|
||||
// return -1 and set errno instead of returning the error number.
|
||||
int result = strerror_r(errnum, buf, buflen);
|
||||
if (result == -1) {
|
||||
result = errno;
|
||||
}
|
||||
buf[buflen - 1] = '\0';
|
||||
return result;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !defined(_WIN32) && !defined(__wasi__) && !defined(__APPLE__)
|
||||
#define HAVE_PIPE2_DUP3
|
||||
|
||||
@@ -1547,11 +1547,22 @@ extension Errno: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the most recent error
|
||||
/// returned by a system call.
|
||||
///
|
||||
/// The corresponding C function is `strerror(3)`.
|
||||
/// The corresponding C function is `strerror(3)`. This property uses a
|
||||
/// thread-safe variant of it, so it is safe to use from multiple threads.
|
||||
@inline(never)
|
||||
public var description: String {
|
||||
guard let ptr = system_strerror(self.rawValue) else { return "unknown error" }
|
||||
return String(cString: ptr)
|
||||
// Error messages are short, so 256 bytes is plenty. If one is longer,
|
||||
// csystem_strerror_r truncates it.
|
||||
withUnsafeTemporaryAllocation(of: CChar.self, capacity: 256) { buffer in
|
||||
let base = buffer.baseAddress!
|
||||
base.initialize(to: 0)
|
||||
// Even when strerror_r fails, e.g. with EINVAL for an unknown error
|
||||
// number, most C libraries still write a message like
|
||||
// "Unknown error 1234", so use whatever was written.
|
||||
_ = system_strerror_r(self.rawValue, base, buffer.count)
|
||||
guard base.pointee != 0 else { return "unknown error" }
|
||||
return String(cString: base)
|
||||
}
|
||||
}
|
||||
|
||||
/// A textual representation,
|
||||
|
||||
@@ -77,10 +77,6 @@ internal var system_errno: CInt {
|
||||
|
||||
// Convention: `system_foo` is system's wrapper for `foo`.
|
||||
|
||||
internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>! {
|
||||
strerror(__errnum)
|
||||
}
|
||||
|
||||
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
@@ -27,6 +27,16 @@ import Android
|
||||
// Interacting with the mocking system, tracing, etc., is a potentially significant
|
||||
// amount of code size, so we hand outline that code for every syscall
|
||||
|
||||
// strerror(3) isn't guaranteed to be thread-safe: for an unknown error number,
|
||||
// it may format the message into a buffer shared by all threads. This wrapper
|
||||
// uses a caller-provided buffer instead (strerror_r(3), or strerror_s on
|
||||
// Windows). It isn't a syscall, so it isn't mocked.
|
||||
internal func system_strerror_r(
|
||||
_ errnum: CInt, _ buffer: UnsafeMutablePointer<CChar>, _ length: Int
|
||||
) -> CInt {
|
||||
csystem_strerror_r(errnum, buffer, length)
|
||||
}
|
||||
|
||||
// open
|
||||
internal func system_open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2025 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2026 Apple Inc. and the Swift System project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
@@ -19,6 +19,14 @@ import System
|
||||
import WinSDK
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE && canImport(CSystem)
|
||||
import CSystem // for csystem_strerror_r
|
||||
#endif
|
||||
|
||||
#if canImport(Dispatch)
|
||||
import Dispatch
|
||||
#endif
|
||||
|
||||
@available(System 0.0.1, *)
|
||||
final class ErrnoTest: XCTestCase {
|
||||
func testConstants() {
|
||||
@@ -235,5 +243,59 @@ final class ErrnoTest: XCTestCase {
|
||||
|
||||
// TODO: `_code/_domain` for NSError bridging
|
||||
|
||||
// TODO: `description`
|
||||
func testDescription() {
|
||||
XCTAssertEqual(Errno.noSuchFileOrDirectory.description, "No such file or directory")
|
||||
XCTAssertEqual(Errno.notPermitted.debugDescription, Errno.notPermitted.description)
|
||||
|
||||
// Unknown error numbers still get a message.
|
||||
let unknown = Errno(rawValue: 98765).description
|
||||
XCTAssertFalse(unknown.isEmpty)
|
||||
#if !os(Windows) && !os(WASI)
|
||||
// Windows' message is just "Unknown error", without the number.
|
||||
XCTAssert(unknown.contains("98765"), unknown)
|
||||
#endif
|
||||
}
|
||||
|
||||
#if canImport(Dispatch)
|
||||
func testDescriptionIsThreadSafe() {
|
||||
// For unknown error numbers, strerror(3) may format the message into a
|
||||
// buffer shared by all threads, so concurrent calls could see each
|
||||
// other's messages.
|
||||
let errnos = (0..<64).map { Errno(rawValue: 90000 + CInt($0)) }
|
||||
let expected = errnos.map(\.description)
|
||||
let iterations = 200
|
||||
nonisolated(unsafe) let mismatches =
|
||||
UnsafeMutableBufferPointer<Int>.allocate(capacity: errnos.count)
|
||||
mismatches.initialize(repeating: 0)
|
||||
defer { mismatches.deallocate() }
|
||||
|
||||
DispatchQueue.concurrentPerform(iterations: errnos.count) { index in
|
||||
for _ in 0..<iterations where errnos[index].description != expected[index] {
|
||||
mismatches[index] += 1
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(mismatches.reduce(0, +), 0)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if SYSTEM_PACKAGE && canImport(CSystem)
|
||||
func testStrerrorShim() {
|
||||
var buffer = [CChar](repeating: 1, count: 256)
|
||||
XCTAssertEqual(csystem_strerror_r(ENOENT, &buffer, buffer.count), 0)
|
||||
XCTAssertEqual(String(cString: buffer), "No such file or directory")
|
||||
|
||||
// A buffer that is too small yields a truncated, NUL-terminated message.
|
||||
var small = [CChar](repeating: 1, count: 4)
|
||||
XCTAssertEqual(csystem_strerror_r(ENOENT, &small, small.count), ERANGE)
|
||||
#if !os(Windows)
|
||||
XCTAssertEqual(String(cString: small), "No ")
|
||||
#endif
|
||||
XCTAssertEqual(small[3], 0)
|
||||
|
||||
// A zero-length buffer is rejected without writing to it.
|
||||
var empty = CChar(1)
|
||||
XCTAssertEqual(csystem_strerror_r(ENOENT, &empty, 0), ERANGE)
|
||||
XCTAssertEqual(empty, 1)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
Reference in new issue
Block a user