Skip to content

[src] Keep native callback owners alive during synchronous enumeration - #26704

Merged
rolfbjarne merged 8 commits into
mainfrom
dev/rolf/audit-native-enumerator-lifetimes
Oct 28, 2026
Merged

rolfbjarne merged 8 commits into
mainfrom
dev/rolf/audit-native-enumerator-lifetimes

Conversation

@rolfbjarne

Copy link
Copy Markdown
Member

Summary

Follow up on the lifetime audit prompted by #26545 and #26676. Native enumeration receives only the owner's handle; rooting the callback does not necessarily keep its managed owner alive while callbacks allocate or trigger GC.

Add 37 GC.KeepAlive (this) guards after synchronous native calls: the 29 additional enumerators identified by the audit, font sorting, pre-shared-key access, and six adjacent callback operations. Preserve native return values and keep owners alive before callback state is released. The ImageIO fix in #26676 is not duplicated.

Fix DispatchQueue.Submit by retaining its callback/owner tuple until all iterations finish, freeing the handle once in finally, and using the matching Action<int> delegate type.

Correct related defects encountered while exercising these APIs: native boolean callback return types, borrowed metadata ownership, peer certificate conversion, the signature-algorithm success check, pre-shared-key delegate/ownership handling, and recursive WebSocket response header forwarding.

Coverage

Add forced-GC regressions for path application, caret enumeration (full traversal and early termination), all four tag collection operations, and serial/concurrent dispatch iterations. The path, line, and tag tests independently retain native owners so regressions fail assertions instead of crashing.

Add or extend functional coverage for browse-result interfaces, prohibited interface objects, content-context metadata, establishment-report protocols, WebSocket response headers, Security metadata accessors, and connection batching.

WebSocket request enumeration and framer parsing tests remain deferred: their existing public callback APIs require separate native return-contract corrections. Optional TLS collections are checked when available, and the existing fixture does not provide a TLS-PSK server to exercise actual PSK callbacks.

🤖 Pull request created by Copilot

rolfbjarne and others added 2 commits September 24, 2026 13:15
Add receiver lifetime guards at all 29 additional enumerator sites identified by the ImageIO follow-up audit, plus font sorting, pre-shared-key access, and six adjacent synchronous callback operations. Preserve native return values and error handling while keeping each owner alive through its callback boundary.

Keep DispatchQueue.Submit's callback state rooted for the entire dispatch_apply_f call, using the matching Action<int> type and releasing the handle once after completion. Correct native boolean callback returns, borrowed metadata ownership, certificate conversion, the signature-algorithm success check, and the WebSocket response header call needed to exercise these APIs safely.

Add forced-GC regression coverage for paths, caret enumeration, tag collections, and dispatch iterations. Extend missing Network and Security API coverage, including repeated metadata traversal and multi-header responses. Leave the known ImageIO fix in PR #26676 unchanged. Runtime validation requires the repository's .NET 11 SDK and Xcode 27; neither is currently installed in this worktree.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Use a dedicated TCP connection for the new protocol enumeration test so the established UDP fixture does not acquire a new TCP-connectivity requirement. Wait for its report with a bounded task completion source, and cancel and dispose the connection after enumeration.

The no-Xcode macOS product build and install succeeded. Compiling monotouch-test remains blocked by the native test-library XCFrameworks, which cannot be built with the repository's missing Xcode 27 installation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings September 24, 2026 11:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

A critical dispatch range-validation issue and two moderate lifetime/ownership issues remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Review effort: Lite
Findings: 1 High severity · 1 Low severity

Open (2)
What changed in this PR

Updates Apple bindings to keep managed owners alive during synchronous native callbacks and adds regression coverage.

Changes:

  • Adds lifetime guards and corrects callback ABI/ownership handling.
  • Fixes dispatch callback retention and WebSocket header forwarding.
  • Adds forced-GC and functional tests across affected APIs.
File Summary
tests/​monotouch-test/​Security/​SecProtocolMetadataTest.cs Tests security metadata accessors. Nit (3 votes): expected text uses OSCP instead of OCSP.
tests/​monotouch-test/​Network/​NWWebSocketResponseTest.cs Tests WebSocket response headers.
tests/​monotouch-test/​Network/​NWParametersTest.cs Tests prohibited interfaces.
tests/​monotouch-test/​Network/​NWEstablishmentReportTest.cs Tests establishment-report protocols and resolutions.
tests/​monotouch-test/​Network/​NWContentContextTest.cs Tests metadata iteration.
tests/​monotouch-test/​Network/​NWConnectionTest.cs Tests connection batching.
tests/​monotouch-test/​Network/​NWBrowserTest.cs Tests browse-result interfaces.
tests/​monotouch-test/​CoreText/​CTLineTest.cs Tests caret enumeration under GC.
tests/​monotouch-test/​CoreMedia/​CMTagCollectionTests.cs Tests tag collection lifetime under GC.
tests/​monotouch-test/​CoreGraphics/​PathTest.cs Tests path lifetime under GC.
tests/​monotouch-test/​CoreFoundation/​DispatchQueueTest.cs Tests dispatch iterations and GC behavior.
src/​VideoToolbox/​VTFrameSilo.cs Keeps frame silos alive during enumeration.
src/​Security/​SecProtocolMetadata.cs Corrects metadata callbacks and ownership.
src/​Security/​SecIdentity2.cs Keeps identities alive during certificate access.
src/​Network/​NWWebSocketResponse.cs Fixes header forwarding and enumeration. Moderate bug (1 vote): SetHeader still needs to keep the response alive through the native call.
src/​Network/​NWWebSocketRequest.cs Corrects request callback return types.
src/​Network/​NWTxtRecord.cs Keeps records alive during callbacks.
src/​Network/​NWProxyConfig.cs Keeps proxy configurations alive during enumeration.
src/​Network/​NWProtocolStack.cs Keeps protocol stacks alive during iteration.
src/​Network/​NWPath.cs Keeps paths alive during enumeration.
src/​Network/​NWParameters.cs Keeps parameters alive during interface enumeration.
src/​Network/​NWMulticastGroup.cs Keeps multicast groups alive during enumeration.
src/​Network/​NWFramerMessage.cs Keeps messages alive during value access.
src/​Network/​NWFramer.cs Keeps framers alive during parsing.
src/​Network/​NWEstablishmentReport.cs Corrects enumeration callbacks and lifetimes.
src/​Network/​NWContentContext.cs Corrects borrowed metadata ownership.
src/​Network/​NWConnection.cs Keeps owners alive during batching.
src/​Network/​NWBrowseResult.cs Corrects interface callback ABI. Moderate operational issue (1 vote): borrowed interface wrappers retain handles until finalization instead of being disposed in the callback.
src/​CoreText/​CTLine.cs Keeps lines alive during caret enumeration.
src/​CoreText/​CTFontCollection.cs Keeps font collections alive while sorting.
src/​CoreMedia/​CMTagCollection.cs Keeps collections alive during callbacks.
src/​CoreGraphics/​CGPath.cs Keeps paths alive during application.
src/​CoreFoundation/​Dispatch.cs Retains callback state during dispatch iterations. Critical bug (2 votes): negative times values can convert to an effectively unbounded unsigned dispatch count; validate the range before the native call.

Comment thread src/CoreFoundation/Dispatch.cs Resolved
@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.

rolfbjarne and others added 3 commits September 28, 2026 18:37
Use the correct protocol acronym in the unavailable-response exception and update the matching monotouch-test expectation, so the new coverage no longer preserves the existing typo.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Import System.Threading and use Interlocked directly in the Submit regression test. Within MonoTouchFixtures.CoreFoundation, qualifying the calls with System.Threading instead resolves against the sibling MonoTouchFixtures.System namespace and causes CS0234 on both increments.

Confirmed the two errors in CI's macOS/Mac Catalyst test-build log and reproduced them with a focused compiler check; the corrected statements compile with the same namespace layout.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings September 30, 2026 17:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

The nullable psk_identity bug remains unresolved, with two additional test-coverage nits.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
Resolved since last review (2)

Comment thread src/Security/SecProtocolMetadata.cs Resolved
@vs-mobiletools-engineering-service2

This comment has been minimized.

Move the independent Dispatch, Network, and Security binding fixes and their corresponding tests out of this change for seven dedicated PRs. Preserve all 37 GC.KeepAlive additions and the result handling needed to execute them after native calls.

The extraction sessions use immutable source commit 5e2f4cb. DispatchQueue callback-state cleanup moves together with its delegate-type fix and tests; the remaining path, caret, tag, batching, and prohibited-interface tests stay here. Verified the seven source files reduce exactly to their base implementations after removing lifetime-only guards/scaffolding, and all six extracted test files match the intended base/absence.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
rolfbjarne added a commit that referenced this pull request Oct 3, 2026
Fix two binding errors in `NWWebSocketResponse`:

* Return a native boolean (`byte`, with `1` to continue enumeration) from the additional-header callback, and update its function-pointer signature to match. The previous `void` callback did not provide the continuation result expected by Network.framework.
* Forward the transient header-name and value pointers to the native `nw_ws_response_add_additional_header` overload. Passing the original strings recursively called the managed wrapper instead.

Add a regression test that sets two headers and verifies that enumeration completes and returns both names and values.

This independently extracts only the binding fixes and their test from #26704. All `GC.KeepAlive` guards and associated result locals remain in that separate change.

🤖 Pull request created by Copilot

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
rolfbjarne added a commit that referenced this pull request Oct 3, 2026
…alues. (#26798)

The native resolution, protocol, and resolution-report enumerators return a Boolean indicating whether enumeration should continue. Return byte 1 from their unmanaged trampolines and update the matching function pointers so the existing Action-based managed API consistently continues enumeration.

Extract the binding corrections and related coverage from #26704 without its GC.KeepAlive changes. Add a dedicated TCP protocol-enumeration test with a bounded establishment-report wait and explicit cleanup, preserving the shared UDP fixture. Exercise resolution-report enumeration on devices and require at least one report.

🤖 Pull request created by Copilot

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
rolfbjarne added a commit that referenced this pull request Oct 3, 2026
…26796)

The protocol definition and metadata passed to the content context iterator are borrowed native references. Construct both temporary callback wrappers with owns: false so they retain their own reference and disposal releases only that reference, rather than consuming references owned by the context or caller.

Add a regression test that traverses the metadata twice and checks both native handles on each pass. Extract only this ownership fix and its test from #26704; synchronous enumeration lifetime guards remain in that separate change.

🤖 Pull request created by Copilot

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
rolfbjarne added a commit that referenced this pull request Oct 3, 2026
…6795)

Match the iteration trampoline to the existing Action<int> callback contract so Submit invokes the supplied action. Keep the callback/queue tuple rooted for the entire synchronous dispatch_apply_f call, and free its GCHandle exactly once in finally instead of in each iteration. This also releases the handle when there are no iterations.

Add Submit coverage for zero, one, and eight serial iterations and eight concurrent iterations. Force collections inside callbacks and verify the queue stays alive and each index is visited exactly once before Submit returns.

Extract only the Dispatch source and test hunks from #26704; leave the public API and all GC.KeepAlive changes untouched.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

🤖 Pull request created by Copilot

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
rolfbjarne added a commit that referenced this pull request Oct 3, 2026
The native interface enumerator returns a bool to control whether enumeration continues. Return a byte with value 1 from the unmanaged trampoline and update its function-pointer signature, preserving the public Action-based API while ensuring enumeration continues deterministically.

Exercise interface enumeration in NWBrowserTest by collecting and checking interface names under a lock. Extract only this binding correction and its test coverage from #26704; callback-owner lifetime changes remain separate.

🤖 Pull request created by Copilot

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Integrate the latest main branch after separating the independent callback binding corrections. Preserve the 37 managed-owner lifetime guards and their regression coverage while retaining the binding fixes already landed upstream.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings October 20, 2026 16:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Two moderate SecProtocolMetadata bugs remain, and the batching test lacks moderate forced-GC coverage.

1 open issue
1 resolved since last review

Review effort: Lite

Comment thread src/Security/SecProtocolMetadata.cs Resolved
@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

GetTags_Filter fails in all three NativeAOT configurations on each Apple platform because NUnit instantiates CollectionItemsEqualConstraint.TallyResultCore<CMTag> through reflection, leaving the required native code unavailable.

Check the result length and count each expected tag using statically compiled predicates instead. This preserves the order-independent comparison and rejects missing, duplicate, unexpected, or additional tags without changing product code.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings October 21, 2026 09:16

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

SecProtocolMetadata has an inverted success check and a PSK delegate-type mismatch that can cause valid calls to fail or callbacks to throw.

