Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash dereferencing unowned _publisher in KVO trampoline #112

Merged

Conversation

nolanw
Copy link
Collaborator

@nolanw nolanw commented Aug 16, 2024

A FoilDefaultStorage{,Optional} can deallocate while its ObserverTrampoline sticks around long enough to receive a KVO notification. (I'm not sure how.) When this happens, the attempt to dereference the captured _publisher crashes.

I don't know how to write a reliable test for the test suite, but I can reproduce the crash ~instantly with this code (e.g. pasted into a new test) in Xcode 16.0 beta 5 on an iPhone 8 running iOS 16.7.8 (as well as in iOS 15, 16, 17, and 18 simulators I have kicking around):

DispatchQueue.global().async {
    var storage: FoilDefaultStorageOptional<Int>?
    while true {
        storage = .init(key: "aloha")
    }
}
while true {
    UserDefaults.standard.set(Int.random(in: Int.min...Int.max), forKey: "aloha")
}

That's an admittedly silly test, but I'm seeing crashes in the wild attempting to dereference _publisher.

The obvious fix to me is to capture _publisher as either weak or strong, instead of unowned. A strong reference doesn't cause a cycle, so I chose it over the theoretically slower weak reference.

nolanw added a commit to happybits/Foil that referenced this pull request Aug 16, 2024
Submitted upstream as jessesquires#112 but upstream latest changes the name of the property wrappers and I'm not bothering to do that here.
Copy link
Owner

@jessesquires jessesquires left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ha, wow. What an edge case. Thanks for finding and fixing @nolanw! 💯 🙌🏼

  • I left one comment/question about the capture.
  • Also, could you add a changelog entry for this? Let's add a new 5.1.2 version.

After we merge this, I'll tag a new release. 😄

Sources/FoilDefaultStorage.swift Outdated Show resolved Hide resolved
Copy link
Owner

@jessesquires jessesquires left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome. thanks @nolanw ! 💯

@jessesquires jessesquires merged commit bcdc8c1 into jessesquires:main Aug 16, 2024
9 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants