Skip to content

fix: dangling pointer crash in mutating re namespace under Release builds - #8

Merged
vnixx merged 3 commits into
mainfrom
fix/re-namespace-dangling-pointer
Oct 16, 2026
Merged

vnixx merged 3 commits into
mainfrom
fix/re-namespace-dangling-pointer

Conversation

@vnixx

@vnixx vnixx commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Fix an EXC_BAD_ACCESS crash in every mutating re API (e.g. array.re.removeDuplicates(), string.re.trim(), array.re.prepend(_:), date.re.year = ...) that only shows up in optimized (Release) builds.
  • The mutating wrappers no longer store an escaped UnsafeMutablePointer. They hold the value, and re gains a _modify accessor that moves self into the wrapper, yields it, and writes it back, so in-place mutation still avoids an extra copy-on-write copy.
  • Also includes an O(n) Hashable overload for removeDuplicates() / removingDuplicates() (previously O(n²) for every element type).
  • A repo-wide audit for the same class of bug (pointers used outside their valid scope) found and fixed three more spots in Memory, Data AES and Data zlib/gzip, plus a Mach thread-port leak in UIDevice.re.appCPUUsage. See Other fixes from the audit.

Problem

Symptom

A production app crashed in Release builds on a background queue with:

Thread 9: EXC_BAD_ACCESS (code=1, address=0x8)

at this call site:

static func mergeStickers(recentUsed: [Sticker], recommended: [Sticker], hiStickers: [Sticker]) -> [Sticker] {
    var result = recentUsed + recommended + hiStickers
    result.re.removeDuplicates()   // <- crash
    return result
}

The same code never crashes in Debug. Running the app's unit tests for it 100 times in a row in Debug passed every time.

Root cause

The mutating namespace wrappers captured the address of the value like this:

public struct ReerReferenceGeneric<Base, T> {
    public let base: UnsafeMutablePointer<Base>
    public init(_ base: inout Base) {
        self.base = withUnsafeMutablePointer(to: &base) { $0 }   // pointer escapes the closure
    }
}

var re: ReerReferenceGeneric<Self, T> {
    mutating get { return ReerReferenceGeneric(&self) }
    set {}
}

The pointer passed to the withUnsafeMutablePointer closure is only valid for the duration of that closure. Returning it with { $0 } and using it later through base.pointee is undefined behavior.

  • In -Onone, the caller happens to pass the address of the variable's own stack slot, and the access stays open for the whole result.re.removeDuplicates() expression. So the pointer happens to stay valid, and Debug builds work.
  • With optimizations (-O / -Osize + whole-module optimization), the compiler is free to keep the value in registers or in a temporary that only lives inside the closure. After re's getter returns, base points at dead stack memory, and the next base.pointee read or write dereferences garbage. That's the crash in _ArrayBuffer / objc_retain.

This isn't specific to removeDuplicates. Every API built on these wrappers was affected:

Wrapper Used by
ReerReference Date, URL, CATransform3D, ...
ReerReferenceGeneric Array, Set
ReerReferenceGeneric2 Dictionary
ReerForMutableCollection all MutableCollections
ReerForRangeReplaceableCollection all RangeReplaceableCollections, including String

Fix

All five wrappers now store the value instead of a pointer, and re adds a _modify accessor:

public struct ReerReferenceGeneric<Base, T> {
    public var base: Base
    public init(_ base: Base) { self.base = base }
}

var re: ReerReferenceGeneric<Self, T> {
    mutating get { return ReerReferenceGeneric(self) }
    set { self = newValue.base }
    _modify {
        var wrapper = ReerReferenceGeneric<Self, T>(consume self)
        defer { self = wrapper.base }
        yield &wrapper
    }
}

When you write result.re.removeDuplicates(), the compiler now uses _modify:

  1. consume self moves the value into the wrapper, so the buffer stays uniquely referenced.
  2. yield &wrapper lends the wrapper to the mutating method, which mutates wrapper.base in place. No copy-on-write copy happens, because there's only one reference.
  3. defer writes the result back to self. This also runs if the caller unwinds, and the compiler checks that self is reinitialized on every path after consume.