2 open issues

Review effort: Lite

Comment thread src/Security/SecProtocolMetadata.cs Resolved
@vs-mobiletools-engineering-service2

Copy link
Copy Markdown
Collaborator

✅ API diff for current PR / commit

NET (empty diffs)

✅ API diff vs stable

NET (empty diffs)

ℹ️ Generator diff

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

Pipeline on Agent
Hash: 2152cfd0d991221adba69f3ff654130991d186ff [PR build]

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

Copy link
Copy Markdown
Collaborator

🚀 [CI Build #2152cfd] Test results 🚀

Test results

✅ All tests passed on VSTS: test results.

🎉 All 221 tests passed 🎉

Tests counts

✅ assembly-processing: All 1 tests passed. Html Report (VSDrops) Download
✅ cecil: All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (iOS): All 1 tests passed. [attempt 2] 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 (iOS): All 21 tests passed. Html Report (VSDrops) Download
✅ linker (MacCatalyst): All 21 tests passed. Html Report (VSDrops) Download
✅ linker (macOS): All 21 tests passed. Html Report (VSDrops) Download
✅ linker (tvOS): All 21 tests passed. Html Report (VSDrops) Download
✅ monotouch (iOS): All 20 tests passed. Html Report (VSDrops) Download
✅ monotouch (MacCatalyst): All 20 tests passed. Html Report (VSDrops) Download
✅ monotouch (macOS): All 20 tests passed. Html Report (VSDrops) Download
✅ monotouch (tvOS): All 20 tests passed. Html Report (VSDrops) Download
✅ msbuild: All 2 tests passed. Html Report (VSDrops) Download
✅ sharpie: All 1 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

macOS tests

✅ Tests on macOS Sonoma (14): All 5 tests passed. Html Report (VSDrops) Download
✅ Tests on macOS Sequoia (15): All 5 tests passed. Html Report (VSDrops) Download
✅ Tests on macOS Tahoe (26): All 5 tests passed. Html Report (VSDrops) Download
✅ Tests on macOS Golden Gate (27): All 5 tests passed. Html Report (VSDrops) Download

Linux Build Verification

✅ Linux build succeeded

Pipeline on Agent
Hash: 2152cfd0d991221adba69f3ff654130991d186ff [PR build]

@rolfbjarne
rolfbjarne enabled auto-merge (squash) October 27, 2026 23:32
@rolfbjarne rolfbjarne added the ready-to-review This PR is ready to review/merge. label Oct 27, 2026
@rolfbjarne
rolfbjarne merged commit bbeedd5 into main Oct 28, 2026
56 checks passed
@rolfbjarne
rolfbjarne deleted the dev/rolf/audit-native-enumerator-lifetimes branch October 28, 2026 12:02
rolfbjarne added a commit that referenced this pull request Nov 27, 2026
…n callback return values. (#27493)

The native resolution, protocol, and resolution-report enumerators return a Boolean indicating whether enumeration should continue. Return byte 1 from their unmanaged trampolines and update the matching function pointers so the existing Action-based managed API consistently continues enumeration.

Extract the binding corrections and related coverage from #26704 without its GC.KeepAlive changes. Add a dedicated TCP protocol-enumeration test with a bounded establishment-report wait and explicit cleanup, preserving the shared UDP fixture. Exercise resolution-report enumeration on devices and require at least one report.

Applied without conflicts or dependencies. No app-size expectations changed or needed regeneration.

Backport of #26798.

🤖 Pull request created by Copilot

---------

Co-authored-by: Rolf Bjarne Kvinge <rokvin@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
rolfbjarne added a commit that referenced this pull request Nov 27, 2026
… callback ABI (#27512)

The native interface enumerator returns a bool to control whether enumeration continues. Return a byte with value 1 from the unmanaged trampoline and update its function-pointer signature, preserving the public Action-based API while ensuring enumeration continues deterministically.

Exercise interface enumeration in NWBrowserTest by collecting and checking interface names under a lock. Extract only this binding correction and its test coverage from #26704; callback-owner lifetime changes remain separate.

Backport of #26797.

🤖 Pull request created by Copilot

---------

Co-authored-by: Rolf Bjarne Kvinge <rokvin@microsoft.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

copilot ready-to-review This PR is ready to review/merge.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants