Skip to content

[dotnet-linker] Add a trimmer step to inline calls to Class.GetHandle[Intrinsic].#25318

Open
rolfbjarne wants to merge 5 commits into
mainfrom
dev/rolf/inline-class-gethandle
Open

[dotnet-linker] Add a trimmer step to inline calls to Class.GetHandle[Intrinsic].#25318
rolfbjarne wants to merge 5 commits into
mainfrom
dev/rolf/inline-class-gethandle

Conversation

@rolfbjarne
Copy link
Copy Markdown
Member

@rolfbjarne rolfbjarne commented May 4, 2026

Summary

Adds a new trimmer step that inlines calls to Class.GetHandle (and Class.GetHandleIntrinsic) with direct native references to Objective-C classes. This is a companion feature to the existing InlineDlfcnMethods step, and together they enable the linker to replace managed dictionary lookups with direct native symbol references that are resolved at native link time.

Motivation

Class.GetHandle ("ClassName") calls go through a managed dictionary lookup at runtime. By inlining these calls, we:

  1. Improve startup performance — eliminates dictionary lookups for class handles.
  2. Enable dead-code elimination — the native linker can strip unreferenced class references, reducing binary size.
  3. Support NativeAOT — ensures class references survive the NativeAOT compilation pipeline without relying on reflection-based discovery.

Design

The feature works in two modes controlled by the InlineClassGetHandle MSBuild property:

  • compatibility (default for IL trimming on .NET 11+): Rewrites Class.GetHandle calls to P/Invoke wrappers, then generates native code for all surviving wrappers after trimming. Falls back to objc_getClass at runtime for missing classes.
  • strict (default for NativeAOT on .NET 11+): Same rewriting, but does not generate runtime fallbacks — missing classes produce a build error.

Pipeline

  1. ILTrim phase (InlineClassGetHandleStep): Rewrites Class.GetHandle/GetHandleIntrinsic calls to generated P/Invoke methods.
  2. Type map generation (CoreTypeMapStep): Emits class metadata (framework, introduced version, wrapper status) used by post-trim code generation.
  3. Post-trim processing (PostTrimmingProcessing MSBuild task): Collects surviving class references from trimmed assemblies, generates native source files with @interface forward declarations and wrapper functions.
  4. NativeAOT path (CollectUnresolvedNativeSymbols + ComputeNativeAOTSurvivingNativeSymbols): Extracts unresolved symbols from NativeAOT output and generates native code for surviving references only.

Changes

  • New linker steps: InlineClassGetHandleStep, GenerateInlinedClassGetHandleCodeStep, updated CoreTypeMapStep.
  • New MSBuild tasks: PostTrimmingProcessing (generates native code), CollectUnresolvedNativeSymbols, ComputeNativeAOTSurvivingNativeSymbols, CollectPostILTrimInformation.
  • Shared utilities: FileUtils.WriteIfDifferent, MachO unresolved symbol extraction, framework lookup helpers.
  • MSBuild integration: New properties (InlineClassGetHandle), targets for post-trim native code generation and compilation.
  • Tests: New test variations (inline-class-gethandle-compat, inline-class-gethandle-strict) for both ILTrim and NativeAOT paths.
  • Documentation: docs/code/class-handles.md, docs/building-apps/build-properties.md updated.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds a new trimming/linking pipeline to replace some ObjCRuntime.Dlfcn and Class.GetHandle[Intrinsic] calls with direct native references, so surviving symbols/classes can be materialized as native code after trimming and preserved for the final app link.

Changes:

  • Adds new linker steps and linker configuration for inlining Dlfcn and Class.GetHandle calls, plus symbol/type collection helpers.
  • Adds MSBuild tasks/targets to scan trimmed outputs / NativeAOT objects, generate native source files, and compile/link those generated references.
  • Adds docs and test variations/tests intended to exercise the new symbol/class inlining behavior.

Reviewed changes

