2178 Commits
Author SHA1 Message Date
Cory Benfield 74c924fd01 Apply an autoreleasepool around the task drop (#3638)
Motivation:

Users can write arbitrary code in their deinits, and that arbitrary code
_may_ end up hitting Objective-C autoreleases. We don't want to leak
those objects into the per-thread autoreleasepool, as that may not be
popped for a very long time, if ever, so we need to to ensure that
deiniting the task objects has an autoreleasepool.

Modifications:

Add an autoreleasepool around the task drop, and tests to validate that
we do things correctly.

Result:

Better memory management around deinit
2026-06-24 09:27:31 +01:00
Hamish Knight 849ab561ae NFC: Move fileIO binding before use in childChannelInitializer (#3563)
I'm hoping to ban use-before-declarations at the top level of a
`main.swift` (swiftlang/swift#88082), fix-up this case.
2026-06-23 17:41:32 +00:00
Kumar TanayandGeorge Barnett a8e036cb86 Fix incorrect status lines in HTTPResponseEncoder fast paths (#3631)
### Motivation

`HTTPResponseEncoder` writes hand-optimised status lines for the
well-known `HTTPResponseStatus` values instead of going through the
general `default` path that formats `HTTP/<version> <code>
<reasonPhrase>`. Several of those fast paths had drifted out of sync
with `HTTPResponseStatus.reasonPhrase`, so the exact bytes on the wire
depended on whether a status happened to have a fast path:

* **HTTP/1.0 + 511** emitted the wrong HTTP version (`HTTP/1.1 511 ...`)
— a wire-format correctness bug, not just cosmetic.
* **HTTP/1.1 + 431** emitted the reason phrase `Range Not Satisfiable`
instead of `Request Header Fields Too Large`.
* **HTTP/1.1 + 416** emitted `Request Range Not Satisified` (also
misspelled) instead of `Range Not Satisfiable`.
* **HTTP/1.0 and HTTP/1.1 + 307** emitted `Tempory Redirect`
(misspelled) instead of `Temporary Redirect`.

Resolves #3630.

### Modifications

* Correct the five diverging status lines in `HTTPResponseEncoder` so
they match `HTTPResponseStatus.reasonPhrase` and carry the correct HTTP
version.
* Add a regression test that, for every well-known status at both
HTTP/1.0 and HTTP/1.1, asserts the encoded status line equals the
canonical `HTTP/<version> <code> <reasonPhrase>` form, keeping the fast
paths in lockstep with `reasonPhrase`.

### Result

The encoder now produces correct, consistent status lines for all
well-known statuses regardless of whether they use a fast path. The new
test fails on the pre-fix code (the 511 case fails on the version, the
431/416/307 cases on the reason phrase) and passes after the fix.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2026-06-23 12:33:49 +00:00
jmestwa-coderandCory Benfield 0b38af6217 fix off-by-one boundaries in QUIC bytesNeededForInteger (#3628)
Off-by-one in the QUIC variable-length integer length boundaries.

### Motivation:

`bytesNeededForInteger` classifies an integer into the 1/2/4/8 byte QUIC
encoding using half-open ranges (`0..<63`, `0..<16383`,
`0..<1_073_741_823`, `0..<4_611_686_018_427_387_903`). Those upper
bounds are the *largest* value each size can hold (2^6-1, 2^14-1, 2^30-1
and 2^62-1 per RFC 9000 § 16), so each maximum is wrongly excluded:

- 63, 16383 and 2^30-1 report one byte too many, so the encoder writes
them with a larger encoding than needed.
- 2^62-1, the largest value the encoding can represent, falls through to
the `fatalError` and crashes the encoder.

The existing one-byte write test only iterates `0..<63`, so the 63 case
was never exercised.

### Modifications:

- Switch the four ranges in `bytesNeededForInteger` to inclusive bounds.
- Extend the one-byte write test to include 63, and add boundary checks
plus a 2^62-1 round-trip test.

### Result:

Boundary values encode in the minimal number of bytes and 2^62-1
round-trips instead of crashing.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-06-22 12:45:20 +00:00
Kenta KuboandCory Benfield 0676c27260 [NFC] Remove trailing whitespaces from CNIOFreeBSD (#3632)
This PR is just a cleanup of the source code.

### Motivation:

The `CNIOFreeBSD` source code contains inconsistent trailing
whitespaces, which hinders future modifications.

### Modifications:

Removed all trailing whitespaces from `CNIOFreeBSD`.

### Result:

The source code remains exactly the same; only the trailing whitespace
has been removed.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-06-22 11:02:51 +00:00
Mads Odgaard 77b84ac2cd [NIOFileSystem] Fallback to rename when renameat2 is not available (#3612)
We are running into some issues when doing:

```swift
        let writeOptions: OpenOptions.Write =
            byteOffset > 0 ? .modifyFile(createIfNecessary: true) : .newFile(replaceExisting: true)

        try await FileSystem.shared.withFileHandle(
            forWritingAt: FilePath(outputFilePath),
            options: writeOptions
        ) { fileHandle in
```

which results in crashes on some Android devices where `renameat2` is
not available:

```
('renameat2' system call failed with '(38) Function not implemented'.)
```

This PR adds functionality similar to what is already done for `EINVAL`
on Linux, such that both lead to the same recovery: stat the
destination, then plain rename() if absent.

And for non-exclusive renames where it also fails to function not
implemented, it falls back to plain `rename`.
2026-06-03 14:33:41 +01:00
Aditya Singh 03848cb0cc NonBlockingFileIO: error instead of silently truncating oversized reads (#3607)
Error instead of silently truncating oversized `NonBlockingFileIO`
reads.

### Motivation:

A `ByteBuffer` can hold at most `UInt32.max` bytes, so a read for more
than that can never be satisfied. Today the read functions clamp the
requested `byteCount` to `Int32.max` and then read at most that many
bytes, returning a short buffer with no error and no end-of-file. That
silently breaks the documented contract that the returned `ByteBuffer`
is only shorter than `byteCount` when end-of-file is reached. It also
means a request between 2 GiB and 4 GiB returns fewer bytes than the
caller asked for.

Resolves #2591.

### Modifications:

- `read0` (both the `EventLoopFuture` and the `async` overload) now
fails with an `IOError` (`EINVAL`) when `byteCount` is larger than
`UInt32.max` instead of clamping. The guard runs before any allocation.
On 32-bit platforms `Int.max` is smaller than `UInt32.max` so the guard
is never hit there, and behaviour is unchanged.
- `readSync` now caps the size of each individual `read`/`pread` syscall
at `Int32.max` rather than capping the total `byteCount`. The OS returns
`EINVAL` for a single read larger than `Int32.max`, and the surrounding
loop already reads repeatedly until the whole request is satisfied or
end-of-file is reached, so a request up to `UInt32.max` is now read in
full.
- Added tests covering the future and async read variants for a
`byteCount` larger than a `ByteBuffer` can hold.

I went with `IOError(errnoCode: EINVAL, ...)` rather than a new
`NonBlockingFileIO.Error` case to keep this non API-breaking, matching
the existing `IOError(errnoCode: ENOTDIR, ...)` use in the same file.
Happy to switch to a typed error case if you would prefer that.

### Result:

A read that cannot fit in a `ByteBuffer` fails clearly, and reads
between 2 GiB and 4 GiB are no longer truncated. No public API changes.
2026-05-29 13:53:15 +00:00
Aditya Singh 9ebe69d269 Add get/setMultipleIntegers on ByteBuffer (#3606)
`ByteBuffer` exposes `read`, `write`, and (since the peek work landed)
`peek`
variants of `MultipleIntegers`, but not the absolute-index `get`/`set`
pair that
every other integer accessor on `ByteBuffer` has. This fills that gap,
which is
what #2736 originally asked for.

The thread on #2736 settled on adding `peek*` first so that the common
"look without consuming" use case has a non-mutating, index-free
spelling, and
that is now in place. `get`/`set` remain useful for the niche cases that
genuinely need to address an arbitrary index, so this completes the set
of four
for `MultipleIntegers` to match `getInteger`/`setInteger`.

Both methods are generated from `dev/generate-bytebuffer-multi-int.sh`,
the same
script that produces the read/write/peek variants, so they stay in
lockstep with
the rest of the file across all arities (2 through 15):

- `getMultipleIntegers(at:endianness:as:)` reads at an explicit index
without
moving the reader index and returns `nil` when the requested bytes are
not
  readable, exactly like `getInteger(at:)`.
- `setMultipleIntegers(_:at:endianness:as:)` writes at an explicit index
without
moving the writer index and returns the number of bytes written, exactly
like
  `setInteger(_:at:)`.

The new tests mirror the existing read/write and peek tests: a
round-trip across
both endiannesses, a check that the bytes written by `set` are
byte-for-byte
identical to `writeMultipleIntegers`, coverage of every arity, a check
that
neither method moves the reader or writer index, and the out-of-bounds /
before-reader-index cases that must return `nil`.

Resolves #2736
2026-05-29 12:30:55 +00:00
4e370dc4d7 NIOWebSocket: reject 8-byte payload lengths that exceed Int.max (#3603)
RFC 6455 §5.2 specifies that when the payload length indicator byte is
127, the following 8 bytes hold a 64-bit unsigned integer and the most
significant bit of that integer must be 0. The maximum legal value is
therefore 0x7FFFFFFFFFFFFFFF, which equals Int.max on all 64-bit
platforms Swift supports.

WSParser.parseStep read the raw UInt64 and passed it directly to Int()
without a bounds check. Swift's Int initializer performs a checked
conversion and traps on overflow, so any remote peer that sends a single
WebSocket frame with the MSB of the 8-byte length set will cause a fatal
error in the receiving process. No authentication is required; the frame
is processed before any application handler runs.

The fix adds a guard that rejects the frame with
NIOWebSocketError.invalidFrameLength before the conversion, which is the
same error path used for frames that exceed maxFrameSize. The call site
in decode() is updated to propagate the throw.

A regression test covers the exact byte sequence that previously caused
the fatal trap.

Co-authored-by: g0w6y <g0w6y@users.noreply.github.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-05-26 15:35:59 +01:00
Aditya Singh d20fa05a64 Fix readInlineArray reading from the wrong index when readerIndex is non-zero (#3605)
ByteBuffer.readInlineArray reads each element through getInteger(at:).
The index parameter of getInteger(at:) is an absolute index into the
buffer, the same one readInteger passes self.readerIndex into. The loop
in readInlineArray instead passed stride * index, which starts at zero
and never accounts for the reader index.

As long as the buffer has a reader index of zero this absolute index
lines up with the bytes the caller expects, which is why the current
tests pass: they all read from a freshly written buffer. On any buffer
whose reader index has already moved (the normal case once some bytes
have been consumed, for example reading a length prefix before the
array), getInteger(at:) is given an index below the reader index.
rangeWithinReadableBytes rejects it, getInteger returns nil, and the
force-unwrap on the result traps. So a public read API crashes the
process on entirely valid input.

The fix snapshots the reader index before building the array and offsets
each element index by it, so getInteger(at:) gets the correct absolute
index. The multiplication stays bounded by bytesRequired as before, and
adding the reader index cannot overflow because the result stays within
the writer index.

I added a regression test that writes a short prefix, reads it off so
the reader index is non-zero, then reads an InlineArray and checks both
the element values and the resulting reader index. It traps before this
change and passes after it. The three existing InlineArray tests, the
full ByteBufferTest suite (275 tests), and ByteBufferSpanTests all still
pass.

Reopening the change from #3604, which I closed inadvertently. The
original branch and fork were deleted, so this is a fresh PR with the
identical commit.
2026-05-26 09:03:23 +00:00
Adam FowlerandCory Benfield 9670fe1d68 Don't fatalError if NIOTypedHTTPServerUpgraderStateMachine is in state finished when finding upgrader (#3597)
Don't fatalError in
NIOTypedHTTPServerUpgraderStateMachine.findingUpgraderCompleted` when
the state is `.finished`.

### Motivation:

There is a race where the connection can be closed and the
NIOTypedHTTPServerUpgraderHandler can be removed setting the state to
`.finished` while we are still finding upgraders. And then when
`findingUpgraderCompleted` gets called it would fatalError.

### Modifications:

- Return `nil` as an action if the state is `.finished` when
`findingUpgraderCompleted` is called.
- Added a new set of tests which test the
`NIOTypedHTTPServerUpgraderStateMachine` directly instead of relying on
`HTTPServerUpgraderTests`. I used Swift Testing for these, not sure what
NIO policy on new tests are?

### Result:

No more crashes and better testing for
NIOTypedHTTPServerUpgraderStateMachine

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-05-21 13:41:50 +00:00
Fabian Fett 57c0a08a33 Speed up the tests (#3601)
### Motivation

We want our tests to pass in reasonable time.

### Changes

- Disable test
`ByteBufferCrashTests.setBytesWithoutContigiousStorageMoreThanUInt32maxBytes`
- Do not initialize data in `ByteBufferCrashTests.
takingOwnershipOfPointerThatsToLarge`

### Result

Tests are faster again.
2026-05-20 10:12:53 +00:00
Fabian Fett b24872d3aa Merge commit from fork
Add configurable HTTP/1 decoder parsing limits

### Motivation:

The HTTP/1 decoder previously enforced a single hardcoded limit (80 KB per header field) and placed no cap on the total header-block size or the number of header fields per message. That made resource use unpredictable on requests with very many or very large headers, and there was no way for users to tune the limits for their workload.

### Modifications:

- Introduce a new public `NIOHTTPDecoderLimitConfiguration` exposing three parsing limits:
  - maxHeaderFieldSize — maximum size of a single header field (name + value). Default: 80 KB.
  - maxHeaderListSize — maximum total bytes of all header field names and values combined per message. Default: 2 MB.
  - maxHeaderFieldCount — maximum number of header fields per message, including trailers. Default: 256.
- Plumb the configuration through `HTTPDecoder` / `HTTPRequestDecoder` / `HTTPResponseDecoder` initializers. The existing initializers continue to work unchanged via convenience overloads that fall back to
  default limits.
- Expose the configuration on `NIOUpgradableHTTPServerPipelineConfiguration` and `NIOUpgradableHTTPClientPipelineConfiguration` so users of the typed pipeline setup can override the defaults.
- Track per-message totals in `BetterHTTPParser` and reject with `HTTPParserError.headerOverflow` when a limit is exceeded; counters reset at each new message so HTTP/1 pipelined connections behave
  correctly.
- Add tests covering the success and error paths for each limit, the default behaviors, and that trailer fields count toward the field-count cap.

### Result:

Users can configure the HTTP/1 decoder's per-field-size, total-list-size, and field-count limits. Existing call sites continue to compile and run unchanged, now with bounded defaults across all three dimensions instead of just one.
2026-05-20 10:00:56 +01:00
Fabian Fett 87f935b70c Merge commit from fork
This patch adds additional validation that we don't overflow the ByteBuffers capacity (which is capped at UInt32.max).
2026-05-20 09:58:46 +01:00
Fabian Fett dd16365724 Merge commit from fork
- Ensure HTTP Request Uri and Method only contain allowed bytes
- Ensure HTTP Response Reasons only contain allowed bytes
2026-05-20 09:56:46 +01:00
Shaurya SinghandCory Benfield 6338e9fb5e Fix doubled 'the' in NIOAsyncChannel upgrade docs (#3600)
## Summary

Trivial typo fix in the Swift Concurrency user-facing documentation.

In
[`Sources/NIOCore/Docs.docc/swift-concurrency.md`](https://github.com/apple/swift-nio/blob/main/Sources/NIOCore/Docs.docc/swift-concurrency.md),
the NIOAsyncChannel websocket-upgrade walkthrough reads:

> switch over the the `upgradeResult`. Importantly, we have to `await`
the

Drops the duplicate "the".

## Test plan

- [x] `grep -rEn '\b(the the|of of|in in|and and|that that|is is|to
to)\b' --include='*.swift' --include='*.md' Sources` — exit 1 after the
fix (was the only hit before).

## Scope

One-character change in one Markdown file. No code, no behavior, no API.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-05-18 19:23:35 +00:00
Mads OdgaardandCory Benfield 0ee0fd1b38 [Android] Gate getifaddrs behind API 24 availability (#3506)
The `getifaddrs` is only available on Android API 24+. So, to make
`swift-nio` compile on API 23, we need to add `@available` annotations
to the functions that use it. Which are just the two interface enumerate
functions.

### Result:

`swift-nio` can be compiled for Android 23.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-05-18 12:25:24 +01:00
PAVANSAI KUMAR ALLADIandPavan sai kumar alladi 9f506606a9 Add dnsResolver configuration option for randomized DNS load balancing (#3577)
### Motivation:

When connecting to services with multiple DNS records (e.g. Kubernetes
headless services), getaddrinfo returns addresses in a deterministic
order, causing all connections to go to the same backend. SwiftNIO now
provides a RandomizedDNSResolver that shuffles results.

### Modifications:

Add a dnsResolver property to HTTPClient.Configuration with two options:
.system (default, current behavior) and randomized (uses NIO's
RandomizedDNSResolver to shuffle DNS results). Apply the resolver to
ClientBootstrap during connection creation.

### Result:

Users can opt into randomized DNS resolution by setting
config.dnsResolver = .randomized, enabling load distribution across
multiple backend IPs while preserving the default behavior.

---------

Co-authored-by: Pavan sai kumar alladi <p_alladi@apple.com>
2026-05-17 21:53:29 +00:00
David SternandDavid Stern c077074e9f Allow concurrent createDirectory calls with shared ancestor paths (#3598)
Allow concurrent calls of `_createDirectory()` for file paths with
shared ancestors.

### Motivation:

The current implementation of
`_createDirectory(withIntermediateDirectories: true)` does not catch and
continue during execution when the intermediate directory path it is
trying to create already exists.

The current loop looks like this: 

```swift
 // Successfully made a directory, construct its children.
        while let subdirectory = droppedComponents.popLast() {
            path.append(subdirectory)
            switch Syscall.mkdir(at: path, permissions: permissions) {
            case .success:
                continue
            case let .failure(errno):
                return .failure(.mkdir(errno: errno, path: path, location: .here()))
            }
        }
```
If we are concurrently trying to create directories `/foo/bar/dir1` and
`foo/bar/dir2`, we can fail with an error like `directory /foo already
exists` because one of the two task's `mkdir` syscall on line 928
errored with a `fileExists` error.
 
### Modifications:

The code adds the same logic already present on lines 894-907 of
`FileSystem.swift` to the failure case while iterating over the
subdirectory paths:

If the syscall errors because the directory already exists, (but didn't
exist during the loop on lines 886-923), we can safely continue. Another
task must have beaten our task to creating the directory, but that is
ok.

### Result:

Without this change, it would be difficult to actually call the
`FileSystem.createDirectory(withIntermediateDirectories: true)` function
in concurrent tasks, because if you were creating directories with
common ancestors, at least one of the 2 tasks would error due to the
race condition on directory creation. With this change, the
`createDirectory()` function can now be called concurrently without this
race issue potentially causing an error. I added the change to both the
`NIOFS` and `_NIOFileSystem` directories since they seem to be copies of
each other.

Co-authored-by: David Stern <d_stern@apple.com>
2026-05-15 08:11:37 +00:00
Francesco Paolo Severino 32f395bc91 Add helpers for reading length-prefixed things (#3589)
Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length.

### Motivation:

There are already some APIs for writing length-prefixed strings and
bytes with a custom strategy for encoding the length, but there weren't
helpers to read them.

### Modifications:

- Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length
- Add tests for the new APIs 
- Fix DocC comments and improve the related article 

### Result:

New APIs are added for reading length-prefixed strings and bytes with a
custom strategy for encoding the length.
2026-05-12 11:53:10 +01:00
Rafael Cepeda ad37b30223 Makes NIOCore target compile on FreeBSD (#3587)
This PR is a step towards having full support for FreeBSD in SwiftNIO.
It builds on #3494 to enable full compilation of the NIOCore target.

### Motivation:

Currently, SwiftNIO doesn't not compile on FreeBSD. This PR ensures that
at least the **NIOCore** module compiles correctly on FreeBSD.

### Modifications:
* Make `swift build --target NIOCore` work on FreeBSD.

### Result:

Using the available Swift FreeBSD x86_64 toolchain, it is now possible
to run `swift build --target NIOCore` successfully.
2026-05-11 19:56:51 +01:00
Fabian Fett 37e191d35b Strip Transfer-Encoding when Content-Length is present in HTTPEncoder (#3583)
Strip Transfer-Encoding when Content-Length is present in HTTPEncoder

### Motivation

When `correctlyFrameTransportHeaders()` detected a `Content-Length`
header, it returned `.contentLength` without removing any existing
`Transfer-Encoding` header.

### Changes

- Remove `Transfer-Encoding` header, if a `Content-Length` header is
present

### Result

NIO sends either a `Content-Length` header or a `Transfer-Encoding`
header, but not both.
2026-05-06 10:14:09 +00:00
Johannes Weiss 1c8b29ce10 make internal FTSInfo take CInt (#3586)
### Motivation:

Internally, `FTSInfo` always casted up to `CInt` from `UInt16` but for
some reason it only accepted `UInt16`. Let's add a `CInt` constructor
too.

### Modifications:

- Make internal `FTSInfo` constructible from `CInt` and `UInt16`.

### Result:

- Slightly better platform compatibility
- Possibly fewer casts
2026-05-05 15:09:00 +00:00
38000794f2 Split FoundationEssentials extensions from NIOFoundationCompat (#3567)
Split FoundationEssentials extensions from NIOFoundationCompat

### Motivation:

Resolves #3038 

### Modifications:

Split NIOFoundationCompat into two and only import FoundationEssentials
and NIOFoundationEssentialsCompat where appropriate.

### Result:

ByteBuffer/Codable extensions can be used without vendoring the code or
linking to Foundation.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Fabian Fett <fabianfett@apple.com>
2026-04-21 18:58:43 +01:00
mananandSi Beaumont cd6710454f Preserve getaddrinfo error code in SocketAddressError (#3558)
As observed by @weissi https://github.com/apple/swift-nio/issues/3382
  ### Motivation:
When `getaddrinfo` fails, SwiftNIO throws `SocketAddressError.unknown`
which discards the error code. This makes it impossible for callers to
distinguish between different failure reasons (e.g., `EAI_NONAME` vs
`EAI_AGAIN`), which is needed for retry logic and diagnostics.
   
### Modifications:
- Add `SocketAddressError.UnknownHost` struct that carries `host`,
`port`, `errorCode` (from `getaddrinfo`), and `errorDescription` (from
`gai_strerror`).
- Update `SocketAddress.makeAddressResolvingHost` and
`GetaddrinfoResolver` to throw/fail with the new error type on both
POSIX and Windows paths.
- Update existing test catch blocks to use the new error type.
- Add `testGetaddrinfoErrorCodeIsPreserved` to verify the error code is
captured.
  ### Result:
Callers can now inspect the `getaddrinfo` error code when host
resolution fails, enabling more specific error handling. Resolves
https://github.com/apple/swift-nio/issues/3382
  
### Questions for reviewer

1. **Should `case unknown(host:port:)` be deprecated?** — This enum case
is no longer thrown after this PR. Callers catching `.unknown` will
silently stop matching. Should I add
`@available(*, deprecated, renamed: "UnknownHost")` to provide a
migration path?

2. **Should the doc comment on `makeAddressResolvingHost` be updated?**
— The `- Throws:` line still references `SocketAddressError.unknown`
instead of the new
   `SocketAddressError.UnknownHost`.

---------

Co-authored-by: Si Beaumont <beaumont@apple.com>
2026-04-15 13:08:59 +00:00
Alex TowellandClaude Opus 4.6 98f8824da0 Handle EPERM as permissionDenied in open syscall error mapping (#3560)
## Summary
- NIOFileSystem's `open` syscall error mapping only handled `EACCES`
(`.permissionDenied`) but not `EPERM` (`.notPermitted`), causing EPERM
errors (e.g., on network volumes) to be classified as "unknown" instead
of `permissionDenied`
- Added `.notPermitted` alongside `.permissionDenied` in the `open()`
switch case in `FileSystemError+Syscall.swift` (both `NIOFS` and
`_NIOFileSystem` modules)
- Added corresponding test expectation for the new errno mapping

## Motivation
Other syscall handlers in the same file (`remove`, `symlink`, `unlink`,
`futimens`) already correctly handle both `.permissionDenied` and
`.notPermitted` as `permissionDenied`. The `open` handler was missing
this treatment.

Fixes #3559

## Test plan
- [x] Updated `testErrnoMapping_open` to verify `.notPermitted` maps to
`.permissionDenied`
- [ ] CI will validate on all supported Swift versions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 15:59:06 +00:00
Cory Benfield bdf004b44f Enable thread-pools to be pinned to CPUs (#3557)
Motivation:

Similar to MultiThreadedEventLoopGroup, it is useful in some NUMA
circumstances to be able to pin thread pools to specific CPUs. This can
minimise the overheads of moving memory around across NUMA nodes.

Modifications:

Added a pinned CPUs initializer to NIOThreadPool

Result:

Users have more flexibility.
2026-03-23 08:20:33 +00:00
Kenta KuboandCory Benfield 795162f1bc Add partial support for FreeBSD (#3494)
This PR adds support for FreeBSD to the `CNIOSHA1` target and the
`NIOConcurrencyHelpers` target.

### Motivation:

This PR is partial because the `NIOCore` target still can't be built,
and the existing PR #3398 includes almost the same changes too.

However, #3398 is a little bit old. Besides, the source code in
`NIOConcurrencyHelpers` is used in other repositories now, for example:

- https://github.com/apple/swift-log/pull/398
- https://github.com/apple/swift-log/pull/387 was merged before
swift-nio is fixed.

So I think it's important to fix `NIOConcurrencyHelpers` first, even if
the entire swift-nio is yet to be fixed.

### Modifications:

- Make `swift build --target NIOConcurrencyHelpers` work on FreeBSD
- Make `swift build --target CNIOSHA1` work on FreeBSD

### Result:

The following commands finished successfully.

```shell
swift build --target NIOConcurrencyHelpers
swift build --target CNIOSHA1
```

Environment:

- FreeBSD 15.0-RELEASE-p1 x86_64
- [Swift on FreeBSD Preview
toolchain](https://forums.swift.org/t/swift-on-freebsd-preview/83064)
  ```
  Swift version 6.3-dev (LLVM b58b2a34d509492, Swift cf535d8b998d09b)
  Target: x86_64-unknown-freebsd14.3
  Build config: +assertions
  ```

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-03-18 10:30:06 +00:00
Cory Benfield b9d20d3476 Benchmarks for channel pipeline creation (#3531)
Motivation:

Creating channel pipelines is a fairly expensive operation. We should
try to know how expensive.

Modifications:

Add benchmarks for ChannelPipeline setup.

Result:

We'll know more.

Some results in a Linux VM on my M4 Max laptop:

```
=================
NIOCoreBenchmarks
=================

ChannelPipeline.init(0 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         3 │         3 │         3 │         3 │         3 │         3 │         3 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       156 │       177 │       214 │       322 │       367 │       989 │      2148 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(1 handler)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         5 │         5 │         5 │         5 │         5 │         5 │         5 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       269 │       290 │       301 │       463 │       501 │       583 │       611 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(3 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │         9 │         9 │         9 │         9 │         9 │         9 │         9 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │       477 │       521 │       540 │       553 │       574 │       817 │       907 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

ChannelPipeline.init(10 handlers)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Malloc (total) *         │        23 │        23 │        23 │        23 │        23 │        23 │        23 │      1000 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ns) * │      1263 │      1363 │      1404 │      1679 │      2146 │      2482 │      3133 │      1000 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```
2026-03-16 11:23:45 +00:00
Cory Benfield 5b3cab2bb0 Make MTELG's support for CPU pinning public (#3543)
Motivation:

NIO has had support for CPU pinning for 8 years, but nobody has ever
used it. Ask me how I know?

Modifications:

- Make the CPU pinning constructor public.

Result:

Users can pin MTELG threads to specific CPU cores, _finally_.
2026-03-09 16:58:55 +00:00
George Barnett 57a73c653b Deprecate System.udpMaxSegments (#3541)
Motivation:

System.udpMaxSegments purports to expose the value of UDP_MAX_SEGMENTS.
However this doesn't appear to be part of the UAPI so it always returns
nil.

Modifications:

- Deprecate `System.udpMaxSegments`
- Remove the C shim
- Update tests

Result:

After your change, what will change.
2026-03-09 15:46:31 +00:00
Stepan Ulyanin 182ae0b4f9 Add the replaceExisting to the _NIOFileSystem copyItem (#3535)
Adds the changes from https://github.com/apple/swift-nio/pull/3508 to
the `_NIOFileSystem`.
### Motivation:

We have added capability to overwrite regular files and symbolic links
to `NIOFS` `FileSystem.copyItem` in
https://github.com/apple/swift-nio/pull/3508. Now we want to port the
same logic to `_NIOFileSystem`.

### Modifications:

- Adds a new `FileSystemProtocol.copyItem` requirement with
`replaceExisting: bool` parameter along with a default implementation.
- Adds an implementation of the new `FileSystemProtocol.copyItem`
requirement to `_NIOFileSystem`'s `FileSystem` struct for regular files
and symbolic links.

### Notes

It seems that the tests for `FileSystem` are only in `NIOFS` - so no
tests are added in this PR.
2026-03-09 10:59:41 +00:00
Mihai ChioreanandCory Benfield acf9bbe0fd Support scoped IPv6 addresses in SocketAddress.init(ipAddress:port:) (#3525)
### Motivation

`SocketAddress.init(ipAddress:port:)` uses `inet_pton` to parse IP
address strings. `inet_pton` does not support the `%scope` suffix used
in IPv6 link-local addresses (e.g., `fe80::1%eth0`), causing these
addresses to fail with `failedToParseIPString`. This forces downstream
consumers like grpc-swift-nio-transport to reimplement scoped IPv6
parsing using `getaddrinfo` themselves.

Related: https://github.com/grpc/grpc-swift-nio-transport/issues/147

### Modifications

When the IP address string contains a `%` character, fall back to
`getaddrinfo` with `AI_NUMERICHOST` instead of `inet_pton`. This
properly parses the `%scope` suffix and sets `sin6_scope_id` in the
resulting `sockaddr_in6`. The scoped path is extracted into a private
`_parseScopedIPv6` helper, guarded with `#if !os(Windows) && !os(WASI)`.
The non-scoped `inet_pton` path is completely unchanged.

Added 5 tests:
- Named scope (`fe80::1%lo`) — verifies `sin6_scope_id` matches
`if_nametoindex`
- Numeric scope (`fe80::1%1`) — verifies numeric index parsing
- Scoped vs non-scoped inequality — different `sin6_scope_id` means
different addresses
- Invalid scopes rejected — empty scope and nonexistent interface both
throw
- Non-scoped regression — `::1` still works with `scope_id == 0`

### Result

`SocketAddress(ipAddress: "fe80::1%eth0", port: 80)` now succeeds and
preserves the scope ID in `sin6_scope_id`. Non-scoped addresses continue
to work exactly as before.

### Context

This came up while working on IPv6 link-local support in
[grpc-swift-nio-transport#146](https://github.com/grpc/grpc-swift-nio-transport/pull/146),
where the workaround was to use `getaddrinfo` directly in the gRPC
layer. The reviewer suggested upstreaming this to swift-nio so the
workaround can be removed.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-03-06 08:49:57 +00:00
Fabian Fett ada5f7690b Improve NIOAsyncChannel performance with UnsafeContinuations (#3521)
Let's improve NIOAsyncChannels performance, by using UnsafeContinuations
instead of CheckedContinuations.

### Motivation:

We want to improve the performance for our async APIs.

### Modifications:

- Introduce a new typealias `NIOUnsafeContinuation` that behaves like a
UnsafeContinuation in release mode and like a CheckedContinuation in
debug mode.
- Use the `NIOUnsafeContinuation` inside the `NIOAsyncWriter`
- Use the `NIOUnsafeContinuation` inside the
`NIOThrowingAsyncSequenceProducer`

### Result:

Fewer allocations
2026-03-04 11:09:34 +00:00
Rick Newton-Rogers 83509ed06d ByteBuffer custom allocator support (#3526)
### Motivation

* Other libraries often have byte buffer storage with similar concepts
as NIO's `ByteBuffer`, linear storage with reader and writer indices -
it would be nice to have efficient conversion to and from these objects.
* Efficienct conversion would likely mean taking ownership of the byte
storage allocated by the other object and exposing `ByteBuffer`s
internals so that they may be owned by another object, there is no API
for this currently.

### Modifications

* Added new methods behind `CustomByteBufferAllocator` SPI.
* Added public `ByteBuffer` initializer for adopting
externally-allocated memory
* Made `ByteBufferAllocator` initializer public with custom
`malloc`/`realloc`/`free`/`memcpy` hooks
* Updated `realloc` signature to pass old capacity alongside new
capacity to allow implementations to copy over bytes
* Added `withVeryUnsafeMutableBytesWithStorageManagement` for mutable
storage access
* Updated all existing tests using internal allocator API to use the new
API
* Added tests for custom allocator functionality

### Result

* Custom allocators can manage `ByteBuffer` memory with full size
information
* External systems can transfer memory ownership to `ByteBuffer`
* System allocator maintains zero overhead due to inlining of the
wrapper
* API (SPI) is extensible for future allocation system integrations
2026-03-02 10:52:17 +00:00
Stepan Ulyanin fff2515d6e Add symlinkat, renameatx_np, and unlinkat system call wrappers to the _NIOFileSystem module (#3524)
Ports the added system calls from `NIOFS` (from
https://github.com/apple/swift-nio/pull/3505) to `_NIOFileSystem`:

> Adds three new system call wrappers for the `symlinkat`,
`renameatx_np`, and `unlinkat` system calls.

### Motivation:

`_NIOFileSystem` module is around for backward compatibility - hence, we
are porting the new feature to it.

### Modifications:

Exactly same as in https://github.com/apple/swift-nio/pull/3505 but
applied to the `_NIOFileSystem`:

> Related to https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470. This PR adds syscall
wrappers needed to atomically overwrite existing files or symlinks at
the destination during copy operations. On Linux, atomic overwrites
require a "copy to temp file, then rename" strategy. We use the `*at`
family of syscalls (which operate relative to directory file
descriptors) to avoid TOCTOU race conditions.
2026-03-02 10:00:35 +00:00
Cory Benfield d38344d14b Improve the performance of looking up the current SEL (#3530)
Motivation:

Right now we store our selectable event loop reference in a NIO
ThreadSpecificVariable. That's nice enough, but this has become a hot
code path in cases where users are using the complete concurrency
override. In those cases, the ThreadSpecificVariable forces us to both
call `pthread_getspecific` and to end up needing to perform a dynamic
cast to our expected type.

These dynamic casts are costly: in one sample project where we spent
fully 7.84% of the runtime in dispatching tasks onto the EL, the cost of
that dynamic cast _alone_ was 0.5% of the runtime, with
pthread_getspecific being another 0.2%. This is 10% of the cost of
dispatching a job, entirely unnecessarily.

Modifications:

- Use some fancy C thread-locals, which have much better performance:
see #3302 for more on that.
- Use Unamanged to pass the self reference into and out of the
thread-local, avoiding dynamic casts.

Result:

Further improved performance for concurrency takeover.

Before this change:

```
any() from event loop thread (fast path): 30.654833 ns/iteration
any() from outside (fallback path): 17.881084 ns/iteration
```

After this change:

```
any() from event loop thread (fast path): 11.571958 ns/iteration
any() from outside (fallback path): 17.52175 ns/iteration
```

Nearly a 3x speedup on that particular operation. Not so bad.

Note the irony that before this change it was actually more expensive to
call `any` from _on_ an EL thread than off it. Both calls had to call
pthread_getspecific, which means all of this cost was the runtime type
conversion.
2026-02-27 16:46:58 +00:00
Cory Benfield 41fc4a7aff Make concurrency take over cheaper (#3527)
Motivation:

When using concurrency takeover, we currently spend nearly half the
runtime checking if our SelectableEventLoop has an enqueue function. We
know it does, but we just haven't given the compiler enough evidence.
This patch rewrites the code to prove it to the compiler.

Modifications:

- Expose internal functions without erased types on MTELG
- Use these internal functions, and call directly to SEL, eliminiating
the as!.

Result:

Massive perf improvement in task enqueueing.
2026-02-27 13:58:35 +00:00
Stepan UlyaninandGeorge Barnett be8fdc13c0 Allow to copy files and symlinks while overwriting the destination (#3508)
Adds capability to NIOFS to copy regular files and symlink, allowing to
overwrite the destination.

### Motivation:

Per https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470 we want to add
`replaceExisting: bool` to `FileSystem.copyItem`.

### Modifications:

1. Adds `replaceExisting: bool` parameter to
`FileSystemProtocol.copyItem`.
2. Adds `replaceExisting: bool` parameter to `FileSystem.copyItem` and
implementation for regular files and symbolic links.
3. Adds tests.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2026-02-18 08:57:33 +00:00
Si BeaumontandAgam Dua b0e024792a Add opt-in API for channels to expose their underlying transport (#3509)
## Motivation

NIO channels abstract over an underlying transport mechanisms (sockets,
pipes, etc.), which users typically need not interact with. However,
there are scenarios where users need direct access to the underlying
transport for low-level operations that work outside NIOs abstraction.
One example is performing out out-of-band operations on the underlying
file descriptor for a socket-based channel.

This PR adds a structured way to access the underlying transport of a
channel, for channels that choose to implement it.

## Modifications

- Add a new `public protocol
NIOTransportAccessibleChannelCore<Transport>` which provides a scoped
`withUnsafeTransport(_:)`, used for channel implementations to opt-in.
- Add conformance to
`NIOTransportAccessibleChannel<NIOBSDSocket.Handle>` for
`BaseSocketChannel`, to make this API available for all socket-based
channels, including channels returned from the socket-based bootstrap
public APIs.
- Add public API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`

Note that not all channels need to or should their transport, which is
why this was added as an additional protocol that refines `ChannelCore`,
vs. extending `Channel` or `ChannelCore` with a default implementation.

The protocol uses a primary associated type allowing channels to provide
typed access to the transport. E.g. this could be used in NIO Transport
Services to expose the underlying `NWConnection`, if desired.

The method itself is spelled with "unsafe", uses scoped access, and has
clear documentation that users must not violated any of NIOs assumptions
about the state of the underlying transport. It's very much not intended
for every day use. It being on `ChannelCore` should defer users of the
low-level API, since `Channel._channelCore` is marked as for NIO
internal use, and the public `withUnsafeTransportIfAvailable(_:)` will
take care of the runtime checks for channels that have opted into this
API.

## Result

- New opt-in API for channel implementations to expose their underlying
transport
- All socket-based channels from NIOPosix now expose the underlying
socket file descriptor
- New API
`ChannelPipeline.SynchronousOperations.withUnsafeTransportIfAvailable(_:)`
for users

---------

Co-authored-by: Agam Dua <agam_dua@apple.com>
2026-02-17 16:12:58 +00:00
Fabian Fett 2fdda6c78e Fix benchmark succeeding – even though Benchmark build failed (#3502)
### Motivation:

Currently if there is an error in the Benchmark targets, that prevents
the Benchmark to build correctly, we still get a CI success.

### Modifications:

- Check for the threshold changed error

### Result:

- More reliable CI
2026-02-17 10:30:44 +00:00
Raphael d948192838 Don't send (in)active when channel closes directly (#3497)
### Motivation

Issue #2773 reports a problem where channels can receive
`channelInactive` before `channelActive`. This breaks expectations and
should not happen. Instead of sending them in the wrong order, this PR
suppresses both of them in those cases.

### Modifications

* Add a test to reproduce the problematic behavior.
* Update the state machine to split the active state into two. This
decouples succeeding the promise from sending the signal. Transiting to
closing only sends `channelInactive` when originating from the state
that sent `channelActive`.

### Result

Address #2773.

Edit: Updated modifications to reflect latests commit.
2026-02-11 15:46:19 +00:00
Kushal Pisavadia 9b92dcd5c2 Replace ConditionLock with wake-one signalling NIOThreadPoolWorkAvailable (#3507)
**TL;DR** This change leads to a ~90% reduction in observed system CPU
time for some use cases by waking a single thread, instead of all idle
threads.

# Changes

Inlining the commit messages here.

## Add NIOThreadPool submit throughput benchmarks

### Motivation

`NIOThreadPool` had no benchmarks measuring submit overhead. This makes
it difficult to evaluate the cost of signalling changes or to catch
latency regressions.

### Modifications

Add thread pool submit benchmarks, covering use cases with 4-thread and
16-thread pools.

### Result

`NIOThreadPool` submit throughput and context-switch overhead are now
tracked by benchmarks.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        77 │        78 │        79 │        80 │        80 │        92 │        92 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │       106 │       107 │       108 │       109 │       110 │       116 │       116 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │      1649 │      1752 │      1768 │      1795 │      1826 │      1929 │      1929 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │      1701 │      1805 │      1821 │      1849 │      1879 │      1987 │      1987 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        51 │        52 │        52 │        53 │        53 │        57 │        57 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │       167 │       177 │       178 │       181 │       183 │       200 │       200 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        44 │        44 │        44 │        45 │        45 │        45 │        45 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        65 │        65 │        65 │        66 │        66 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │       159 │       162 │       163 │       165 │       166 │       169 │       169 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │       178 │       182 │       183 │       185 │       186 │       190 │       190 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        19 │        19 │        20 │        20 │        20 │        21 │        21 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        76 │        79 │        79 │        80 │        80 │        82 │        82 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>

## Replace `ConditionLock` with wake-one signalling
`NIOThreadPoolWorkAvailable`

### Motivation

`NIOThreadPool` used `ConditionLock` which calls
`pthread_cond_broadcast` on every state change, waking all threads when
only one work item is enqueued. This causes a thundering-herd problem.

### Modifications

Add `NIOThreadPoolWorkAvailable` in NIOConcurrencyHelpers that uses
`pthread_cond_signal` (wake-one) for work submission and
`pthread_cond_broadcast` only for shutdown. Replace
`ConditionLock<_WorkState>` and the `_WorkState` enum in `NIOThreadPool`
with this new primitive.

### Result

Submitting a work item wakes exactly **one** thread instead of all
threads.

### Benchmark Results

<details>

```
NIOThreadPool.serial_wakeup(16 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        47 │        49 │        49 │        50 │        50 │        55 │        55 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        57 │        58 │        59 │        60 │        61 │        67 │        67 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (ms) *   │        10 │        10 │        10 │        10 │        10 │        12 │        12 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        54 │        55 │        56 │        56 │        57 │        65 │        65 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛

NIOThreadPool.serial_wakeup(4 threads)
╒══════════════════════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╤═══════════╕
│ Metric                   │        p0 │       p25 │       p50 │       p75 │       p90 │       p99 │      p100 │   Samples │
╞══════════════════════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╪═══════════╡
│ Context switches (K)     │        20 │        20 │        20 │        20 │        20 │        20 │        20 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Syscalls (total) (K) *   │        40 │        40 │        40 │        40 │        40 │        40 │        40 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (system CPU) (ms) * │        45 │        46 │        46 │        47 │        57 │        75 │        75 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (total CPU) (ms) *  │        54 │        55 │        56 │        57 │        68 │        87 │        87 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (user CPU) (μs) *   │      9055 │      9372 │      9478 │      9765 │     10887 │     12585 │     12585 │        30 │
├──────────────────────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┼───────────┤
│ Time (wall clock) (ms) * │        52 │        53 │        53 │        54 │        64 │       124 │       124 │        30 │
╘══════════════════════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╧═══════════╛
```

</details>
2026-02-10 20:01:35 +00:00
Stepan Ulyanin db01d87942 Add symlinkat, renameatx_np, and unlinkat system call wrappers (#3505)
Adds three new system call wrappers for the `symlinkat`, `renameatx_np`,
and `unlinkat` system calls.

### Motivation:

Related to https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470. This PR adds syscall
wrappers needed to atomically overwrite existing files or symlinks at
the destination during copy operations. On Linux, atomic overwrites
require a "copy to temp file, then rename" strategy. We use the `*at`
family of syscalls (which operate relative to directory file
descriptors) to avoid TOCTOU race conditions.

### Modifications:

1. Adds three system call wrappers for the `symlinkat`, `renameatx_np`,
and `unlinkat` system calls.
2. Adds related tests
3. Updates the `FileSystemError` for `symlink` and `unlink` to take in
the system call name to allow for the `*at` names to be passed.
2026-02-09 08:38:25 +00:00
Si Beaumont edad6d8a9b Clarify state and relationship of NIOFileSystem and _NIOFileSystem in API docs (#3504)
### Motivation:

`NIOFileSystem` currently exposes the same API as `_NIOFileSystem`,
which is not API stable. `NIOFileSystem`
was created in error, and its lack of underscore incorrectly implies API
stability. Users who are currently importing `NIOFileSystem` should
ideally move to `_NIOFileSystem`. However this isn't made clear in the
docs:

1. The README talks about the non-underscored `NIOFileSystem`.
2. There are no hosted API docs `NIOFileSystem`.
3. The hosted API docs for `NIO` point to the docs for `NIOFileSystem`
-- results in 404.

### Modifications:

- Update the README to refer to `_NIOFileSystem`.
- Update the hosted API docs for `NIO` to point to docs for
`_NIOFileSystem`.
- Add hosted API docs for `NIOFileSystem` with a statement explaining
the situation and pointing people to the docs
  for `_NIOFileSystem`.

### Result:

Clearer documentation on the state and relationship of the
`NIOFileSystem` and `_NIOFileSystem` modules.
2026-02-06 18:56:42 +00:00
Fabian Fett 6a6f7d7c33 Centralize UnsafeTransfer in NIOCore (#3492)
We have a number of copies of `UnsafeTransfer` and two copies of
`UnsafeMutableTransferBox` in our code base. Before introducing more of
those, lets centralize to just one using a `package` access modifier.
2026-02-03 10:27:30 +00:00
Si Beaumont 37ffc4b8d5 Add API to enable throwing in EmbeddedChannel.getOption and .setOption if channel is closed (#3495)
### Motivation:

Channels based on `BaseSocketChannel` throw in both `getOption` and
`setOption` if the channel has been closed, since the `setsockopt` will
fail. However, the current behavior of `EmbeddedChannel` is options
remain writable and readable on closed channels.

There are situations where we'd like to be able to model the runtime
behaviour of the real channel in tests, e.g. to test this fix:
https://github.com/apple/swift-nio-extras/pull/304.

### Modifications:

- Add API to enable throwing in `EmbeddedChannel.getOption` and
`.setOption` if channel is closed.
- Add a test for this new behavior.

### Result:

- New API to enable throwing in `EmbeddedChannel.getOption` and
`.setOption` if channel is closed.
- No observable change for existing users of `EmbeddedChannel`.
2026-01-27 12:06:55 +00:00
scottmarchant 5bf0267df4 build: Elide NIOPosix for WASI platforms only (#3485)
### Motivation:

Packages that consume NIOPosix should be able to compile to WASI
platforms without special configurations. This change elides the
NIOPosix source from WASI platforms to simplify configuration.

Without this change:

```swift
dependencies: [
    // Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
    .product(
        name: "NIOPosix",
        package: "swift-nio",
        condition: .when(platforms: [
            .macOS,
            .macCatalyst,
            .iOS,
            .tvOS,
            .watchOS,
            .visionOS,
            .driverKit,
            .linux,
            .windows,
            .android,
            .openbsd,
            // .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
        ])
    ),
]
```

With this change:

```swift
dependencies: [
    // Without this PR, downstream packages can consume NIOPosix simply:
    .product(name: "NIOPosix", package: "swift-nio"),
]
```

### Modifications:

- Add compiler directives (`#if !os(WASI)`) to all source files in
NIOPosix

### Result:

Downstream packages can compile to wasm without manually excluding the
NIOPosix dependency.

### Testing performed

- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOPosix` compiles, which demonstrates proper elision of source files in
NIOPosix that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151341738).
2026-01-23 16:39:32 +00:00
scottmarchant 3f80264185 build: Elide NIOEmbedded for WASI platforms only (#3484)
### Motivation:

Packages that consume NIOEmbedded should be able to compile to WASI
platforms without special configurations. This change elides the
NIOEmbedded source from WASI platforms to simplify configuration.

Without this change:

```swift
dependencies: [
    // Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
    .product(
        name: "NIOEmbedded",
        package: "swift-nio",
        condition: .when(platforms: [
            .macOS,
            .macCatalyst,
            .iOS,
            .tvOS,
            .watchOS,
            .visionOS,
            .driverKit,
            .linux,
            .windows,
            .android,
            .openbsd,
            // .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
        ])
    ),
]
```

With this change:

```swift
dependencies: [
    // Without this PR, downstream packages can consume NIOEmbedded simply:
    .product(name: "NIOEmbedded", package: "swift-nio"),
]
```

### Modifications:

- Fix compiler directive using in AsyncTestingChannel.swift to include
an extension

### Result:

Packages can compile to wasm without manually excluding the NIOEmbedded
dependency.

### Testing performed

- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOEmbedded` compiles, which demonstrates proper elision of source files
in NIOEmbedded that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151287289).
2026-01-22 18:58:24 +00:00
scottmarchant c337170d91 chore: Elide mutex variable from Lock class when it is unused (#3483)
### Motivation:

In reviewing a copy of this file in swift-log, @czechboy0
[noticed](https://github.com/apple/swift-log/pull/398#discussion_r2685605800)
that the `mutex` variable is essentially unused and unnecessarily
allocated for certain conditions. It is possible the compiler elided
usage. But given the unconditional variable reference in the `deinit`,
the compiler may not be able to.

This change ensures the `mutex` property is completely elided except in
the conditions where it is used.

### Modifications:

- Adjusted compiler directive pattern to completely elide the `mutex`
property for conditions where it would be unused.
- Adjusted `deinit` to avoid referencing `mutex` unless it is compiled
into the `Lock` class

### Result:

The `mutex` property is no longer allocated or even compiled into the
`Lock` class for unsupported configurations. All unit tests and checks
pass.

### Research:

The `deinit` used to have a blanket call to `mutex.deallocate()`. This
has been moved into the platform-specific checks within the `deinit`.
This allows complete elision of the `mutex` property altogether. The
`_runtime(_multithreaded)` condition [appears to be rooted to this
implementation](https://github.com/swiftlang/swift/blob/ffc51b914602765c5d680241796dbd3c3711fa6b/lib/Basic/LangOptions.cpp#L490).
Diving deeper, all [operating systems in this
list](https://github.com/swiftlang/swift/blob/ffc51b914602765c5d680241796dbd3c3711fa6b/lib/Basic/LangOptions.cpp#L554)
except for UnknownOS and WASI result in `_runtime(_multithreaded)`
returning true. That means that `OpenBSD` (and many other operating
systems besides windows) were almost certainly using the `#elseif
(compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) &&
_runtime(_multithreaded))` condition in the `deinit`. In conclusion,
moving `mutex.deallocate()` up into the conditional clauses inside
`deinit` should be identical to the previous implementation for all
operating systems except `llvm::Triple::UnknownOS`. And
`llvm::Triple::UnknownOS` is likely not to have every compiled anyways
due to the [check on line
32](https://github.com/apple/swift-nio/blob/main/Sources/NIOConcurrencyHelpers/lock.swift#L32).

So in summary, it is expected that this clean up will compile identical
to the previous implementation for all platforms except WASI platforms
that don't have pthread support. For non-pthread WASI platforms, the
unused `mutex` is properly elided from compilation altogether.

### Testing Done:

- Confirmed that unit tests pass locally using Xcode
- Verified [PR checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21149729751)
2026-01-22 17:57:10 +00:00