Skip to content

Initialize out SafeHandles before publishing them - #1878

Merged
Jevan Saks (jevansaks) merged 1 commit into
mainfrom
jevansaks-issue-1877-investigation
Nov 9, 2026
Merged

Jevan Saks (jevansaks) merged 1 commit into
mainfrom
jevansaks-issue-1877-investigation

Conversation

@jevansaks

@jevansaks Jevan Saks (jevansaks) commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Summary

Relates to #1877.

Generated friendly overloads currently assign a newly allocated safe handle to the caller's out parameter before invoking native code, then read that parameter again for Marshal.InitHandle. When the caller passes a field, concurrent or reentrant code can clear or replace that field during the native call, causing initialization to target null or a different object.

Keep the allocated safe handle in a private local, initialize that local after the native call, and only then assign it to the out parameter. This also avoids exposing the uninitialized safe handle to premature disposal. Allocation still happens before acquiring the native resource, preserving the existing allocation-failure protection. The path for targets without Marshal.InitHandle is unchanged.

Generated code before and after

For the SubscribeServiceChangeNotifications friendly overload used in #1877, the relevant generated statements are shown below. The unchanged input-handle lifetime management, method signature, and surrounding try/finally are omitted; namespace qualifications and line wrapping are simplified for readability.

Before

PSC_NOTIFICATION_REGISTRATION pSubscriptionLocal;
pSubscription = new UnsubscribeServiceChangeNotificationsSafeHandle(
    default, ownsHandle: true);
uint __result = PInvoke.SubscribeServiceChangeNotifications(
    hServiceLocal, eEventType, pCallback, pCallbackContext, &pSubscriptionLocal);
Marshal.InitHandle(pSubscription, pSubscriptionLocal);
return __result;

When the caller passes out _dbSubscription, pSubscription aliases that field. Clearing or replacing _dbSubscription during the native call changes the object passed to Marshal.InitHandle.

After

PSC_NOTIFICATION_REGISTRATION pSubscriptionLocal;
UnsubscribeServiceChangeNotificationsSafeHandle pSubscriptionSafeHandle =
    new UnsubscribeServiceChangeNotificationsSafeHandle(
        default, ownsHandle: true);
uint __result = PInvoke.SubscribeServiceChangeNotifications(
    hServiceLocal, eEventType, pCallback, pCallbackContext, &pSubscriptionLocal);
Marshal.InitHandle(pSubscriptionSafeHandle, pSubscriptionLocal);
pSubscription = pSubscriptionSafeHandle;
return __result;

Initialization now targets the private local regardless of changes to the caller's field. The out parameter receives the safe handle only after initialization.

Remaining limitation

This does not guarantee that a subscription handle is available when a native notification callback fires before registration completes. Callers must still coordinate callback processing, registration, and disposal; publishing an uninitialized safe handle early did not provide a usable handle during that window.

Validation

  • Existing UseInitHandleApiWhenPossible tests: 6 passed.
  • Existing VerifySignature case for WlanOpenHandle: passed, including generated-code compilation.
  • Re-ran the external .NET 10 reproducer against the rebuilt generator: 10,000 calls to SubscribeServiceChangeNotifications with concurrent clearing of the output field completed without NullReferenceException (the original generator reproduced the exception). An invalid manager handle ensured no native subscriptions were created.
  • No unit tests added, as requested.

@jevansaks
Jevan Saks (jevansaks) marked this pull request as ready for review November 9, 2026 22:44
@jevansaks
Jevan Saks (jevansaks) enabled auto-merge (squash) November 9, 2026 22:45
@jevansaks
Jevan Saks (jevansaks) merged commit aa9216f into main Nov 9, 2026
20 checks passed
@jevansaks
Jevan Saks (jevansaks) deleted the jevansaks-issue-1877-investigation branch November 9, 2026 23:42
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.

2 participants