Copilot reviewed 38 out of 39 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tools/mtouch/Errors.resx Adds new linker warning/error resource strings.
tools/mtouch/Errors.designer.cs Regenerates strongly-typed resource accessors.
tools/linker/MonoTouch.Tuner/ProcessExportedFields.cs Collects [Field] symbol names for compat mode.
tools/linker/MonoTouch.Tuner/ListExportedSymbols.cs Refactors Objective-C type preservation and field handling.
tools/linker/CoreTypeMapStep.cs Emits Objective-C class/framework/version type-map data.
tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs New step that rewrites supported Dlfcn call patterns.
tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs New step that rewrites Class.GetHandle[Intrinsic] calls.
tools/dotnet-linker/Steps/GenerateReferencesStep.cs Minor symbol prefix usage update.
tools/dotnet-linker/Steps/GenerateInlinedClassGetHandleCodeStep.cs Adds a generated-symbol-list step for post-trim processing.
tools/dotnet-linker/Steps/GatherFrameworksStep.cs Broadens framework gathering to all assemblies.
tools/dotnet-linker/Steps/AssemblyModifierStep.cs Makes type iteration resilient to newly added types.
tools/dotnet-linker/LinkerConfiguration.cs Adds new inlining-related options and state.
tools/dotnet-linker/AppBundleRewriter.cs Adds helpers for creating synthetic types/PInvokes.
tools/common/Symbols.cs Exposes symbol prefix constants/shared APIs.
tools/common/StaticRegistrar.cs Exposes SDK-introduced-version lookup override.
tools/common/PathUtils.cs Adds directory-creation helper for file paths.
tools/common/MachO.cs Adds unresolved-symbol extraction from Mach-O/static libs.
tools/common/Frameworks.cs Adds framework lookup helpers and broader gathering logic.
tools/common/FileUtils.cs Adds a write-if-different helper for generated files.
tools/common/CompilerFlags.cs Updates symbol prefix usage.
tests/xharness/Jenkins/TestVariationsFactory.cs Adds new CI test variations for the inlining modes.
tests/monotouch-test/ObjCRuntime/DlfcnTest.cs Adds regression coverage for inlined Dlfcn scenarios.
tests/monotouch-test/Foundation/AttributedStringTest.cs Removes obsolete missing-symbol assertions.
tests/monotouch-test/dotnet/shared.csproj Adds ignored/reference native symbols for tests.
tests/monotouch-test/CoreGraphics/GeometryTest.cs Refactors CGRect symbol lookup test helper.
tests/monotouch-test/CoreFoundation/ProxyTest.cs Removes obsolete missing-symbol assertions.
tests/common/test-variations.csproj Declares new build/test variation names and properties.
src/ObjCRuntime/Registrar.cs Exposes exported Objective-C type-name lookup helpers.
msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj Includes shared symbol code and new task files.
msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs Generates post-trim native source files.
msbuild/Xamarin.MacDev.Tasks/Tasks/ComputeNativeAOTSurvivingNativeSymbols.cs Filters NativeAOT unresolved symbols into surviving lists.
msbuild/Xamarin.MacDev.Tasks/Tasks/CompileNativeCode.cs Ensures output directories exist before compilation.
msbuild/Xamarin.MacDev.Tasks/Tasks/CollectUnresolvedNativeSymbols.cs Collects unresolved symbols from NativeAOT outputs.
msbuild/Xamarin.MacDev.Tasks/Tasks/CollectPostILTrimInformation.cs Scans trimmed assemblies for surviving generated P/Invokes.
dotnet/targets/Xamarin.Shared.Sdk.targets Wires new linker parameters, steps, and post-trim targets.
dotnet/targets/Xamarin.Shared.Sdk.props Adds default values for the new inlining properties.
docs/code/native-symbols.md Documents the Dlfcn native-symbol pipeline.
docs/code/class-handles.md Documents the Class.GetHandle pipeline.
docs/building-apps/build-properties.md Documents InlineDlfcnMethods.
Files not reviewed (1)
  • tools/mtouch/Errors.designer.cs: Language not supported

Comment thread dotnet/targets/Xamarin.Shared.Sdk.props Outdated
Comment thread msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs
Comment thread tools/common/FileUtils.cs Outdated
Comment thread tests/xharness/Jenkins/TestVariationsFactory.cs Outdated
Comment thread dotnet/targets/Xamarin.Shared.Sdk.targets Outdated
Comment thread tests/xharness/Jenkins/TestVariationsFactory.cs Outdated
@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

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2

This comment has been minimized.

@rolfbjarne rolfbjarne changed the base branch from main to dev/rolf/inline-dlfcn May 5, 2026 16:24
@rolfbjarne rolfbjarne force-pushed the dev/rolf/inline-class-gethandle branch from 83c1324 to 556a21c Compare May 5, 2026 16:25
@rolfbjarne
Copy link
Copy Markdown
Member Author

