Skip to content

[src/runtime] Don't allow native code to resolve a weak reference for an object in the finalizer queue. #23072

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

rolfbjarne
Copy link
Member

@rolfbjarne rolfbjarne commented Jun 18, 2025

The following happens:

  1. An instance of a custom NSObject subclass is created, with both a native instance
    and the corresponding managed wrapper.

  2. Native code creates a weak reference to the native instance.

  3. No other managed code references the managed instance, and there's no non-weak
    native reference to the native instance, so the GC schedules the managed instance
    for finalization.

  4. Native code fetches the native instance from the weak reference.

  5. Native code thinks it can do whatever it wants with the native instance, because
    it got a perfectly valid (and retained) native instance. Unfortunately, there's no way
    to stop the managed instance from being finalized (which happens on a background
    thread anyway, so there's no thread-safe way to do it), which means havoc ensues.

The most frequent manifestation of this problem has been like this:

ObjCRuntime.RuntimeException: Failed to marshal the Objective-C object 0x13d566800 (type: Microsoft_Maui_Platform_MauiTextField). Could not find an existing managed instance for this object, nor was it possible to create a new managed instance (because the type 'Microsoft.Maui.Platform.MauiTextField' does not have a constructor that takes one NativeHandle argument).
   at ObjCRuntime.Runtime.MissingCtor(IntPtr , IntPtr , Type , MissingCtorResolution , IntPtr , RuntimeMethodHandle )
   at ObjCRuntime.Runtime.ConstructNSObject[NSObject](IntPtr , Type , MissingCtorResolution , IntPtr , RuntimeMethodHandle )
   at ObjCRuntime.Runtime.ConstructNSObject[NSObject](IntPtr , Type , MissingCtorResolution )
   at ObjCRuntime.Runtime.ConstructNSObject(IntPtr , IntPtr , MissingCtorResolution )
   at ObjCRuntime.Runtime.GetNSObject(IntPtr , MissingCtorResolution , Boolean )
   at ObjCRuntime.Runtime.GetNSObject(IntPtr )
   at ObjCRuntime.Runtime.InvokeConformsToProtocol(IntPtr , IntPtr )
   at ObjCRuntime.Runtime.invoke_conforms_to_protocol(IntPtr obj, IntPtr protocol, IntPtr* exception_gchandle)
   Exception_EndOfInnerExceptionStack

but other problems can also occur.

This is a rather complicated issue to fix, because:

  • There's no way to be notified when native code creates a weak reference to a
    native instance.
  • There's not even a way to know if anybody has a weak reference to a native
    instance.
  • I also looked into manually clearing the weak references for a native
    instance, but that's not possible either.

However, it is possible to basically say "nope!" when native code tries to
fetch a native instance from a weak reference:

We override the '[NSObject retainWeakReference]' method for all custom
NSObject subclasses, and return FALSE if the corresponding managed object has
been scheduled for finalization (otherwise call the base class implementation).

The '[NSObject retainWeakReference]' method is public, but it's not
documented how it's supposed to behave. Fortunately, the corresponding source
code
is public, so we can figure out the semantics ourselves: return
TRUE if the object can be / was retained, FALSE otherwise.

Might also fix the following issues:

rolfbjarne and others added 2 commits June 18, 2025 15:03
… an object in the finalizer queue.

The following happens:

1. An instance of a custom NSObject subclass is created, with both a native instance
   and the corresponding managed wrapper.

2. Native code creates a weak reference to the native instance.

3. No other managed code references the managed instance, and there's no non-weak
   native reference to the native instance, so the GC schedules the managed instance
   for finalization.

4. Native code fetches the native instance from the weak reference.

5. Native code thinks it can do whatever it wants with the native instance, because
   it got a perfectly valid (and retained) native instance. Unfortunately, there's no way
   to stop the managed instance from being finalized (which happens on a background
   thread anyway, so there's no thread-safe way to do it), which means havoc ensues.

The most frequent manifestation of this problem has been like this:

    ObjCRuntime.RuntimeException: Failed to marshal the Objective-C object 0x13d566800 (type: Microsoft_Maui_Platform_MauiTextField). Could not find an existing managed instance for this object, nor was it possible to create a new managed instance (because the type 'Microsoft.Maui.Platform.MauiTextField' does not have a constructor that takes one NativeHandle argument).
       at ObjCRuntime.Runtime.MissingCtor(IntPtr , IntPtr , Type , MissingCtorResolution , IntPtr , RuntimeMethodHandle )
       at ObjCRuntime.Runtime.ConstructNSObject[NSObject](IntPtr , Type , MissingCtorResolution , IntPtr , RuntimeMethodHandle )
       at ObjCRuntime.Runtime.ConstructNSObject[NSObject](IntPtr , Type , MissingCtorResolution )
       at ObjCRuntime.Runtime.ConstructNSObject(IntPtr , IntPtr , MissingCtorResolution )
       at ObjCRuntime.Runtime.GetNSObject(IntPtr , MissingCtorResolution , Boolean )
       at ObjCRuntime.Runtime.GetNSObject(IntPtr )
       at ObjCRuntime.Runtime.InvokeConformsToProtocol(IntPtr , IntPtr )
       at ObjCRuntime.Runtime.invoke_conforms_to_protocol(IntPtr obj, IntPtr protocol, IntPtr* exception_gchandle)
       Exception_EndOfInnerExceptionStack

but other problems can also occur.

This is a rather complicated issue to fix, because:

* There's no way to be notified when native code creates a weak reference to a
  native instance.
* There's not even a way to know if anybody has a weak reference to a native
  instance.
* I also looked into manually clearing the weak references for a native
  instance, but that's not possible either.

However, it is possible to basically say "nope!" when native code tries to
fetch a native instance from a weak reference:

We override the '[NSObject retainWeakReference]' method for all custom
NSObject subclasses, and return FALSE if the corresponding managed object has
been scheduled for finalization (otherwise call the base class implementation).

The ['[NSObject retainWeakReference]'][1] method is public, but it's not
documented how it's supposed to behave. Fortunately, the corresponding [source
code][2] is public, so we can figure out the semantics ourselves: return
`TRUE` if the object can be / was retained, `FALSE` otherwise.

* Fixes #21648.
* Fixes dotnet/maui#21485.
* Fixes #19076.

Might also fix the following issues:

* #22867
* #19579
* #4207
* https://bugzilla.xamarin.com/show_bug.cgi?id=34242 (https://web.archive.org/web/20170630214134/https://bugzilla.xamarin.com/show_bug.cgi?id=34242)

[1]: https://developer.apple.com/documentation/foundation/nsproxy/retainweakreference
[2]: https://github.com/apple-oss-distributions/objc4/blob/f126469408dc82bd3f327217ae678fd0e6e3b37c/runtime/NSObject.mm#L539-L541
@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2
Copy link
Collaborator

💻 [CI Build #e4bdd15] Tests on macOS M1 - Mac Ventura (13) passed 💻

All tests on macOS M1 - Mac Ventura (13) passed.

Pipeline on Agent
Hash: e4bdd15f74fcd98bdac87dcd78358c14e9589858 [PR build]

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2
Copy link
Collaborator

💻 [CI Build #e4bdd15] Tests on macOS arm64 - Mac Sequoia (15) passed 💻

All tests on macOS arm64 - Mac Sequoia (15) passed.

Pipeline on Agent
Hash: e4bdd15f74fcd98bdac87dcd78358c14e9589858 [PR build]

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2
Copy link
Collaborator

🔥 [CI Build #e4bdd15] Test results 🔥

Test results

❌ Tests failed on VSTS: test results

0 tests crashed, 14 tests failed, 107 tests passed.

Failures

❌ monotouch tests (iOS)

7 tests failed, 3 tests passed.
  • monotouch-test/iOS - simulator/Debug (LinkSdk): Crashed
  • monotouch-test/iOS - simulator/Debug (static registrar): Crashed
  • monotouch-test/iOS - simulator/Release (all optimizations): Crashed
  • monotouch-test/iOS - simulator/Debug (ARM64): Crashed
  • monotouch-test/iOS - simulator/Debug (managed static registrar): Crashed
  • monotouch-test/iOS - simulator/Release (managed static registrar, all optimizations): Crashed
  • monotouch-test/iOS - simulator/Debug (interpreter): Crashed

Html Report (VSDrops) Download

❌ monotouch tests (tvOS)

7 tests failed, 1 tests passed.
  • monotouch-test/tvOS - simulator/Debug: Crashed
  • monotouch-test/tvOS - simulator/Debug (LinkSdk): Crashed
  • monotouch-test/tvOS - simulator/Debug (static registrar): Crashed
  • monotouch-test/tvOS - simulator/Release (all optimizations): Crashed
  • monotouch-test/tvOS - simulator/Debug (managed static registrar): Crashed
  • monotouch-test/tvOS - simulator/Release (managed static registrar, all optimizations): Crashed
  • monotouch-test/tvOS - simulator/Debug (interpreter): Crashed

Html Report (VSDrops) Download

Successes

✅ cecil: All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (iOS): All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (MacCatalyst): All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (macOS): All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (Multiple platforms): All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (tvOS): All 1 tests passed. Html Report (VSDrops) Download
✅ framework: All 2 tests passed. Html Report (VSDrops) Download
✅ fsharp: All 4 tests passed. Html Report (VSDrops) Download
✅ generator: All 5 tests passed. Html Report (VSDrops) Download
✅ interdependent-binding-projects: All 4 tests passed. Html Report (VSDrops) Download
✅ introspection: All 4 tests passed. Html Report (VSDrops) Download
✅ linker: All 44 tests passed. Html Report (VSDrops) Download
✅ monotouch (MacCatalyst): All 15 tests passed. Html Report (VSDrops) Download
✅ monotouch (macOS): All 9 tests passed. Html Report (VSDrops) Download
✅ msbuild: All 2 tests passed. Html Report (VSDrops) Download
✅ windows: All 3 tests passed. Html Report (VSDrops) Download
✅ xcframework: All 4 tests passed. Html Report (VSDrops) Download
✅ xtro: All 1 tests passed. Html Report (VSDrops) Download

Pipeline on Agent
Hash: e4bdd15f74fcd98bdac87dcd78358c14e9589858 [PR build]

@vs-mobiletools-engineering-service2
Copy link
Collaborator

✅ [CI Build #b4ec021] Build passed (Build packages) ✅

Pipeline on Agent
Hash: b4ec0219cf767f14959a3a5c8db9d29fee18b587 [PR build]

@vs-mobiletools-engineering-service2
Copy link
Collaborator

✅ [PR Build #b4ec021] Build passed (Detect API changes) ✅

Pipeline on Agent
Hash: b4ec0219cf767f14959a3a5c8db9d29fee18b587 [PR build]

@vs-mobiletools-engineering-service2
Copy link
Collaborator

✅ API diff for current PR / commit

.NET ( No breaking changes )

✅ API diff vs stable

.NET ( No breaking changes )

ℹ️ Generator diff

Generator Diff: vsdrops (html) vsdrops (raw diff) gist (raw diff) - Please review changes)

Pipeline on Agent
Hash: b4ec0219cf767f14959a3a5c8db9d29fee18b587 [PR build]

@vs-mobiletools-engineering-service2
Copy link
Collaborator

✅ [CI Build #b4ec021] Build passed (Build macOS tests) ✅

Pipeline on Agent
Hash: b4ec0219cf767f14959a3a5c8db9d29fee18b587 [PR build]

@vs-mobiletools-engineering-service2
Copy link
Collaborator

💻 [CI Build #b4ec021] Tests on macOS X64 - Mac Sonoma (14) passed 💻

All tests on macOS X64 - Mac Sonoma (14) passed.

Pipeline on Agent
Hash: b4ec0219cf767f14959a3a5c8db9d29fee18b587 [PR build]

@vs-mobiletools-engineering-service2
Copy link
Collaborator

💻 [CI Build #b4ec021] Tests on macOS M1 - Mac Monterey (12) passed 💻

All tests on macOS M1 - Mac Monterey (12) passed.

Pipeline on Agent
Hash: b4ec0219cf767f14959a3a5c8db9d29fee18b587 [PR build]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
5 participants