Merge pull request #421 from 100lalitahegde-eng/fix-156-thread-safe-strerror

Use a thread-safe strerror in Errno.description
This commit is contained in:
Guillaume Lessard authored and GitHub committed 2026-11-12 10:22:43 -08:00
commit 640e5755b5
9 files changed
+189 -14

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ jobs:
uses: swiftlang/github-workflows/.github/workflows/create_automerge_pr.yml@0.0.17
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
@@ -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 <HH-MM> 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
+3 -3
View File
@@ -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
+15
View File
@@ -12,3 +12,18 @@ 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). 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.
extern int csystem_strerror_r(int errnum, char *buf, size_t buflen);
+52
View File
@@ -41,6 +41,58 @@ unsigned long long _system_get_ST_NOSYMFOLLOW(void) { return ST_NOSYMFOLLOW; }
#endif
#include <errno.h>
#include <string.h>
#include <CSystemShared.h>
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) && \
(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;
}
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
+18 -4
View File
@@ -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
@@ -1547,11 +1547,25 @@ 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. 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,
-4
View File
@@ -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)
}
+10
View File
@@ -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
+69 -2
View File
@@ -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,64 @@ 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) && !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
}
#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(
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(
small.withUnsafeBufferPointer { String(cString: $0.baseAddress!) },
"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
}