From 30c6f3ef6dbdb5fec78105f75aabef2164977f45 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Fri, 24 Jul 2026 10:04:26 +0200 Subject: [PATCH 1/3] [msbuild] Don't turn missing Objective-C classes into hard link errors when inlining Class.GetHandle. The Class.GetHandle inlining feature (compatibility/strict InlineClassGetHandle) emits a direct native reference ([X class] -> _OBJC_CLASS_$_X) for every surviving Class.GetHandle call. If the native Objective-C class doesn't actually exist in any linked library, the native link fails with 'Undefined symbols: _OBJC_CLASS_$_X', even if the class is never used at runtime. This happens for third-party bindings that declare a [BaseType (typeof (NSObject))] type for something that is a protocol - and not a class - natively (the reported Drastic.FFMpegKit 'Session' type is one example). The existing __attribute__((weak_import)) on the generated @interface isn't enough: ld still errors on a weak-external undefined symbol that isn't defined in any linked library. Fix: only emit a direct native reference for classes we can prove exist (classes that belong to a known platform/SDK framework). For any other class (a third-party binding class, or a class with no managed type) we: * pass '-U _OBJC_CLASS_$_X' to the native linker so a missing class doesn't break the link (this is a no-op for classes that do exist), and * fall back to objc_getClass at runtime if the direct reference is null. This mirrors the weak + dlsym fallback we already do for inlined dlfcn symbols, and restores the net10 behavior (a missing class handle resolves to null) for these classes while keeping the fast direct reference + native dead-strip protection for SDK classes. Fixes https://github.com/dotnet/macios/issues/26268 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 07efe22e-a3b1-444f-8ae9-08325ffcaf1c --- docs/code/class-handles.md | 19 ++++ dotnet/targets/Xamarin.Shared.Sdk.targets | 4 + .../Tasks/PostTrimmingProcessing.cs | 36 +++++++- .../PostTrimmingProcessingTaskTest.cs | 87 +++++++++++++++++++ 4 files changed, 145 insertions(+), 1 deletion(-) create mode 100644 tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs diff --git a/docs/code/class-handles.md b/docs/code/class-handles.md index 48255fb5aa6a..a4d0df2a839b 100644 --- a/docs/code/class-handles.md +++ b/docs/code/class-handles.md @@ -14,6 +14,25 @@ It's highly desirable to use a direct native reference to Objective-C classes wh On the other hand there's one scenario when a direct native reference is not desirable: when the native Objective-C class does not exist. +This can happen for third-party bindings: for instance a binding might declare a +`[BaseType (typeof (NSObject))]` type for something that is a protocol - and not a class - +natively, in which case there's no native Objective-C class to reference. A direct native +reference to such a class would turn into a hard link error (`Undefined symbols: +_OBJC_CLASS_$_TheClass`), even if the class is never actually used at runtime. + +To avoid this, we only emit a direct native reference for classes we can prove exist: classes +that belong to a known platform (SDK) framework. For any other class (a class from a +third-party binding, or a class we couldn't find a managed type for) we can't prove the native +class exists, so we: + +* tell the native linker that the corresponding `_OBJC_CLASS_$_*` symbol is allowed to be + undefined (by passing `-U` to the native linker), so that a missing native class doesn't + break the link, and +* fall back to `objc_getClass` at runtime if the direct reference turns out to be null. + +This mirrors the weak + `dlsym` fallback we do for inlined `dlfcn` symbols (see +[native-symbols.md](native-symbols.md)). + In order to create a direct native reference to Objective-C classes, we need to know the names of those Objective-C classes. ## The `InlineClassGetHandle` property diff --git a/dotnet/targets/Xamarin.Shared.Sdk.targets b/dotnet/targets/Xamarin.Shared.Sdk.targets index c7394415fbb3..73051a6a9c37 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.targets +++ b/dotnet/targets/Xamarin.Shared.Sdk.targets @@ -2052,6 +2052,7 @@ TypeMapFilePath="$(_TypeMapFilePath)" > + @@ -2278,6 +2279,9 @@ <_AllLinkerFlags Include="@(_AssemblyLinkerFlags);@(_MainLinkerFlags);@(_CustomLinkFlags)" /> <_AllLinkerFlags Condition="'$(_ExportSymbolsExplicitly)' != 'true'" Include="@(_ProcessedReferenceNativeSymbol->'-u%(Identity)')" /> + + <_AllLinkerFlags Include="@(_PostTrimmingAllowUndefinedSymbols->'-Wl,-U,%(Identity)')" /> + <_AllLinkerFlags Condition="'$(_UseClassicLinker)' == 'true'" Include="-Xlinker" /> <_AllLinkerFlags Condition="'$(_UseClassicLinker)' == 'true'" Include="-ld_classic" /> diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs index c549ca71c035..66eb989d0264 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs @@ -50,6 +50,16 @@ public class PostTrimmingProcessing : XamarinTask { [Output] public ITaskItem []? NativeSourceFiles { get; set; } + /// + /// Output list of native symbols (Objective-C class symbols) that may be undefined at link + /// time, and which must therefore be passed to the native linker with '-U' so that a missing + /// symbol doesn't turn into a hard link error. These are the Objective-C classes whose native + /// existence we can't prove at build time (e.g. classes from third-party bindings whose native + /// class doesn't actually exist). See docs/code/class-handles.md. + /// + [Output] + public ITaskItem []? AllowUndefinedSymbols { get; set; } + HashSet? ignoredSymbols; HashSet IgnoredSymbols { @@ -208,25 +218,49 @@ void GenerateInlinedClassGetHandleNativeCode (List items) var sb = new StringBuilder (); sb.AppendLine ($"#include "); sb.AppendLine ($"#include "); + var allowUndefinedSymbols = new List (); foreach (var objectiveCClassName in classes) { + // We can't always prove that the native Objective-C class actually exists at link time: it + // might come from a third-party binding whose native class doesn't exist (for instance a + // binding that declares a [BaseType (typeof (NSObject))] type for what is a protocol - and + // not a class - natively). For such classes a direct native reference ([X class]) would turn + // into a hard link error ('Undefined symbols: _OBJC_CLASS_$_X'), even though the class is + // never actually used at runtime. We consider a class "provably existing" if it's a known + // platform (SDK) class (it has a framework), and "risky" otherwise. For risky classes we + // tell the native linker the symbol is allowed to be undefined ('-U'), and we fall back to + // 'objc_getClass' at runtime if the direct reference turns out to be null (which mirrors the + // weak + dlsym fallback we do for inlined dlfcn symbols). + var risky = false; + // We don't want to import every header under the sun to find the @interface definitions for each class, so we generate // a forward declaration for each class. To avoid potential issues with missing classes at runtime, we mark each declaration with __attribute__((weak_import)). // The only exception is that we need to #include Foundation, which means we can't create declarations for Foundation classes. if (!typeMap.TryGetValue (objectiveCClassName, out var info)) { + risky = true; sb.AppendLine ($"__attribute__((weak_import)) @interface {objectiveCClassName} : NSObject @end // no objc type found"); } else if (info.IsWrapper && info.Framework == "Foundation") { // This is a special case for wrapper classes in the Foundation framework. Since we need to #include Foundation, we can't create a forward declaration for these classes. However, since they are wrappers, we know they won't be missing at runtime, so we don't need to mark them with __attribute__((weak_import)). sb.AppendLine ($"// The class '{objectiveCClassName}' comes from the Foundation framework, so no generated @interface declaration."); } else { + // If the class doesn't belong to a known platform framework, then it comes from a third-party + // binding, and we can't prove that the native class actually exists, so treat it as risky. + risky = string.IsNullOrEmpty (info.Framework); if (info.IsStubClass) sb.AppendLine ("__attribute__((objc_class_stub)) __attribute__((objc_subclassing_restricted))"); sb.AppendLine ($"__attribute__((weak_import)) @interface {objectiveCClassName} : NSObject @end // is stub: {info.IsStubClass}"); } sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native ();"); - sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native () {{ return [{objectiveCClassName} class]; }}"); + if (risky) { + sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native () {{ Class rv = [{objectiveCClassName} class]; return rv ? rv : objc_getClass (\"{objectiveCClassName}\"); }}"); + allowUndefinedSymbols.Add (new Microsoft.Build.Utilities.TaskItem (Symbol.Prefix + Symbol.ObjectiveCPrefix + objectiveCClassName)); + } else { + sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native () {{ return [{objectiveCClassName} class]; }}"); + } sb.AppendLine (); } + AllowUndefinedSymbols = allowUndefinedSymbols.ToArray (); + var outputPath = Path.Combine (OutputDirectory, "inlined-class-gethandle.m"); FileUtils.WriteIfDifferent (outputPath, sb.ToString (), (msg) => Log.LogMessage (MessageImportance.Low, msg)); diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs new file mode 100644 index 000000000000..b4e4eab1a015 --- /dev/null +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; +using System.Linq; + +using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; + +using NUnit.Framework; + +using Xamarin.MacDev.Tasks; +using Xamarin.Tests; + +#nullable enable + +namespace Xamarin.MacDev.Tasks.Tests { + + [TestFixture] + public class PostTrimmingProcessingTaskTest : TestBase { + + (string GeneratedCode, ITaskItem [] AllowUndefinedSymbols) RunTask (string [] survivingClasses, string [] typeMapLines) + { + var tempDir = Cache.CreateTemporaryDirectory (); + + var survivingClassesFile = Path.Combine (tempDir, "surviving-classes.txt"); + File.WriteAllLines (survivingClassesFile, survivingClasses); + + var typeMapFile = Path.Combine (tempDir, "type-map.txt"); + File.WriteAllLines (typeMapFile, typeMapLines); + + var outputDir = Path.Combine (tempDir, "output"); + + var task = CreateTask (); + task.Architecture = "arm64"; + task.OutputDirectory = outputDir; + task.SurvivingClassesFiles = new ITaskItem [] { new TaskItem (survivingClassesFile) }; + task.TypeMapFilePath = typeMapFile; + + ExecuteTask (task); + + var generatedCode = File.ReadAllText (Path.Combine (outputDir, "inlined-class-gethandle.m")); + return (generatedCode, task.AllowUndefinedSymbols ?? []); + } + + [Test] + public void ThirdPartyClassIsRisky () + { + // A binding class that doesn't belong to any known platform framework (empty Framework) + // can't be proven to exist natively, so it should get the objc_getClass fallback and be + // added to the list of symbols allowed to be undefined at link time. + var (code, allowUndefined) = RunTask ( + new [] { "ThirdPartyClass" }, + new [] { "Class=ThirdPartyClass|Framework=|Introduced=|IsWrapper=true|IsStubClass=false" }); + + Assert.That (code, Does.Contain ("objc_getClass (\"ThirdPartyClass\")"), "fallback"); + Assert.That (allowUndefined.Select (v => v.ItemSpec), Does.Contain ("_OBJC_CLASS_$_ThirdPartyClass"), "allow undefined"); + } + + [Test] + public void UnknownClassIsRisky () + { + // A class that isn't in the type map at all can't be proven to exist either. + var (code, allowUndefined) = RunTask ( + new [] { "UnknownClass" }, + new [] { "Class=SomethingElse|Framework=UIKit|Introduced=|IsWrapper=true|IsStubClass=false" }); + + Assert.That (code, Does.Contain ("objc_getClass (\"UnknownClass\")"), "fallback"); + Assert.That (allowUndefined.Select (v => v.ItemSpec), Does.Contain ("_OBJC_CLASS_$_UnknownClass"), "allow undefined"); + } + + [Test] + public void PlatformClassIsNotRisky () + { + // A class that belongs to a known platform framework is expected to exist in the SDK we link + // against, so it should keep the direct native reference (no fallback) and must not be added + // to the list of symbols allowed to be undefined (so a genuinely missing SDK class still errors). + var (code, allowUndefined) = RunTask ( + new [] { "UIView" }, + new [] { "Class=UIView|Framework=UIKit|Introduced=|IsWrapper=true|IsStubClass=false" }); + + Assert.That (code, Does.Contain ("return [UIView class];"), "direct reference"); + Assert.That (code, Does.Not.Contain ("objc_getClass (\"UIView\")"), "no fallback"); + Assert.That (allowUndefined.Select (v => v.ItemSpec), Does.Not.Contain ("_OBJC_CLASS_$_UIView"), "no allow undefined"); + } + } +} From 1a40315fed9812ebd4239df9a2c1b8ca7fc612a8 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Mon, 27 Jul 2026 14:13:49 +0200 Subject: [PATCH 2/3] [linker] Don't inline Class.GetHandle for classes with a [Protocol] attribute. The new InlineClassGetHandle optimization rewrites `Class.GetHandle ("X")` into a direct native reference to `_OBJC_CLASS_$_X`. This breaks third-party bindings that declare a `[BaseType (typeof (NSObject))]` type for something that is a protocol - not a class - natively (e.g. Drastic.FFMpegKit's `Session`). bgen generates a `[Protocol]` attribute on the concrete class it emits for these, and the static registrar never registers such classes, so there's no native Objective-C class to reference. Inlining the call then turns into a hard link error (`Undefined symbols: _OBJC_CLASS_$_X`), even when the class is never used at runtime. Fix this by skipping the inlining when the target class has a `[Protocol]` attribute (`ObjCType.IsFakeProtocol`). The call falls back to a runtime lookup instead, which returns null for a missing native class - the same behavior these bindings had before Class.GetHandle inlining existed. This replaces the previous, more complex approach (emitting linker `-U` flags plus an `objc_getClass` fallback), which is reverted here. The `ReferenceNativeSymbol ... Ignore` workarounds for the P2 and ProtocolWithBlockProperties test bindings are now redundant (they're fake protocols, handled automatically) and are removed; TestProtocolRegister keeps its workaround since it's a plain `[Register]` class, not a `[Protocol]`. Fixes https://github.com/dotnet/macios/issues/26268 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 07efe22e-a3b1-444f-8ae9-08325ffcaf1c --- docs/code/class-handles.md | 29 +++---- dotnet/targets/Xamarin.Shared.Sdk.targets | 4 - .../Tasks/PostTrimmingProcessing.cs | 36 +------- tests/linker/link all/dotnet/shared.csproj | 4 +- .../linker/trimmode link/dotnet/shared.csproj | 4 +- .../PostTrimmingProcessingTaskTest.cs | 87 ------------------- .../Steps/InlineClassGetHandleStep.cs | 11 +++ 7 files changed, 25 insertions(+), 150 deletions(-) delete mode 100644 tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs diff --git a/docs/code/class-handles.md b/docs/code/class-handles.md index a4d0df2a839b..139543d8f8a7 100644 --- a/docs/code/class-handles.md +++ b/docs/code/class-handles.md @@ -14,24 +14,17 @@ It's highly desirable to use a direct native reference to Objective-C classes wh On the other hand there's one scenario when a direct native reference is not desirable: when the native Objective-C class does not exist. -This can happen for third-party bindings: for instance a binding might declare a -`[BaseType (typeof (NSObject))]` type for something that is a protocol - and not a class - -natively, in which case there's no native Objective-C class to reference. A direct native -reference to such a class would turn into a hard link error (`Undefined symbols: -_OBJC_CLASS_$_TheClass`), even if the class is never actually used at runtime. - -To avoid this, we only emit a direct native reference for classes we can prove exist: classes -that belong to a known platform (SDK) framework. For any other class (a class from a -third-party binding, or a class we couldn't find a managed type for) we can't prove the native -class exists, so we: - -* tell the native linker that the corresponding `_OBJC_CLASS_$_*` symbol is allowed to be - undefined (by passing `-U` to the native linker), so that a missing native class doesn't - break the link, and -* fall back to `objc_getClass` at runtime if the direct reference turns out to be null. - -This mirrors the weak + `dlsym` fallback we do for inlined `dlfcn` symbols (see -[native-symbols.md](native-symbols.md)). +This can happen for third-party bindings that declare a `[BaseType (typeof (NSObject))]` +type for something that is a protocol - and not a class - natively (bgen generates a +`[Protocol]` attribute on such a type). There's no native Objective-C class for these types +(the static registrar doesn't even register them), so a direct native reference would turn +into a hard link error (`Undefined symbols: _OBJC_CLASS_$_TheClass`), even if the class is +never actually used at runtime. + +To avoid this, we don't inline `Class.GetHandle` when the target class has a `[Protocol]` +attribute: the call falls back to a runtime lookup instead, which returns null (`IntPtr.Zero`) +for a missing native class - the same behavior these bindings had before `Class.GetHandle` +inlining existed. In order to create a direct native reference to Objective-C classes, we need to know the names of those Objective-C classes. diff --git a/dotnet/targets/Xamarin.Shared.Sdk.targets b/dotnet/targets/Xamarin.Shared.Sdk.targets index 73051a6a9c37..c7394415fbb3 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.targets +++ b/dotnet/targets/Xamarin.Shared.Sdk.targets @@ -2052,7 +2052,6 @@ TypeMapFilePath="$(_TypeMapFilePath)" > - @@ -2279,9 +2278,6 @@ <_AllLinkerFlags Include="@(_AssemblyLinkerFlags);@(_MainLinkerFlags);@(_CustomLinkFlags)" /> <_AllLinkerFlags Condition="'$(_ExportSymbolsExplicitly)' != 'true'" Include="@(_ProcessedReferenceNativeSymbol->'-u%(Identity)')" /> - - <_AllLinkerFlags Include="@(_PostTrimmingAllowUndefinedSymbols->'-Wl,-U,%(Identity)')" /> - <_AllLinkerFlags Condition="'$(_UseClassicLinker)' == 'true'" Include="-Xlinker" /> <_AllLinkerFlags Condition="'$(_UseClassicLinker)' == 'true'" Include="-ld_classic" /> diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs index 66eb989d0264..c549ca71c035 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs @@ -50,16 +50,6 @@ public class PostTrimmingProcessing : XamarinTask { [Output] public ITaskItem []? NativeSourceFiles { get; set; } - /// - /// Output list of native symbols (Objective-C class symbols) that may be undefined at link - /// time, and which must therefore be passed to the native linker with '-U' so that a missing - /// symbol doesn't turn into a hard link error. These are the Objective-C classes whose native - /// existence we can't prove at build time (e.g. classes from third-party bindings whose native - /// class doesn't actually exist). See docs/code/class-handles.md. - /// - [Output] - public ITaskItem []? AllowUndefinedSymbols { get; set; } - HashSet? ignoredSymbols; HashSet IgnoredSymbols { @@ -218,49 +208,25 @@ void GenerateInlinedClassGetHandleNativeCode (List items) var sb = new StringBuilder (); sb.AppendLine ($"#include "); sb.AppendLine ($"#include "); - var allowUndefinedSymbols = new List (); foreach (var objectiveCClassName in classes) { - // We can't always prove that the native Objective-C class actually exists at link time: it - // might come from a third-party binding whose native class doesn't exist (for instance a - // binding that declares a [BaseType (typeof (NSObject))] type for what is a protocol - and - // not a class - natively). For such classes a direct native reference ([X class]) would turn - // into a hard link error ('Undefined symbols: _OBJC_CLASS_$_X'), even though the class is - // never actually used at runtime. We consider a class "provably existing" if it's a known - // platform (SDK) class (it has a framework), and "risky" otherwise. For risky classes we - // tell the native linker the symbol is allowed to be undefined ('-U'), and we fall back to - // 'objc_getClass' at runtime if the direct reference turns out to be null (which mirrors the - // weak + dlsym fallback we do for inlined dlfcn symbols). - var risky = false; - // We don't want to import every header under the sun to find the @interface definitions for each class, so we generate // a forward declaration for each class. To avoid potential issues with missing classes at runtime, we mark each declaration with __attribute__((weak_import)). // The only exception is that we need to #include Foundation, which means we can't create declarations for Foundation classes. if (!typeMap.TryGetValue (objectiveCClassName, out var info)) { - risky = true; sb.AppendLine ($"__attribute__((weak_import)) @interface {objectiveCClassName} : NSObject @end // no objc type found"); } else if (info.IsWrapper && info.Framework == "Foundation") { // This is a special case for wrapper classes in the Foundation framework. Since we need to #include Foundation, we can't create a forward declaration for these classes. However, since they are wrappers, we know they won't be missing at runtime, so we don't need to mark them with __attribute__((weak_import)). sb.AppendLine ($"// The class '{objectiveCClassName}' comes from the Foundation framework, so no generated @interface declaration."); } else { - // If the class doesn't belong to a known platform framework, then it comes from a third-party - // binding, and we can't prove that the native class actually exists, so treat it as risky. - risky = string.IsNullOrEmpty (info.Framework); if (info.IsStubClass) sb.AppendLine ("__attribute__((objc_class_stub)) __attribute__((objc_subclassing_restricted))"); sb.AppendLine ($"__attribute__((weak_import)) @interface {objectiveCClassName} : NSObject @end // is stub: {info.IsStubClass}"); } sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native ();"); - if (risky) { - sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native () {{ Class rv = [{objectiveCClassName} class]; return rv ? rv : objc_getClass (\"{objectiveCClassName}\"); }}"); - allowUndefinedSymbols.Add (new Microsoft.Build.Utilities.TaskItem (Symbol.Prefix + Symbol.ObjectiveCPrefix + objectiveCClassName)); - } else { - sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native () {{ return [{objectiveCClassName} class]; }}"); - } + sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native () {{ return [{objectiveCClassName} class]; }}"); sb.AppendLine (); } - AllowUndefinedSymbols = allowUndefinedSymbols.ToArray (); - var outputPath = Path.Combine (OutputDirectory, "inlined-class-gethandle.m"); FileUtils.WriteIfDifferent (outputPath, sb.ToString (), (msg) => Log.LogMessage (MessageImportance.Low, msg)); diff --git a/tests/linker/link all/dotnet/shared.csproj b/tests/linker/link all/dotnet/shared.csproj index bf4a46cecf39..d257acc41efa 100644 --- a/tests/linker/link all/dotnet/shared.csproj +++ b/tests/linker/link all/dotnet/shared.csproj @@ -91,9 +91,7 @@ - - - + diff --git a/tests/linker/trimmode link/dotnet/shared.csproj b/tests/linker/trimmode link/dotnet/shared.csproj index abe1e66a3c38..cc0428443ed8 100644 --- a/tests/linker/trimmode link/dotnet/shared.csproj +++ b/tests/linker/trimmode link/dotnet/shared.csproj @@ -92,9 +92,7 @@ - - - + diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs deleted file mode 100644 index b4e4eab1a015..000000000000 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PostTrimmingProcessingTaskTest.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.IO; -using System.Linq; - -using Microsoft.Build.Framework; -using Microsoft.Build.Utilities; - -using NUnit.Framework; - -using Xamarin.MacDev.Tasks; -using Xamarin.Tests; - -#nullable enable - -namespace Xamarin.MacDev.Tasks.Tests { - - [TestFixture] - public class PostTrimmingProcessingTaskTest : TestBase { - - (string GeneratedCode, ITaskItem [] AllowUndefinedSymbols) RunTask (string [] survivingClasses, string [] typeMapLines) - { - var tempDir = Cache.CreateTemporaryDirectory (); - - var survivingClassesFile = Path.Combine (tempDir, "surviving-classes.txt"); - File.WriteAllLines (survivingClassesFile, survivingClasses); - - var typeMapFile = Path.Combine (tempDir, "type-map.txt"); - File.WriteAllLines (typeMapFile, typeMapLines); - - var outputDir = Path.Combine (tempDir, "output"); - - var task = CreateTask (); - task.Architecture = "arm64"; - task.OutputDirectory = outputDir; - task.SurvivingClassesFiles = new ITaskItem [] { new TaskItem (survivingClassesFile) }; - task.TypeMapFilePath = typeMapFile; - - ExecuteTask (task); - - var generatedCode = File.ReadAllText (Path.Combine (outputDir, "inlined-class-gethandle.m")); - return (generatedCode, task.AllowUndefinedSymbols ?? []); - } - - [Test] - public void ThirdPartyClassIsRisky () - { - // A binding class that doesn't belong to any known platform framework (empty Framework) - // can't be proven to exist natively, so it should get the objc_getClass fallback and be - // added to the list of symbols allowed to be undefined at link time. - var (code, allowUndefined) = RunTask ( - new [] { "ThirdPartyClass" }, - new [] { "Class=ThirdPartyClass|Framework=|Introduced=|IsWrapper=true|IsStubClass=false" }); - - Assert.That (code, Does.Contain ("objc_getClass (\"ThirdPartyClass\")"), "fallback"); - Assert.That (allowUndefined.Select (v => v.ItemSpec), Does.Contain ("_OBJC_CLASS_$_ThirdPartyClass"), "allow undefined"); - } - - [Test] - public void UnknownClassIsRisky () - { - // A class that isn't in the type map at all can't be proven to exist either. - var (code, allowUndefined) = RunTask ( - new [] { "UnknownClass" }, - new [] { "Class=SomethingElse|Framework=UIKit|Introduced=|IsWrapper=true|IsStubClass=false" }); - - Assert.That (code, Does.Contain ("objc_getClass (\"UnknownClass\")"), "fallback"); - Assert.That (allowUndefined.Select (v => v.ItemSpec), Does.Contain ("_OBJC_CLASS_$_UnknownClass"), "allow undefined"); - } - - [Test] - public void PlatformClassIsNotRisky () - { - // A class that belongs to a known platform framework is expected to exist in the SDK we link - // against, so it should keep the direct native reference (no fallback) and must not be added - // to the list of symbols allowed to be undefined (so a genuinely missing SDK class still errors). - var (code, allowUndefined) = RunTask ( - new [] { "UIView" }, - new [] { "Class=UIView|Framework=UIKit|Introduced=|IsWrapper=true|IsStubClass=false" }); - - Assert.That (code, Does.Contain ("return [UIView class];"), "direct reference"); - Assert.That (code, Does.Not.Contain ("objc_getClass (\"UIView\")"), "no fallback"); - Assert.That (allowUndefined.Select (v => v.ItemSpec), Does.Not.Contain ("_OBJC_CLASS_$_UIView"), "no allow undefined"); - } - } -} diff --git a/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs b/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs index 84eb9833cd17..5a26cc90c775 100644 --- a/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs +++ b/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs @@ -194,6 +194,17 @@ bool isOurOwnCode () } if (objCType is not null) { + if (objCType.IsFakeProtocol) { + // This is a class with a [Protocol] attribute (typically a binding that declares a + // [BaseType (typeof (NSObject))] type for something that is a protocol - and not a class - + // natively). The static registrar doesn't register these classes, so there's no native + // Objective-C class to reference, which means inlining the call to Class.GetHandle would + // turn into a hard link error ('Undefined symbols: _OBJC_CLASS_$_X'). Don't inline it, so + // that the call falls back to a runtime lookup (which returns null for a missing class). + App.Log (3, "Not inlining the call to Class.GetHandle (\"{0}\") in method {1} because the class has a [Protocol] attribute, so there's no native Objective-C class to reference.", objectiveCClassName, FormatMethod (method)); + continue; + } + if (DerivedLinkContext.App.IsSimulatorBuild) { if (DerivedLinkContext.HasAvailabilityAttributesShowingUnavailableInSimulator (objCType.Type.Resolve (), method)) { App.Log (3, "Not inlining the call to Class.GetHandle (\"{0}\") in method {1} because the type is marked with an attribute indicating it's not available in the simulator.", objectiveCClassName, FormatMethod (method)); From b75cd4d7e7c075be386acde9b40f5bdc8ab19923 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Tue, 28 Jul 2026 11:37:06 +0200 Subject: [PATCH 3/3] [linker] Clarify that Class.GetHandle returns a zero handle, not null. Address review feedback: Class.GetHandle returns a NativeHandle (a value type), so for a missing native class it returns a zero handle (IntPtr.Zero), not null. Fix the wording in the code comment and the documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 07efe22e-a3b1-444f-8ae9-08325ffcaf1c --- docs/code/class-handles.md | 6 +++--- tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/code/class-handles.md b/docs/code/class-handles.md index 139543d8f8a7..998267728cd9 100644 --- a/docs/code/class-handles.md +++ b/docs/code/class-handles.md @@ -22,9 +22,9 @@ into a hard link error (`Undefined symbols: _OBJC_CLASS_$_TheClass`), even if th never actually used at runtime. To avoid this, we don't inline `Class.GetHandle` when the target class has a `[Protocol]` -attribute: the call falls back to a runtime lookup instead, which returns null (`IntPtr.Zero`) -for a missing native class - the same behavior these bindings had before `Class.GetHandle` -inlining existed. +attribute: the call falls back to a runtime lookup instead, which returns a zero handle +(`IntPtr.Zero`) for a missing native class - the same behavior these bindings had before +`Class.GetHandle` inlining existed. In order to create a direct native reference to Objective-C classes, we need to know the names of those Objective-C classes. diff --git a/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs b/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs index 5a26cc90c775..a6f48cde6b6e 100644 --- a/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs +++ b/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs @@ -200,7 +200,7 @@ bool isOurOwnCode () // natively). The static registrar doesn't register these classes, so there's no native // Objective-C class to reference, which means inlining the call to Class.GetHandle would // turn into a hard link error ('Undefined symbols: _OBJC_CLASS_$_X'). Don't inline it, so - // that the call falls back to a runtime lookup (which returns null for a missing class). + // that the call falls back to a runtime lookup (which returns a zero handle for a missing class). App.Log (3, "Not inlining the call to Class.GetHandle (\"{0}\") in method {1} because the class has a [Protocol] attribute, so there's no native Objective-C class to reference.", objectiveCClassName, FormatMethod (method)); continue; }