Repository navigation
fix: dangling pointer crash in mutating re namespace under Release builds - #8
Merged
Merged
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
EXC_BAD_ACCESScrash in every mutatingreAPI (e.g.array.re.removeDuplicates(),string.re.trim(),array.re.prepend(_:),date.re.year = ...) that only shows up in optimized (Release) builds.UnsafeMutablePointer. They hold the value, andregains a_modifyaccessor that movesselfinto the wrapper, yields it, and writes it back, so in-place mutation still avoids an extra copy-on-write copy.Hashableoverload forremoveDuplicates()/removingDuplicates()(previously O(n²) for every element type).Memory,DataAES andDatazlib/gzip, plus a Mach thread-port leak inUIDevice.re.appCPUUsage. See Other fixes from the audit.Problem
Symptom
A production app crashed in Release builds on a background queue with:
at this call site:
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:
The pointer passed to the
withUnsafeMutablePointerclosure is only valid for the duration of that closure. Returning it with{ $0 }and using it later throughbase.pointeeis undefined behavior.-Onone, the caller happens to pass the address of the variable's own stack slot, and the access stays open for the wholeresult.re.removeDuplicates()expression. So the pointer happens to stay valid, and Debug builds work.-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. Afterre's getter returns,basepoints at dead stack memory, and the nextbase.pointeeread 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:ReerReferenceDate,URL,CATransform3D, ...ReerReferenceGenericArray,SetReerReferenceGeneric2DictionaryReerForMutableCollectionMutableCollectionsReerForRangeReplaceableCollectionRangeReplaceableCollections, includingStringFix
All five wrappers now store the value instead of a pointer, and
readds a_modifyaccessor:When you write
result.re.removeDuplicates(), the compiler now uses_modify:consume selfmoves the value into the wrapper, so the buffer stays uniquely referenced.yield &wrapperlends the wrapper to the mutating method, which mutateswrapper.basein place. No copy-on-write copy happens, because there's only one reference.deferwrites the result back toself. This also runs if the caller unwinds, and the compiler checks thatselfis reinitialized on every path afterconsume.No pointers are stored anywhere, so there is nothing left to dangle.
consumerequires Swift 5.9, which already matches the package's minimum tools version and the podspec'sswift_version.Other changes:
base.pointeewithbasein all extensions (171 occurrences).Dictionary'ssubscript(path: String)getter called the mutatingregetter 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.rekeeps itsmutating get, so which call sites compile and whichreoverload is picked stay exactly the same.O(n) de-duplication
Added
T: Hashableoverloads, picked automatically over theEquatableones:ReerReferenceGeneric.removeDuplicates()usesSet.insert(_:).inserted+removeAll(where:), in place.ReerGeneric.removingDuplicates()usesSet+filter. This needs its own overload, because the existingEquatableversion callsremoveDuplicates()from anEquatable-only generic context, which always binds to the O(n²) overload.Both keep first-occurrence order. Element types that are
Equatablebut notHashablekeep 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.246ffce)mergeStickerson a localvar(5000 iterations)EXC_BAD_ACCESSinobjc_retainDispatchQueue.concurrentPerformString.re.trim()Array.re.prepend+re.swapAtTests
ArrayExtensionsTests:testMutatingNamespaceOnLocalVariableandtestMutatingNamespaceOnBackgroundQueuecover the crashing call pattern.testMutatingNamespaceDoesNotCopyBufferchecks that the array's buffer address is unchanged afterarray.re.swapAt, so there's no copy-on-write copy.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.Other fixes from the audit
I scanned the whole repo for
withUnsafe*/&valuepointer conversions whose pointer is used after it stops being valid. Unlike therewrappers, 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 fromwithUnsafePointer(to: &v) { UnsafeRawPointer($0) }. That's the same escape as therewrappers.bytes(ofVal:),string(ofVal:)andmemoryType()then dereferenced it (memoryType()readsbase + 15/base + 7to classify the string storage, andMemory.pointer(ofRef:)relies on it for strings). They now read the bytes inside thewithUnsafePointer/withUnsafeBytes(of:)closure.memoryType()also now returns.unknowinstead of reading out of bounds on platforms whereStringis 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/aesDecryptThe output buffer was passed to
CCCryptasresult.withUnsafeMutableBytes { $0.baseAddress }, which escapes the pointer. It only worked because a ≥16-byteDatais heap-backed.result.withUnsafeMutableBytesnow wraps the wholeCCCryptcall, and the length comes fromresultBytes.countinstead of readingresult.countwhileresultis borrowed mutably, which would violate exclusivity.Data.re.zlibCompressed/zlibDecompressed/gzipCompressed/gzipDecompresseddeflateInit_/inflateInit_store thez_streamaddress in zlib's internal state, and every laterdeflate/inflate/*Endcall checks that it gets the same address (deflateStateCheck/inflateStateCheck).&streamonly guarantees an address for the duration of a single call, not the same address across calls. If it ever changed, these would fail withZ_STREAM_ERRORand returnnil. The stream is now heap-allocated (UnsafeMutablePointer<z_stream>), so its address is fixed, and it's freed withdefer.UIDevice.re.appCPUUsage(Mach resource leaks, not a pointer-scope issue)threadActPointers()/threadBasicInfos()had three leaks:vm_deallocatewas called withvm_address_t(array.pointee), the first thread port name, instead of the array's address. So the thread array returned bytask_threadswas never freed, and a bogus address was passed tovm_deallocateinstead.task_threadsadds for every thread was never released withmach_port_deallocate, so each call leaked one reference per thread.thread_infobuffers allocated withallocate(capacity:)were never deallocated.Thread info is now read into a stack
thread_basic_info, ports are released withdefer, and the array is freed at its real address. The existing behavior of returning[]if anythread_infocall fails is kept.Tests added for the audit
UIDeviceExtensionsTests.testAppCPUUsageDoesNotLeakThreadPortscallsappCPUUsage500 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 severaldeflate/inflatecalls on the same stream.DataExtensionsTests.testAesLargeData: 100 KB AES-256-CBC round trip.MemoryTests.testStringMemoryType: small, literal and heap strings map to.taggedPointer,.textand.heap.MemoryTests.testBytesOfValue: byte and string dumps of a knownInt64.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:basechanged fromUnsafeMutablePointer<Base>toBase. Replacebase.pointeewithbasein custom extensions.init(_ base: inout Base)changed toinit(_ base: Base).basemust now bemutating. 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).