/review

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 5, 2026

.NET for Apple Platforms PR Reviewer completed successfully!

Copy link
Copy Markdown
Contributor

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

Code Review Summary

This PR adds a new trimmer step to inline calls to Class.GetHandle[Intrinsic], converting them to direct P/Invoke calls that reference Objective-C classes natively. This optimization improves runtime performance and enables better native linking.

Critical Issues Found

🔴 Blocking Issues

  1. Typo in MSBuild property name (dotnet/targets/Xamarin.Shared.Sdk.props:111): TargetFrameworkVersion is split as "TargetFr ameworkVersion" with a space, breaking the condition that sets default values for InlineClassGetHandle. This will cause the feature to not activate correctly.

  2. Placeholder error codes (tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs:41, 114, 119, 127, 132): Multiple error messages use placeholder code 9999 with "Copilot:" comments indicating they need proper error codes and resource strings. These must be replaced with actual error codes before merging.

⚠️ Non-Blocking Issues

  1. Typo in parameter name (PostTrimmingProcessing.cs:112): filterObjetiveCClasses should be filterObjectiveCClasses (missing 'c'). While this doesn't affect functionality, it should be corrected for code quality.

  2. Missing optimization (CollectPostILTrimInformation.cs:124): Comment indicates an unimplemented early-exit optimization for assemblies without __Internal module references.

  3. Missing validation in typeMap parsing (PostTrimmingProcessing.cs:156): The typeMap parsing doesn't validate that required fields exist, potentially creating entries with empty keys.

  4. Potential KeyNotFoundException (PostTrimmingProcessing.cs:182): ToDictionary call may throw if the typeMap file contains duplicate class names. Consider using a more defensive approach.

Architecture & Design

The overall design is sound:

  • Clear separation of concerns between trimming steps, MSBuild tasks, and code generation
  • Good use of caching for incremental builds
  • Appropriate handling of both ILTrim and NativeAOT paths
  • Documentation file (class-handles.md) provides good context

Recommendation

Request Changes - The typo in TargetFrameworkVersion and placeholder error codes must be fixed before this can be merged, as they will cause the feature to malfunction.

Generated by .NET for Apple Platforms PR Reviewer for issue #25318 · ● 1.6M

Comment thread dotnet/targets/Xamarin.Shared.Sdk.props
Comment thread msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs Outdated
Comment thread msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs Outdated
Comment thread tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs Outdated
Comment thread msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs Outdated
Comment thread msbuild/Xamarin.MacDev.Tasks/Tasks/CollectPostILTrimInformation.cs Outdated
Comment thread tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs Outdated
@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
Copy Markdown
Collaborator

🔥 Failed to compute test summaries on VSTS: test results 🔥

Failed to compute test summaries:

Unicorn! · GitHub

  body {
    background-color: #f1f1f1;
    margin: 0;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  }

  .container { margin: 50px auto 40px auto; width: 600px; text-align: center; }

  a { color: #4183c4; text-decoration: none; }
  a:hover { text-decoration: underline; }

  h1 { letter-spacing: -1px; line-height: 60px; font-size: 60px; font-weight: 100; margin: 0px; text-shadow: 0 1px 0 #fff; }
  p { color: rgba(0, 0, 0, 0.5); margin: 10px 0 10px; font-size: 18px; font-weight: 200; line-height: 1.6em;}

  ul { list-style: none; margin: 25px 0; padding: 0; }
  li { display: table-cell; font-weight: bold; width: 1%; }

  .logo { display: inline-block; margin-top: 35px; }
  .logo-img-2x { display: none; }
  @media
  only screen and (-webkit-min-device-pixel-ratio: 2),
  only screen and (   min--moz-device-pixel-ratio: 2),
  only screen and (     -o-min-device-pixel-ratio: 2/1),
  only screen and (        min-device-pixel-ratio: 2),
  only screen and (                min-resolution: 192dpi),
  only screen and (                min-resolution: 2dppx) {
    .logo-img-1x { display: none; }
    .logo-img-2x { display: inline-block; }
  }

  #suggestions {
    margin-top: 35px;
    color: #ccc;
  }
  #suggestions a {
    color: #666666;
    font-weight: 200;
    font-size: 14px;
    margin: 0 10px;
  }






  
    
  

  We had issues producing the response to your request.
  Sorry about that. Please try refreshing and contact us if the problem persists.
  
    Contact Support —
    GitHub Status —
    @githubstatus

