From 6dbc60a3737f664007109e6dc8be9010bc4a0857 Mon Sep 17 00:00:00 2001 From: Jonathan Flat Date: Wed, 4 Nov 2026 14:39:33 -0700 Subject: [PATCH 1/4] Update automergers to run from 1.8.x to 1.9.x to main --- .github/workflows/automerge_to_main.yml | 2 +- .github/workflows/automerge_to_release.yml | 21 +++++++++++++++++++++ README.md | 6 +++--- 3 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/automerge_to_release.yml diff --git a/.github/workflows/automerge_to_main.yml b/.github/workflows/automerge_to_main.yml index ec295ff..4e55883 100644 --- a/.github/workflows/automerge_to_main.yml +++ b/.github/workflows/automerge_to_main.yml @@ -12,7 +12,7 @@ jobs: uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.15 with: base_branch: main - head_branch: release/1.8.x + head_branch: release/1.9.x pr_message: This PR was automatically opened by a GitHub action. Review the changes included in this PR and determine if they should be included on main. If yes, merge the PR. Otherwise revert changes that should not be included on this branch. permissions: contents: write diff --git a/.github/workflows/automerge_to_release.yml b/.github/workflows/automerge_to_release.yml new file mode 100644 index 0000000..006fa36 --- /dev/null +++ b/.github/workflows/automerge_to_release.yml @@ -0,0 +1,21 @@ +name: Create PR to merge the previous release branch into the current release branch +# Changes should land on the earliest release branch they will need to ship on and then be automatically forwarded to later release branches and main +permissions: + contents: read +on: + schedule: + # An hour before automerge_to_main.yml. Runs at the same time would collide due to branch naming. + - cron: '0 8 * * *' + workflow_dispatch: +jobs: + create_merge_pr: + name: Create PR to merge previous release branch into current release branch + uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.17 + with: + base_branch: release/1.9.x + head_branch: release/1.8.x + pr_message: This PR was automatically opened by a GitHub action. Review the changes included in this PR and determine if they should be included on this release branch. If yes, merge the PR. Otherwise revert changes that should not be included on this branch. + permissions: + contents: write + pull-requests: write + if: (github.event_name == 'schedule' && github.repository == 'apple/swift-system') || (github.event_name != 'schedule') # Ensure that we don't run this on a schedule in a fork diff --git a/README.md b/README.md index c4c2ad3..49441e2 100644 --- a/README.md +++ b/README.md @@ -114,13 +114,13 @@ We maintain separate branches for each active minor version of the package: | swift-system 1.6.x | release/1.6.0 | | swift-system 1.7.x | release/1.7.0 | | swift-system 1.8.x | release/1.8.x | -| swift-system 1.9.x (unreleased) | | +| swift-system 1.9.x (unreleased) | release/1.9.x | Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction: -`release/1.7.0` → `release/1.8.x` → `main` +`release/1.8.x` → `release/1.9.x` → `main` -For example, anything landing on `release/1.7.0` will eventually appear on `release/1.8.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Merges into `main` are performed by the [automerger](.github/workflows/automerge_to_main.yml); propagation between release branches is performed by project maintainers.) +For example, anything landing on `release/1.8.x` will eventually appear on `release/1.9.x` and finally `main` as well. There is no need to file standalone PRs for each release line. (Merges into `release/1.9.x` and `main` are performed by the [release](.github/workflows/automerge_to_release.yml) and [main](.github/workflows/automerge_to_main.yml) automergers; propagation from older release branches is performed by project maintainers.) ### Code of Conduct From 013178c00ec76ab1df9227ab27a984b95eaab936 Mon Sep 17 00:00:00 2001 From: Lalita Hegade Date: Wed, 11 Nov 2026 17:46:01 +0100 Subject: [PATCH 2/4] 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 --- Sources/CSystem/include/CSystemShared.h | 14 ++++++ Sources/CSystem/shims.c | 41 +++++++++++++++ Sources/System/Errno.swift | 17 +++++-- Sources/System/Internals/Exports.swift | 4 -- Sources/System/Internals/Syscalls.swift | 10 ++++ Tests/SystemTests/ErrnoTest.swift | 66 ++++++++++++++++++++++++- 6 files changed, 143 insertions(+), 9 deletions(-) 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.. Date: Wed, 11 Nov 2026 22:12:05 +0100 Subject: [PATCH 3/4] Report truncated strerror messages as ERANGE on every platform strerror_s on Windows and bionic's strerror_r truncate without returning an error, so detect a full buffer in the shim instead. Also avoid the deprecated String(cString:) array overload in the test. --- Sources/CSystem/include/CSystemShared.h | 5 +++-- Sources/CSystem/shims.c | 23 +++++++++++++++++------ Tests/SystemTests/ErrnoTest.swift | 8 ++++++-- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/Sources/CSystem/include/CSystemShared.h b/Sources/CSystem/include/CSystemShared.h index 9ae7cd5..ec259bf 100644 --- a/Sources/CSystem/include/CSystemShared.h +++ b/Sources/CSystem/include/CSystemShared.h @@ -20,8 +20,9 @@ extern int csystem_posix_dup3(int fildes, int fildes2, int flag); // 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". +// truncated). A message that exactly fills the buffer is also reported as +// ERANGE, because not every C library can tell that apart from truncation. +// 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. diff --git a/Sources/CSystem/shims.c b/Sources/CSystem/shims.c index 942b198..9b18aa1 100644 --- a/Sources/CSystem/shims.c +++ b/Sources/CSystem/shims.c @@ -45,11 +45,7 @@ unsigned long long _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; } #include -extern int csystem_strerror_r(int errnum, char *buf, size_t buflen) { - if (buf == NULL || buflen == 0) { - return ERANGE; - } - buf[0] = '\0'; +static int csystem_strerror_r_impl(int errnum, char *buf, size_t buflen) { #if defined(_WIN32) return strerror_s(buf, buflen, errnum); #elif defined(_GNU_SOURCE) && \ @@ -78,11 +74,26 @@ extern int csystem_strerror_r(int errnum, char *buf, size_t buflen) { if (result == -1) { result = errno; } - buf[buflen - 1] = '\0'; return result; #endif } +extern int csystem_strerror_r(int errnum, char *buf, size_t buflen) { + if (buf == NULL || buflen == 0) { + return ERANGE; + } + buf[0] = '\0'; + int result = csystem_strerror_r_impl(errnum, buf, buflen); + buf[buflen - 1] = '\0'; + // strerror_s on Windows and bionic's strerror_r silently truncate the + // message and return 0. Report a message that fills the whole buffer as + // ERANGE on every platform, since it may have been truncated. + if (result == 0 && strlen(buf) == buflen - 1) { + result = ERANGE; + } + return result; +} + #if !defined(_WIN32) && !defined(__wasi__) && !defined(__APPLE__) #define HAVE_PIPE2_DUP3 #endif diff --git a/Tests/SystemTests/ErrnoTest.swift b/Tests/SystemTests/ErrnoTest.swift index 13ebe58..71cd016 100644 --- a/Tests/SystemTests/ErrnoTest.swift +++ b/Tests/SystemTests/ErrnoTest.swift @@ -282,13 +282,17 @@ final class ErrnoTest: XCTestCase { 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") + XCTAssertEqual( + buffer.withUnsafeBufferPointer { String(cString: $0.baseAddress!) }, + "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 ") + XCTAssertEqual( + small.withUnsafeBufferPointer { String(cString: $0.baseAddress!) }, + "No ") #endif XCTAssertEqual(small[3], 0) From 1c44ed678c6d5da2880d0179ef9e2b7c0cd0bfb4 Mon Sep 17 00:00:00 2001 From: Lalita Hegade Date: Thu, 12 Nov 2026 08:13:35 +0100 Subject: [PATCH 4/4] Copy strerror message directly into the String buffer Use String(unsafeUninitializedCapacity:initializingUTF8With:), through the existing backwards-compatible helper, so the message is written straight into the string's storage instead of a stack buffer that is then copied. Also update the copyright year range of Errno.swift. musl's message for an unknown error number doesn't include the number, so skip that check when building against Musl, as on WASI. --- Sources/System/Errno.swift | 25 ++++++++++++++----------- Tests/SystemTests/ErrnoTest.swift | 5 +++-- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/Sources/System/Errno.swift b/Sources/System/Errno.swift index 4eb7bf1..187cf56 100644 --- a/Sources/System/Errno.swift +++ b/Sources/System/Errno.swift @@ -1,7 +1,7 @@ /* This source file is part of the Swift System open source project - Copyright (c) 2020 - 2024 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 @@ -1552,17 +1552,20 @@ extension Errno: CustomStringConvertible, CustomDebugStringConvertible { @inline(never) public var description: String { // 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) + // csystem_strerror_r truncates it. The message is written directly into + // the new string's storage. + let message = String(_unsafeUninitializedCapacity: 256) { buffer in + let capacity = buffer.count + buffer.withMemoryRebound(to: CChar.self) { buffer in + // 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. The shim always + // NUL-terminates the buffer. + _ = system_strerror_r(self.rawValue, buffer.baseAddress!, capacity) + } + return UnsafeBufferPointer(buffer).firstIndex(of: 0) ?? 0 } + return message.isEmpty ? "unknown error" : message } /// A textual representation, diff --git a/Tests/SystemTests/ErrnoTest.swift b/Tests/SystemTests/ErrnoTest.swift index 71cd016..efbef25 100644 --- a/Tests/SystemTests/ErrnoTest.swift +++ b/Tests/SystemTests/ErrnoTest.swift @@ -250,8 +250,9 @@ final class ErrnoTest: XCTestCase { // 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. + #if !os(Windows) && !os(WASI) && !canImport(Musl) + // Windows' message is just "Unknown error", and musl's (also used by + // WASI) is "No error information", without the number. XCTAssert(unknown.contains("98765"), unknown) #endif }