diff --git a/Sources/CSystem/include/CSystemShared.h b/Sources/CSystem/include/CSystemShared.h index 1ee3a6a..9ae7cd5 100644 --- a/Sources/CSystem/include/CSystemShared.h +++ b/Sources/CSystem/include/CSystemShared.h @@ -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 + +// 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); diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index c027917..942b198 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -41,6 +41,47 @@ unsigned long long _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; } #endif #include +#include + +#include + +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 diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index 5fd33ae..4eb7bf1 100644 --- a/Sources/System/Errno.swift +++ b/Sources/System/Errno.swift @@ -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, diff --git a/Sources/System/Internals/Exports.swift b/Sources/System/Internals/Exports.swift index 3793f0a..bb4a843 100644 --- a/Sources/System/Internals/Exports.swift +++ b/Sources/System/Internals/Exports.swift @@ -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! { - strerror(__errnum) -} - internal func system_strlen(_ s: UnsafePointer) -> Int { strlen(s) } diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index 0909029..5b7507e 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -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, _ length: Int +) -> CInt { + csystem_strerror_r(errnum, buffer, length) +} + // open internal func system_open( _ path: UnsafePointer, _ oflag: Int32 diff --git a/Tests/SystemTests/ErrnoTest.swift b/Tests/SystemTests/ErrnoTest.swift index 767190e..13ebe58 100644 --- a/Tests/SystemTests/ErrnoTest.swift +++ b/Tests/SystemTests/ErrnoTest.swift @@ -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.allocate(capacity: errnos.count) + mismatches.initialize(repeating: 0) + defer { mismatches.deallocate() } + + DispatchQueue.concurrentPerform(iterations: errnos.count) { index in + for _ in 0..