No pointers are stored anywhere, so there is nothing left to dangle. consume requires Swift 5.9, which already matches the package's minimum tools version and the podspec's swift_version.

Other changes:

  • Replaced base.pointee with base in all extensions (171 occurrences).
  • Dictionary's subscript(path: String) getter called the mutating re getter from a non-mutating context, which the pointer used to hide. It now reads from a local copy. That's only a retain, not a real copy.
  • re keeps its mutating get, so which call sites compile and which re overload is picked stay exactly the same.

O(n) de-duplication

Added T: Hashable overloads, picked automatically over the Equatable ones:

  • ReerReferenceGeneric.removeDuplicates() uses Set.insert(_:).inserted + removeAll(where:), in place.
  • ReerGeneric.removingDuplicates() uses Set + filter. This needs its own overload, because the existing Equatable version calls removeDuplicates() from an Equatable-only generic context, which always binds to the O(n²) overload.

Both keep first-occurrence order. Element types that are Equatable but not Hashable keep the existing O(n²) fallback.

Verification

Reproduction (before / after)

A minimal SwiftPM executable that depends on ReerKit by path, built with swift build -c release. That's how an app integrating ReerKit through SPM builds it in Release: ReerKit gets -O + WMO, and the caller gets -Osize, matching the crashing app's Release settings. The call site is copied verbatim from the crashing app.

Scenario Before (246ffce) After After + Address Sanitizer
mergeStickers on a local var (5000 iterations) EXC_BAD_ACCESS in objc_retain pass pass
Same, on DispatchQueue.concurrentPerform crash pass pass
String.re.trim() crash pass pass
Array.re.prepend + re.swapAt crash pass pass

Tests

  • Added to ArrayExtensionsTests:
    • testMutatingNamespaceOnLocalVariable and testMutatingNamespaceOnBackgroundQueue cover the crashing call pattern.
    • testMutatingNamespaceDoesNotCopyBuffer checks that the array's buffer address is unchanged after array.re.swapAt, so there's no copy-on-write copy.
  • Full iOS test suite (ReerKit-iOS, iPhone simulator): the set of failing tests is identical before and after this change. The same 24 tests fail on both, and they're environment-dependent locale and snapshot tests unrelated to this PR. Everything else passes.

Note: the in-repo Xcode test target can't reproduce the crash even in Release, because @testable import forces -enable-testing on the library, which changes what the optimizer does. The SwiftPM Release reproduction above is the authoritative check.

Other fixes from the audit

I scanned the whole repo for withUnsafe* / &value pointer conversions whose pointer is used after it stops being valid. Unlike the re wrappers, none of these crash with the current compiler in my Release + ASan runs. They're latent undefined behavior that only works because of how the compiler currently lays things out, so they're fixed here before a compiler change exposes them.

Memory (bytes(ofVal:), string(ofVal:), String.re.memoryType())

Memory.pointer(ofVal:) returns the pointer from withUnsafePointer(to: &v) { UnsafeRawPointer($0) }. That's the same escape as the re wrappers. bytes(ofVal:), string(ofVal:) and memoryType() then dereferenced it (memoryType() reads base + 15 / base + 7 to classify the string storage, and Memory.pointer(ofRef:) relies on it for strings). They now read the bytes inside the withUnsafePointer / withUnsafeBytes(of:) closure. memoryType() also now returns .unknow instead of reading out of bounds on platforms where String is smaller than 16 bytes (arm64_32 on watchOS). pointer(ofVal:) is kept for printing addresses, with a doc warning not to dereference it.

Data.re.aesEncrypt / aesDecrypt

The output buffer was passed to CCCrypt as result.withUnsafeMutableBytes { $0.baseAddress }, which escapes the pointer. It only worked because a ≥16-byte Data is heap-backed. result.withUnsafeMutableBytes now wraps the whole CCCrypt call, and the length comes from resultBytes.count instead of reading result.count while result is borrowed mutably, which would violate exclusivity.