.

Pipeline on Agent
Merge cd34f6e into f34f090

…[Intrinsic].

Add a new custom linker step that replaces runtime `Class.GetHandle[Intrinsic]` calls
with direct native symbol lookups via P/Invokes to `__Internal`. This improves startup
performance and app size, and ensures the native linker can see symbol references
that would otherwise only be resolved at runtime.
@rolfbjarne rolfbjarne force-pushed the dev/rolf/inline-class-gethandle branch from cd34f6e to 813d7de Compare May 21, 2026 17:38
@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.

rolfbjarne and others added 3 commits May 25, 2026 11:44
… separate target

The _PostTrimmingProcessing target always runs (no Inputs/Outputs) and
unconditionally recompiles inlined-class-gethandle.m even when the source
file hasn't changed. This produces a newer .o file which triggers
_LinkNativeExecutable to re-link the native executable, invalidating the
code signature on every incremental build.

Fix by splitting the CompileNativeCode invocation into a new
_CompilePostTrimmingFiles target with proper Inputs/Outputs, so the .o
file is only regenerated when the .m source actually changes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@vs-mobiletools-engineering-service2
Copy link
Copy Markdown
Collaborator

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

Pipeline on Agent
Hash: 9f0410b0e988773cf158df636f93018a03b3739c [PR build]

@vs-mobiletools-engineering-service2

This comment has been minimized.

@vs-mobiletools-engineering-service2
Copy link
Copy Markdown
Collaborator

✅ [PR Build #9f0410b] Build passed (Build packages) ✅

Pipeline on Agent
Hash: 9f0410b0e988773cf158df636f93018a03b3739c [PR build]

@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: 9f0410b0e988773cf158df636f93018a03b3739c [PR build]

@vs-mobiletools-engineering-service2
Copy link
Copy Markdown
Collaborator

✅ [PR Build #9f0410b] Build passed (Build macOS tests) ✅

Pipeline on Agent
Hash: 9f0410b0e988773cf158df636f93018a03b3739c [PR build]

@vs-mobiletools-engineering-service2
Copy link
Copy Markdown
Collaborator

🔥 [CI Build #9f0410b] Test results 🔥

Test results

❌ Tests failed on VSTS: test results

0 tests crashed, 2 tests failed, 191 tests passed.

Failures

❌ interdependent-binding-projects tests

2 tests failed, 2 tests passed.

Failed tests

  • interdependent-binding-projects/iOS - simulator/Debug: LaunchTimedOut
  • interdependent-binding-projects/tvOS - simulator/Debug: LaunchTimedOut

Html Report (VSDrops) Download

Successes

✅ cecil: All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (iOS): All 1 tests passed. (⚠️ Html Report Publish failed ⚠️) Download
✅ dotnettests (MacCatalyst): All 1 tests passed. (⚠️ Html Report Publish failed ⚠️) Download
✅ dotnettests (macOS): All 1 tests passed. Html Report (VSDrops) Download
✅ dotnettests (Multiple platforms): All 1 tests passed. (⚠️ Html Report Publish failed ⚠️) 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
✅ introspection: All 6 tests passed. Html Report (VSDrops) Download
✅ linker (iOS): All 11 tests passed. Html Report (VSDrops) Download
✅ linker (MacCatalyst): All 11 tests passed. Html Report (VSDrops) Download
✅ linker (macOS): All 11 tests passed. Html Report (VSDrops) Download
✅ linker (tvOS): All 11 tests passed. Html Report (VSDrops) Download
✅ monotouch (iOS): All 20 tests passed. Html Report (VSDrops) Download
✅ monotouch (MacCatalyst): All 23 tests passed. Html Report (VSDrops) Download
✅ monotouch (macOS): All 23 tests passed. (⚠️ Html Report Publish failed ⚠️) 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 Monterey (12): All 5 tests passed. Html Report (VSDrops) Download
✅ Tests on macOS Ventura (13): All 5 tests passed. Html Report (VSDrops) Download
✅ 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

Linux Build Verification

Linux build succeeded

Pipeline on Agent
Hash: 9f0410b0e988773cf158df636f93018a03b3739c [PR build]

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.

4 participants