Data.re.zlibCompressed / zlibDecompressed / gzipCompressed / gzipDecompressed

deflateInit_ / inflateInit_ store the z_stream address in zlib's internal state, and every later deflate / inflate / *End call checks that it gets the same address (deflateStateCheck / inflateStateCheck). &stream only guarantees an address for the duration of a single call, not the same address across calls. If it ever changed, these would fail with Z_STREAM_ERROR and return nil. The stream is now heap-allocated (UnsafeMutablePointer<z_stream>), so its address is fixed, and it's freed with defer.

UIDevice.re.appCPUUsage (Mach resource leaks, not a pointer-scope issue)

threadActPointers() / threadBasicInfos() had three leaks:

  • vm_deallocate was called with vm_address_t(array.pointee), the first thread port name, instead of the array's address. So the thread array returned by task_threads was never freed, and a bogus address was passed to vm_deallocate instead.
  • The send right that task_threads adds for every thread was never released with mach_port_deallocate, so each call leaked one reference per thread.
  • The thread_info buffers allocated with allocate(capacity:) were never deallocated.

Thread info is now read into a stack thread_basic_info, ports are released with defer, and the array is freed at its real address. The existing behavior of returning [] if any thread_info call fails is kept.

Tests added for the audit

  • UIDeviceExtensionsTests.testAppCPUUsageDoesNotLeakThreadPorts calls appCPUUsage 500 times and checks that the current thread port's send-right reference count doesn't change. Before this PR it goes from 4 to 504, one leaked reference per call. After, it stays the same.
  • DataExtensionsTests.testCompressionAcrossMultipleChunks: 100 KB of random data, so zlib/gzip need several deflate / inflate calls on the same stream.
  • DataExtensionsTests.testAesLargeData: 100 KB AES-256-CBC round trip.
  • MemoryTests.testStringMemoryType: small, literal and heap strings map to .taggedPointer, .text and .heap.
  • MemoryTests.testBytesOfValue: byte and string dumps of a known Int64.

All of these also pass in the SwiftPM Release reproduction with and without Address Sanitizer. The full iOS test suite still has exactly the same 24 pre-existing failures and no new ones.

Breaking changes

The call-site API is unchanged. x.re.someMutatingMethod() works exactly as before. Code that extends these wrappers is affected:

  • base changed from UnsafeMutablePointer<Base> to Base. Replace base.pointee with base in custom extensions.
  • init(_ base: inout Base) changed to init(_ base: Base).
  • A custom extension method that writes to base must now be mutating. Before, writing through the pointer compiled even in non-mutating methods.

Because of this, this should probably go out as a minor version bump (e.g. 1.3.0).

vnixx and others added 3 commits October 16, 2026 11:07
Co-authored-by: Cursor <cursoragent@cursor.com>
The mutating wrappers (ReerReference, ReerReferenceGeneric, ReerReferenceGeneric2,
ReerForMutableCollection, ReerForRangeReplaceableCollection) stored a pointer that
escaped withUnsafeMutablePointer, which is undefined behavior and crashes with
EXC_BAD_ACCESS once the optimizer moves the value. Wrappers now hold the value
and `re` provides a _modify accessor that consumes self, yields the wrapper and
writes it back, keeping in-place mutation without an extra CoW copy.

Co-authored-by: Cursor <cursoragent@cursor.com>
- Memory: read value bytes inside withUnsafePointer/withUnsafeBytes instead of
  dereferencing a pointer escaped from the closure (bytes/string(ofVal:),
  String memoryType()).
- Data AES: pass CCCrypt the output buffer from an enclosing
  withUnsafeMutableBytes instead of an escaped baseAddress.
- Data zlib/gzip: heap-allocate z_stream, since zlib keeps a back pointer to it
  and `&stream` doesn't guarantee a stable address across calls.
- UIDevice appCPUUsage: release thread ports from task_threads, deallocate the
  thread array at its real address, and stop leaking thread_info buffers.

Co-authored-by: Cursor <cursoragent@cursor.com>
@vnixx
vnixx merged commit 52237a9 into main Oct 16, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant