diff --git a/.github/workflows/maestro-changelog.yml b/.github/workflows/maestro-changelog.yml index e8a308e390c9..90b51961df75 100644 --- a/.github/workflows/maestro-changelog.yml +++ b/.github/workflows/maestro-changelog.yml @@ -17,17 +17,17 @@ jobs: if: github.event.pull_request.user.login == 'dotnet-maestro[bot]' steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: - dotnet-version: '9' + global-json-file: ./global.json - name: 'Compute changelog' run: | set -exo pipefail - git clone https://github.com/spouliot/dotnet-tools - cd dotnet-tools/changelog - dotnet build - ./bin/Debug/net9.0/changelog https://github.com/$GITHUB_REPOSITORY/pull/${GITHUB_REF_NAME/\/*/} > /tmp/changelog.txt 2>&1 + dotnet run --project scripts/changelog/changelog.csproj --verbosity quiet -- https://github.com/$GITHUB_REPOSITORY/pull/${GITHUB_REF_NAME/\/*/} /tmp/changelog.txt - name: 'Add changelog' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 @@ -45,7 +45,9 @@ jobs: issue_number: context.issue.number }).then ((comments) => { - const changelogComment = comments.find(comment => comment.body.includes (".net ChangeLog for") && comment.user.login == 'github-actions[bot]') + const changelogComment = comments.find(comment => + (comment.body.includes (".NET Changelog for") || comment.body.includes (".net ChangeLog for")) && + comment.user.login == 'github-actions[bot]') if (changelogComment) commentId = changelogComment.id }) diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml index ee7127c01f5e..3345724994b9 100644 --- a/.github/workflows/zizmor.yml +++ b/.github/workflows/zizmor.yml @@ -29,6 +29,6 @@ jobs: echo "files=$files" >> "$GITHUB_OUTPUT" - name: Run zizmor - uses: zizmorcore/zizmor-action@6599ee8b7a49aef6a770f63d261d214911a7ce02 # v0.6.0 + uses: zizmorcore/zizmor-action@3dc1ecc9bcb9e94e9b2c709687979e1298497054 # v0.6.2 with: inputs: ${{ steps.find-files.outputs.files }} diff --git a/Directory.Build.props b/Directory.Build.props index 847ba3e62337..d2888d1c973d 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -12,7 +12,7 @@ 4.7.2 - 8.0.0 + 8.0.4 21.1.8.3 5.5.1 diff --git a/NuGet.config b/NuGet.config index 4c0e1a13ba54..cb4c8c39b50d 100644 --- a/NuGet.config +++ b/NuGet.config @@ -10,7 +10,6 @@ - diff --git a/docs/building-apps/build-properties.md b/docs/building-apps/build-properties.md index df81826bd557..2ce9f34eebb3 100644 --- a/docs/building-apps/build-properties.md +++ b/docs/building-apps/build-properties.md @@ -197,6 +197,27 @@ The default value of this property `false` in .NET 9, and `true` in .NET 10+. > [!NOTE] > File an issue if you find that you need to disable this feature, as it's possible that the option to disable it will be removed in future. +## CheckForIllegalCrossThreadCalls + +Controls whether the UI thread checks (the `[NS|UI]Application.EnsureUIThread` +calls the generated bindings emit for UI code) are performed. + +When set to `true`, the checks are enabled: accessing UI API off the UI thread +throws an exception. When set to `false`, the checks are disabled. + +This property is emitted as the `ObjCRuntime.Runtime.CheckForIllegalCrossThreadCalls` +runtime feature switch, so it takes effect even when trimming is disabled: the +`[NS|UI]Application.CheckForIllegalCrossThreadCalls` field reflects the property +value at runtime, and the checks are enabled or disabled accordingly. + +When trimming is enabled and the checks are disabled, ILLink additionally stubs +the `[NS|UI]Application.EnsureUIThread` method body and trims away the +`CheckForIllegalCrossThreadCalls` field, making the app slightly smaller and +faster. + +If this value is not specified, the checks are kept in debug builds and removed +in release builds. + ## CodesignAllocate The path to the `codesign_allocate` tool. @@ -617,6 +638,13 @@ Default: true Where the generated source from the generator are saved. +## GenerateTrustedPlatformAssemblies + +A boolean property that specifies whether the trusted platform assembly list is +generated at build time instead of discovered when the app launches. + +The default value is `false` for debug builds and `true` for other builds. + ## GetApplicationArtifactsDependsOn A semi-colon delimited property that can be used to extend the diff --git a/docs/website/optimizations.md b/docs/website/optimizations.md index 2805613fe810..4fd7e9115f54 100644 --- a/docs/website/optimizations.md +++ b/docs/website/optimizations.md @@ -16,8 +16,15 @@ Xamarin.iOS and Xamarin.Mac apps. ## Remove UIApplication.EnsureUIThread / NSApplication.EnsureUIThread -Removes calls to [UIApplication.EnsureUIThread][1] (for Xamarin.iOS) or -`NSApplication.EnsureUIThread` (for Xamarin.Mac). +> [!NOTE] +> This optimization has been replaced by the `CheckForIllegalCrossThreadCalls` +> MSBuild property, which sets the +> `ObjCRuntime.Runtime.CheckForIllegalCrossThreadCalls` trimmer feature switch. +> The `--optimize=[+|-]remove-uithread-checks` flag is no longer applied and has +> no effect. + +Removes calls to [UIApplication.EnsureUIThread][1] (for .NET for iOS) or +`NSApplication.EnsureUIThread` (for .NET for macOS). This optimization will change the following type of code: @@ -43,7 +50,7 @@ methods with the `[BindingImpl (BindingImplOptions.Optimizable)]` attribute. By default it's enabled for release builds. -The default behavior can be overridden by passing `--optimize=[+|-]remove-uithread-checks` to mtouch/mmp. +Set the `CheckForIllegalCrossThreadCalls` MSBuild property to override the default behavior. [1]: /dotnet/api/UIKit.UIApplication.EnsureUIThread diff --git a/dotnet/targets/Xamarin.Shared.Sdk.props b/dotnet/targets/Xamarin.Shared.Sdk.props index 6cdaf1762789..8e7eaf35f413 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.props +++ b/dotnet/targets/Xamarin.Shared.Sdk.props @@ -41,37 +41,50 @@ <_UseNativeAot Condition="'$(PublishAot)' == 'true' And '$(_IsPublishing)' == 'true'">true - trimmable-static + false + false + true - true + trimmable-static + + + true - $(PrepareAssemblies) - - false - false - true + $(PrepareAssemblies) $(AfterMicrosoftNETSdkTargets);$(MSBuildThisFileDirectory)Microsoft.$(_PlatformName).Sdk.targets diff --git a/dotnet/targets/Xamarin.Shared.Sdk.targets b/dotnet/targets/Xamarin.Shared.Sdk.targets index cba16b77697f..186b1c85970b 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.targets +++ b/dotnet/targets/Xamarin.Shared.Sdk.targets @@ -26,6 +26,7 @@ + @@ -123,6 +124,10 @@ <_BundlerDebug Condition="'$(_BundlerDebug)' == ''">false + + true + false + <_RidSpecificProperties> BuildProjectReferences=false; _IsMultiRidBuild=true; + _IsUniversalBuild=$(_IsUniversalBuild); RuntimeIdentifiers=; _ProcessedBundleResourcesPath=$(_ProcessedBundleResourcesPath); _ProcessedContentPath=$(_ProcessedContentPath); @@ -543,6 +552,14 @@ Compile;_ComputeLinkerArguments;_ComputeManagedAssemblyToLink;SetupOSSpecificProps;PrepareForILLink;_XamarinComputeIlcCompileInputs + + <_PrepareAssembliesForPostProcessingDependsOn> + $(_PrepareAssembliesForPostProcessingDependsOn); + _ComputeLinkerInputs; + _GenerateLinkerDependencyCache; + + + <_ValidateObjectPointers Condition="'$(_ValidateObjectPointers)' == ''">false + + <_CheckForIllegalCrossThreadCalls Condition="'$(CheckForIllegalCrossThreadCalls)' != ''">$(CheckForIllegalCrossThreadCalls) + <_CheckForIllegalCrossThreadCalls Condition="'$(_CheckForIllegalCrossThreadCalls)' == ''">$(_BundlerDebug) + <_CustomLinkerOptions> AreAnyAssembliesTrimmed=$(_AreAnyAssembliesTrimmed) AssemblyName=$(AssemblyName).dll @@ -772,6 +797,7 @@ DynamicRegistrationSupported=$(DynamicRegistrationSupported) @(_CustomLinkFlags -> 'CustomLinkFlags=%(Identity)') EnableSGenConc=$(EnableSGenConc) + GenerateTrustedPlatformAssemblies=$(GenerateTrustedPlatformAssemblies) @(_BundlerEnvironmentVariables -> 'EnvironmentVariable=Overwrite=%(Overwrite)|%(Identity)=%(Value)') @(_XamarinFrameworkAssemblies -> 'FrameworkAssembly=%(Filename)') Interpreter=$(MtouchInterpreter) @@ -784,6 +810,7 @@ HotReloadCompatibleBuild=$(HotReloadCompatibleBuild) ItemsDirectory=$(_LinkerItemsDirectory) IsAppExtension=$(IsAppExtension) + IsMultiRidBuild=$(_IsUniversalBuild) IsSimulatorBuild=$(_SdkIsSimulator) LibMonoLinkMode=$(_LibMonoLinkMode) LibXamarinLinkMode=$(_LibXamarinLinkMode) @@ -905,6 +932,7 @@ + @@ -1371,7 +1399,7 @@ @@ -1621,10 +1649,13 @@ + + <_MergedRuntimeConfigFilePath>$(DeviceSpecificIntermediateOutputPath)runtimeconfig.merged.json + <_RuntimeConfigReservedProperties Include="APP_PATHS" /> @@ -1636,9 +1667,25 @@ <_RuntimeConfigReservedProperties Include="SYSTEM_CORELIB_DIRECTORY" /> <_RuntimeConfigReservedProperties Include="STARTUP_HOOKS" /> - + + + + + + + + diff --git a/eng/Version.Details.props b/eng/Version.Details.props index e8e734c13631..ab80b8e15eb6 100644 --- a/eng/Version.Details.props +++ b/eng/Version.Details.props @@ -30,7 +30,7 @@ This file should be imported by eng/Versions.props 18.5.9227 26.5.9004 - 11.0.0-prerelease.26370.1 + 11.0.0-prerelease.26427.1 18.0.9617 18.0.9617 diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 711aca67f4a9..b722ef26e7d0 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -107,9 +107,9 @@ https://github.com/dotnet/dotnet 6e38c59c51ac7a6995f6252de38caaff27af165d - + https://github.com/dotnet/xharness - 65e5795252474ebd04e4e872bd4152e86c558209 + 31fee41307f51d5108eba7a4c60e469ce06d620f https://github.com/dotnet/dotnet diff --git a/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index 878c84dde23f..43d80bb5f300 100644 --- a/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3098,7 +3098,7 @@ - + diff --git a/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index 9c56629318d0..51f3d2ea7815 100644 --- a/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -683,7 +683,7 @@ - + diff --git a/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index bc80bb7259c2..7b7ed9c49b03 100644 --- a/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -683,7 +683,7 @@ - + diff --git a/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl index 061506e7ef18..66c13a08a2e9 100644 --- a/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl @@ -4655,7 +4655,7 @@ - + diff --git a/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx b/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx index 808b49311e39..35d1e33ccd9f 100644 --- a/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx +++ b/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx @@ -1629,19 +1629,19 @@ - The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. - The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + The environment variable '{0}' is deprecated, and will be ignored. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. - The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. - The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + The settings file '{0}' is deprecated, and will be ignored. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. @@ -1705,4 +1705,15 @@ Codesign failed with 'errSecInternalComponent'. This usually means the keychain is locked, which is common when building over SSH. Unlock the keychain first, for example by running 'security unlock-keychain ~/Library/Keychains/login.keychain-db'. Shown when codesign fails with the 'errSecInternalComponent' error, which typically indicates a locked keychain. + + The runtime configuration file '{0}' is not a valid JSON object. + Shown when the main runtime configuration file (*.runtimeconfig.json) does not contain a valid JSON object at its root. +{0} - The path to the runtime configuration file. + + + Could not read the runtime configuration file '{0}': {1} + Shown when a runtime configuration file (*.runtimeconfig.json or *.runtimeconfig.dev.json) can't be read or parsed. +{0} - The path to the runtime configuration file. +{1} - The error message. + diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs index f06f132d6a7b..2897e24ab914 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs @@ -151,16 +151,16 @@ bool ExecuteImpl () if (appleSdkSettings.SystemHasEnvironmentVariable) { if (isNet11OrNewer) { - Log.LogWarning (MSBStrings.W7172 /* The environment variable '{0}' is deprecated, and will be ignored. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, XcodeLocator.EnvironmentVariableName); + Log.LogWarning (MSBStrings.W7172 /* The environment variable '{0}' is deprecated, and will be ignored. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. */, XcodeLocator.EnvironmentVariableName); } else { - Log.LogWarning (MSBStrings.W7171 /* The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, XcodeLocator.EnvironmentVariableName); + Log.LogWarning (MSBStrings.W7171 /* The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. */, XcodeLocator.EnvironmentVariableName); } } foreach (var file in appleSdkSettings.SystemExistingSettingsFiles) { if (isNet11OrNewer) { - Log.LogWarning (MSBStrings.W7174 /* The settings file '{0}' is deprecated, and will be ignored. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, file); + Log.LogWarning (MSBStrings.W7174 /* The settings file '{0}' is deprecated, and will be ignored. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. */, file); } else { - Log.LogWarning (MSBStrings.W7173 /* The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, file); + Log.LogWarning (MSBStrings.W7173 /* The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode. */, file); } } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/MergeRuntimeConfigFiles.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/MergeRuntimeConfigFiles.cs new file mode 100644 index 000000000000..8e0b7b66d4a5 --- /dev/null +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/MergeRuntimeConfigFiles.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; + +using Microsoft.Build.Framework; + +#nullable enable + +namespace Xamarin.MacDev.Tasks { + // This task merges the 'runtimeOptions.configProperties' from a '*.runtimeconfig.dev.json' file on top of + // the ones from the main '*.runtimeconfig.json' file, writing the merged result to an output file. + // + // We do this because we hand the runtime configuration directly to the runtime (bypassing hostfxr), and + // hostfxr is what would normally merge the dev file (which contains Debug-only switches such as Hot Reload) + // into the main runtime configuration. The dev values win, matching hostfxr's behavior. + public class MergeRuntimeConfigFiles : XamarinTask { + [Required] + public string RuntimeConfigFile { get; set; } = ""; + + public string? RuntimeConfigDevFile { get; set; } + + [Required] + public string OutputFile { get; set; } = ""; + + static readonly JsonDocumentOptions documentOptions = new JsonDocumentOptions { + AllowTrailingCommas = true, + CommentHandling = JsonCommentHandling.Skip, + }; + + JsonNode? TryParse (string path) + { + try { + using var stream = File.OpenRead (path); + return JsonNode.Parse (stream, documentOptions: documentOptions); + } catch (Exception e) { + Log.LogError (MSBStrings.E7186 /* Could not read the runtime configuration file '{0}': {1} */, path, e.Message); + return null; + } + } + + public override bool Execute () + { + if (TryParse (RuntimeConfigFile) is not JsonObject mainObject) { + if (!Log.HasLoggedErrors) + Log.LogError (MSBStrings.E7185 /* The runtime configuration file '{0}' is not a valid JSON object. */, RuntimeConfigFile); + return false; + } + + var devFile = RuntimeConfigDevFile; + if (devFile is not null && devFile.Length > 0 && File.Exists (devFile)) { + var devNode = TryParse (devFile); + if (devNode is null) + return false; // TryParse already logged an error. + var devConfigProperties = (devNode as JsonObject)? ["runtimeOptions"]? ["configProperties"] as JsonObject; + if (devConfigProperties is not null && devConfigProperties.Count > 0) { + var runtimeOptions = mainObject ["runtimeOptions"] as JsonObject; + if (runtimeOptions is null) { + runtimeOptions = new JsonObject (); + mainObject ["runtimeOptions"] = runtimeOptions; + } + + var configProperties = runtimeOptions ["configProperties"] as JsonObject; + if (configProperties is null) { + configProperties = new JsonObject (); + runtimeOptions ["configProperties"] = configProperties; + } + + foreach (var property in devConfigProperties) + configProperties [property.Key] = property.Value?.DeepClone (); + } + } + + var outputDirectory = Path.GetDirectoryName (OutputFile); + if (outputDirectory is not null && outputDirectory.Length > 0) + Directory.CreateDirectory (outputDirectory); + + using (var stream = File.Create (OutputFile)) + using (var writer = new Utf8JsonWriter (stream, new JsonWriterOptions { Indented = true })) + mainObject.WriteTo (writer); + + return !Log.HasLoggedErrors; + } + } +} diff --git a/msbuild/Xamarin.Shared/Xamarin.Shared.targets b/msbuild/Xamarin.Shared/Xamarin.Shared.targets index 7715f1b88a50..761ffa913492 100644 --- a/msbuild/Xamarin.Shared/Xamarin.Shared.targets +++ b/msbuild/Xamarin.Shared/Xamarin.Shared.targets @@ -3686,7 +3686,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - <_AssembliesToPrepare Include="@(ResolvedFileToPublish)" Condition="'%(ResolvedFileToPublish.Extension)' == '.dll' And '%(ResolvedFileToPublish.Culture)' == '' And !$([System.String]::Copy ('%(Filename)').EndsWith ('.resources'))" /> + <_AssembliesToPrepare Include="@(ResolvedFileToPublish)" Condition="('%(ResolvedFileToPublish.Extension)' == '.dll' Or '%(ResolvedFileToPublish.Extension)' == '.exe') And '%(ResolvedFileToPublish.Culture)' == '' And !$([System.String]::Copy ('%(Filename)').EndsWith ('.resources'))" /> $([MSBuild]::EnsureTrailingSlash('$(DeviceSpecificIntermediateOutputPath)prepared-assemblies')) @@ -3727,7 +3727,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - <_AssembliesToPostProcess Include="@(ResolvedFileToPublish)" Condition="'%(ResolvedFileToPublish.Extension)' == '.dll' And '%(ResolvedFileToPublish.Culture)' == '' And !$([System.String]::Copy ('%(Filename)').EndsWith ('.resources'))" /> + <_AssembliesToPostProcess Include="@(ResolvedFileToPublish)" Condition="('%(ResolvedFileToPublish.Extension)' == '.dll' Or '%(ResolvedFileToPublish.Extension)' == '.exe') And '%(ResolvedFileToPublish.Culture)' == '' And !$([System.String]::Copy ('%(Filename)').EndsWith ('.resources'))" /> <_PostprocessedAssembliesDirectory>$([MSBuild]::EnsureTrailingSlash('$(DeviceSpecificIntermediateOutputPath)postprocessed-assemblies')) @@ -3742,7 +3742,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. *files = [NSMutableArray array]; +#if defined (SUPPORTS_UNIVERSAL_BUILDS) + NSFileManager *manager = xamarin_is_multi_rid_build ? [NSFileManager defaultManager] : nil; +#endif + + for (const char * const *assembly = xamarin_trusted_platform_assembly_names; *assembly != NULL; assembly++) { + NSString *path = [NSString stringWithFormat: @"%s/%s", bundle_path, *assembly]; +#if defined (SUPPORTS_UNIVERSAL_BUILDS) + if (xamarin_is_multi_rid_build && ![manager fileExistsAtPath: path]) + path = [NSString stringWithFormat: @"%s/.xamarin/%s/%s", bundle_path, RUNTIMEIDENTIFIER, *assembly]; +#endif + [files addObject: path]; + } + + NSString *joined = [files componentsJoinedByString: @":"]; + return xamarin_strdup_printf ("%s", [joined UTF8String]); +} + // Find the directory that contains System.Private.CoreLib.dll, looking in: // - The bundle directory // - The runtimeidentifier-specific subdirectory diff --git a/runtime/xamarin/main.h b/runtime/xamarin/main.h index 8f41feb03601..4ce66510e185 100644 --- a/runtime/xamarin/main.h +++ b/runtime/xamarin/main.h @@ -15,6 +15,11 @@ #ifndef __XAMARIN_MAIN_H__ #define __XAMARIN_MAIN_H__ +// Universal builds are supported for macOS, Mac Catalyst, and simulator platforms. +#if TARGET_OS_OSX || TARGET_OS_MACCATALYST || ((TARGET_OS_IOS || TARGET_OS_TV) && TARGET_OS_SIMULATOR) +#define SUPPORTS_UNIVERSAL_BUILDS 1 +#endif + #ifdef __cplusplus extern "C" { #endif @@ -127,6 +132,10 @@ extern bool xamarin_supports_dynamic_registration; extern const char *xamarin_runtime_configuration_name; extern enum XamarinNativeLinkMode xamarin_libmono_native_link_mode; extern const char** xamarin_runtime_libraries; +extern const char * const *xamarin_trusted_platform_assembly_names; +#if defined (SUPPORTS_UNIVERSAL_BUILDS) +extern bool xamarin_is_multi_rid_build; +#endif typedef void (*xamarin_setup_callback) (); typedef int (*xamarin_extension_main_callback) (int argc, char** argv); diff --git a/scripts/changelog/Program.cs b/scripts/changelog/Program.cs new file mode 100644 index 000000000000..c36b3539ddbf --- /dev/null +++ b/scripts/changelog/Program.cs @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; + +namespace changelog { + + class Program { + static readonly List list = new (); + static readonly List filters = new (); + + // current repo (1) points to dotnet/installer (2) + // getting into other repos (pointed by dotnet/installer) can show different results + static int level = 2; + + static async Task Main (string [] args) + { + if (args.Length < 2) { + Console.Error.WriteLine ("Usage: changelog [repo-filter ...]"); + Environment.ExitCode = 1; + return; + } + + var pr = args [0]; + var outputFile = args [1]; + for (int i = 2; i < args.Length; i++) + filters.Add (args [i]); + + using (var writer = new StreamWriter (outputFile)) { + writer.WriteLine ($"# .NET Changelog for {pr}"); + if (TryGetGitHubPullRequestDiffUrl (pr, out var diffUrl)) + pr = diffUrl; + list.Add (pr); + await Process (writer); + writer.WriteLine ("Generated using scripts/changelog"); + } + } + + static bool TryGetGitHubPullRequestDiffUrl (string url, out string diffUrl) + { + diffUrl = url; + if (!Uri.TryCreate (url, UriKind.Absolute, out var uri)) + return false; + if (uri.Host != "github.com") + return false; + if (url.EndsWith (".diff", StringComparison.Ordinal)) + return false; + + var parts = uri.AbsolutePath.Split ('/', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length != 4 || parts [2] != "pull") + return false; + + diffUrl = $"https://patch-diff.githubusercontent.com/raw/{string.Join ('/', parts)}.diff"; + return true; + } + + static async Task Process (TextWriter writer) + { + using var client = new HttpClient (); + for (int i = 0; i < Math.Min (list.Count, level); i++) { + writer.WriteLine ($"## Level {i + 1}"); + var url = list [i]; + if (url.StartsWith ("https://", StringComparison.Ordinal)) { + using var result = await client.GetAsync (list [i]); + result.EnsureSuccessStatusCode (); + using var stream = await result.Content.ReadAsStreamAsync (); + ProcessDiff (stream, writer); + } else { + using var stream = new FileStream (url, FileMode.Open, FileAccess.Read); + ProcessDiff (stream, writer); + } + writer.WriteLine (); + } + } + + static bool Include (string uri) + { + if (filters.Count == 0) + return true; + + foreach (var filter in filters) { + if (uri.EndsWith (filter, StringComparison.Ordinal)) + return true; + } + return false; + } + + static void ProcessDiff (Stream s, TextWriter writer) + { + bool processing = false; + var uri = ""; + var old_sha = ""; + var new_sha = ""; + using (var sr = new StreamReader (s)) { + while (!sr.EndOfStream) { + var line = sr.ReadLine (); + if (line is null) + break; + if (line == "diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml") { + processing = true; + continue; + } + if (processing) { + if (line.StartsWith ("diff --git ", StringComparison.Ordinal)) + return; + if (line.Length < 1) + continue; + bool removal = (line [0] == '-'); + bool addition = (line [0] == '+'); + var tl = (removal || addition) ? line [1..] : line; + tl = tl.Trim (); + if (tl.StartsWith ("", StringComparison.Ordinal)) { + uri = tl [5..^6]; + old_sha = ""; + new_sha = ""; + } else if (removal && tl.StartsWith ("", StringComparison.Ordinal)) { + old_sha = tl [5..^6]; + } else if (addition && tl.StartsWith ("", StringComparison.Ordinal)) { + new_sha = tl [5..^6]; + if (!Include (uri)) + continue; + if (string.IsNullOrEmpty (old_sha)) { + writer.WriteLine ($"* {uri} [{new_sha [0..7]}]({uri}/commits/{new_sha}) (new dependency)"); + } else { + var diff_url = $"{uri}/compare/{old_sha}...{new_sha}.diff"; + writer.WriteLine ($"* {uri} [{old_sha [0..7]}...{new_sha [0..7]}]({uri}/compare/{old_sha}...{new_sha})"); + // skip duplicates (if same revisions are used) + if (!list.Contains (diff_url)) + list.Add (diff_url); + } + } + } + } + } + } + } +} diff --git a/scripts/changelog/README.md b/scripts/changelog/README.md new file mode 100644 index 000000000000..599edc954696 --- /dev/null +++ b/scripts/changelog/README.md @@ -0,0 +1,16 @@ + +# Changelog + +This tool reads dependency changes from a pull request and formats them as a +Markdown changelog. + +## Usage + +```sh +dotnet run --project scripts/changelog/changelog.csproj -- https://github.com/dotnet/macios/pull/11175 /tmp/changelog.txt +``` + +Additional arguments filter the dependency repositories included in the output. diff --git a/scripts/changelog/changelog.csproj b/scripts/changelog/changelog.csproj new file mode 100644 index 000000000000..bd08a2be8d8d --- /dev/null +++ b/scripts/changelog/changelog.csproj @@ -0,0 +1,9 @@ + + + + net$(BundledNETCoreAppTargetFrameworkVersion) + + diff --git a/scripts/changelog/fragment.mk b/scripts/changelog/fragment.mk new file mode 100644 index 000000000000..e07f8990a9c8 --- /dev/null +++ b/scripts/changelog/fragment.mk @@ -0,0 +1,4 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +include $(TOP)/scripts/template.mk +$(eval $(call TemplateScript,CHANGELOG,changelog)) diff --git a/src/AVFoundation/Enums.cs b/src/AVFoundation/Enums.cs index a387855b260f..85a7aa7410af 100644 --- a/src/AVFoundation/Enums.cs +++ b/src/AVFoundation/Enums.cs @@ -525,13 +525,12 @@ public enum AVAudioSessionInterruptionOptions : ulong { } /// An enumeration whose values define whether, after an audio session deactivates, previously interrupted audio sessions should or should not re-activate. - /// To be added. [MacCatalyst (13, 1)] [Flags] [Native] // NSUInteger - AVAudioSession.h public enum AVAudioSessionSetActiveOptions : ulong { - /// To be added. + /// Notifies other audio sessions that they can resume when this session deactivates. NotifyOthersOnDeactivation = 1, } @@ -1156,11 +1155,10 @@ public enum AVCaptureColorSpace : long { } /// Enumerates loop count limits. - /// To be added. [MacCatalyst (13, 1)] [Native] public enum AVMusicTrackLoopCount : long { - /// To be added. + /// Loops the music track indefinitely. Forever = -1, } @@ -1751,11 +1749,12 @@ public enum AVPlayerHdrMode : long { DolbyVision = 0x4, } + /// Specifies options for activating an audio session. [MacCatalyst (13, 1)] [Flags] [Native] public enum AVAudioSessionActivationOptions : ulong { - /// To be added. + /// No activation options are specified. None = 0x0, } diff --git a/src/AppKit/Enums.cs b/src/AppKit/Enums.cs index d5ab530d82ac..ad2ce62123eb 100644 --- a/src/AppKit/Enums.cs +++ b/src/AppKit/Enums.cs @@ -2538,11 +2538,12 @@ public enum NSFontTraitMask : ulong { Unitalic = 0x1000000, } + /// Specifies options for writing objects to a pasteboard. [NoMacCatalyst] [Flags] [Native] public enum NSPasteboardWritingOptions : ulong { - /// To be added. + /// The object promises to provide its pasteboard data later. WritingPromised = 1 << 9, } @@ -2924,11 +2925,12 @@ public enum NSLevelIndicatorStyle : ulong { RatingLevel, } + /// Specifies options for creating or modifying font collections. [NoMacCatalyst] [Flags] [Native] public enum NSFontCollectionOptions : long { - /// To be added. + /// Limits the font collection to the current application. ApplicationOnlyMask = 1, } @@ -4027,19 +4029,21 @@ public enum NSViewControllerTransitionOptions : ulong { AllowUserInteraction = 0x1000, } + /// Describes whether an application has visible content. [NoMacCatalyst] [Flags] [Native] public enum NSApplicationOcclusionState : ulong { - /// To be added. + /// At least part of the application's content is visible. Visible = 1 << 1, } + /// Describes whether a window is visible to the user. [NoMacCatalyst] [Flags] [Native] public enum NSWindowOcclusionState : ulong { - /// To be added. + /// At least part of the window is visible. Visible = 1 << 1, } @@ -4181,11 +4185,12 @@ public enum NSSpringLoadingOptions : ulong { NoHover = 1 << 3, } + /// Specifies how to order windows in a window list. [NoMacCatalyst] [Flags] [Native] public enum NSWindowListOptions : long { - /// To be added. + /// Orders windows from front to back. OrderedFrontToBack = (1 << 0), } @@ -4316,10 +4321,11 @@ public enum NSTabViewBorderType : ulong { Bezel, } + /// Specifies options for replacing the contents of a pasteboard. [NoMacCatalyst] [Native] public enum NSPasteboardContentsOptions : ulong { - /// To be added. + /// Restricts the pasteboard contents to the current host. CurrentHostOnly = 1, } @@ -4453,11 +4459,12 @@ public enum NSColorType : long { Catalog, } + /// Specifies options for requesting downloadable font assets. [NoMacCatalyst] [Native] [Flags] public enum NSFontAssetRequestOptions : ulong { - /// To be added. + /// Displays the standard user interface while downloading fonts. UsesStandardUI = 1 << 0, } diff --git a/src/AppKit/NSApplication.cs b/src/AppKit/NSApplication.cs index b11eb5bfaa53..18248837792d 100644 --- a/src/AppKit/NSApplication.cs +++ b/src/AppKit/NSApplication.cs @@ -32,9 +32,8 @@ namespace AppKit { public partial class NSApplication : NSResponder { - /// To be added. - /// To be added. - public static bool CheckForIllegalCrossThreadCalls = true; + /// + public static bool CheckForIllegalCrossThreadCalls; /// To be added. /// To be added. public static bool CheckForEventAndDelegateMismatches = true; @@ -53,6 +52,12 @@ public static void Init () internal static void InitializeApplication () { + // The linker replaces the 'Runtime.CheckForIllegalCrossThreadCalls' getter with a constant value, so when the UI + // thread checks are disabled the assignment below (and the 'CheckForIllegalCrossThreadCalls' field + // itself, unless something else references it) is trimmed away. + if (Runtime.CheckForIllegalCrossThreadCalls) + CheckForIllegalCrossThreadCalls = true; + SynchronizationContext.SetSynchronizationContext (new AppKitSynchronizationContext ()); } diff --git a/src/AudioUnit/AUEnums.cs b/src/AudioUnit/AUEnums.cs index a7adc8542cb8..3fd51f5ad02c 100644 --- a/src/AudioUnit/AUEnums.cs +++ b/src/AudioUnit/AUEnums.cs @@ -358,11 +358,12 @@ public enum AudioObjectPropertyScope : uint { PlayThrough = 1886679669, // 'ptru' } + /// Identifies an element of an audio object property. [MacCatalyst (13, 1)] [NoTV] [NoiOS] public enum AudioObjectPropertyElement : uint { - /// To be added. + /// The main element of the audio object. Main = 0, // 0 } @@ -1197,8 +1198,9 @@ public enum AUHostTransportStateFlags : ulong { Cycling = 8, } + /// Specifies sample times for scheduling audio unit events. public enum AUEventSampleTime : long { - /// To be added. + /// Schedules the event to occur immediately. Immediate = unchecked((long) 0xffffffff00000000), } diff --git a/src/CoreMotion/Defs.cs b/src/CoreMotion/Defs.cs index 293cd19e1fcd..16d7304017b2 100644 --- a/src/CoreMotion/Defs.cs +++ b/src/CoreMotion/Defs.cs @@ -168,7 +168,6 @@ public override string ToString () // untyped enum -> CMDeviceMotion.h /// An enumeration whose values specify the quality of the magnetometer calibration. - /// To be added. public enum CMMagneticFieldCalibrationAccuracy { /// Magnetic calibration has not occurred. Uncalibrated = -1, diff --git a/src/CoreTelephony/CTEnums.cs b/src/CoreTelephony/CTEnums.cs index 1ac9b4543d02..ba8e7d78715e 100644 --- a/src/CoreTelephony/CTEnums.cs +++ b/src/CoreTelephony/CTEnums.cs @@ -7,11 +7,11 @@ namespace CoreTelephony { // in header file this is used inside a CTError structure where the domain is a SInt32 /// An enumeration whose values specify an error domain. public enum CTErrorDomain { - /// To be added. + /// No error occurred. NoError = 0, - /// To be added. + /// The error is in the POSIX error domain. Posix = 1, - /// To be added. + /// The error is in the Mach error domain. Mach = 2, } @@ -19,23 +19,25 @@ public enum CTErrorDomain { [MacCatalyst (13, 1)] [Native] public enum CTCellularDataRestrictedState : ulong { - /// To be added. + /// The cellular data restriction state is unknown. Unknown, - /// To be added. + /// Cellular data access is restricted. Restricted, - /// To be added. + /// Cellular data access is not restricted. NotRestricted, } + /// Enumerates the results of adding a cellular plan. [MacCatalyst (13, 1)] [Native] public enum CTCellularPlanProvisioningAddPlanResult : long { - /// To be added. + /// The result is unknown. Unknown, - /// To be added. + /// The cellular plan could not be added. Fail, - /// To be added. + /// The cellular plan was added successfully. Success, + /// The operation was canceled. [iOS (17, 0)] Cancel, } diff --git a/src/CoreVideo/CVEnums.cs b/src/CoreVideo/CVEnums.cs index 3bbf1c319ae3..e907f0dee141 100644 --- a/src/CoreVideo/CVEnums.cs +++ b/src/CoreVideo/CVEnums.cs @@ -102,7 +102,7 @@ public enum CVReturn : int { /// A flagging enumeration. Currently only contains a None value of 0. [MacCatalyst (13, 1)] public enum CVOptionFlags : long { - /// To be added. + /// No options are specified. None = 0, } @@ -110,7 +110,7 @@ public enum CVOptionFlags : long { [Flags] [MacCatalyst (13, 1)] public enum CVTimeFlags : int { - /// To be added. + /// The time value is indefinite. IsIndefinite = 1 << 0, } @@ -173,7 +173,7 @@ public enum CVSMPTETimeType : uint { /// Defines an option for . [MacCatalyst (13, 1)] public enum CVPixelBufferPoolFlushFlags : ulong { - /// To be added. + /// Releases all unused buffers from the pool. FlushExcessBuffers = 1, } diff --git a/src/EventKitUI/Defs.cs b/src/EventKitUI/Defs.cs index 422afac4eb41..a8277dbfb0a4 100644 --- a/src/EventKitUI/Defs.cs +++ b/src/EventKitUI/Defs.cs @@ -14,31 +14,28 @@ namespace EventKitUI { // untyped enum -> EKCalendarChooser.h // iOS 9 promoted this to an NSInteger - which breaks compatibility /// An enumeration whose values specify whether a single or multiple calendars can be chosen by an object. - /// To be added. [Native] public enum EKCalendarChooserSelectionStyle : long { - /// To be added. + /// Allows the user to select one calendar. Single, - /// To be added. + /// Allows the user to select multiple calendars. Multiple, } // untyped enum -> EKCalendarChooser.h // iOS 9 promoted this to an NSInteger - which breaks compatibility /// An enumeration whose values specify which calendars are displayed by a . - /// To be added. [Native] public enum EKCalendarChooserDisplayStyle : long { - /// To be added. + /// Displays all calendars. AllCalendars, - /// To be added. + /// Displays only calendars that the user can modify. WritableCalendarsOnly, } // untyped enum -> EKEventViewController.h // iOS 9 promoted this to an NSInteger - which breaks compatibility /// Enumerates actions that a user can take to dismiss an event view controller. - /// To be added. [Native] public enum EKEventViewAction : long { /// The user tapped "Done". @@ -52,7 +49,6 @@ public enum EKEventViewAction : long { // untyped enum -> EKEventEditViewController.h // iOS 9 promoted this to an NSInteger - which breaks compatibility /// Enumerates possible actions that a user can take when editing a view. - /// To be added. [Native] public enum EKEventEditViewAction : long { /// The user canceled the change to the event. diff --git a/src/Foundation/Enum.cs b/src/Foundation/Enum.cs index ba806c598e9b..7dd43f033c64 100644 --- a/src/Foundation/Enum.cs +++ b/src/Foundation/Enum.cs @@ -1263,20 +1263,18 @@ public enum NSNumberFormatterRoundingMode : ulong { } /// Allows the application developer to specify that the old version of the file should be removed from the version store. - /// To be added. [Flags] [Native] public enum NSFileVersionReplacingOptions : ulong { - /// To be added. + /// Moves the replacement file instead of copying it. ByMoving = 1 << 0, } /// Allows the application developer to specify that a new file version should be created by moving the source file. - /// To be added. [Flags] [Native] public enum NSFileVersionAddingOptions : ulong { - /// To be added. + /// Moves the source file instead of copying it. ByMoving = 1 << 0, } @@ -2259,10 +2257,11 @@ public enum NSItemProviderRepresentationVisibility : long { OwnProcess = 3, } + /// Specifies how an item provider supplies a file. [MacCatalyst (13, 1)] [Native] public enum NSItemProviderFileOptions : long { - /// To be added. + /// Opens the file in place instead of copying it. OpenInPlace = 1, } diff --git a/src/Foundation/NSObject2.cs b/src/Foundation/NSObject2.cs index 2a286be68f97..ae2f04e0496c 100644 --- a/src/Foundation/NSObject2.cs +++ b/src/Foundation/NSObject2.cs @@ -329,6 +329,11 @@ public NSObject () { bool alloced = AllocIfNeeded (); InitializeObject (alloced); + // This constructor doesn't send 'init', so the handle is final. Complete any + // deferred registration for user types (see #25861); no-op if already registered + // (e.g. direct bindings, which InitializeObject registers eagerly). + if (alloced && !Runtime.RegisterObjectsBeforeInit) + Runtime.RegisterNSObject (this, handle, onlyIfNeeded: true); } // This is just here as a constructor chain that can will @@ -509,20 +514,35 @@ private void InitializeObject (bool alloced) // and any subclasses in the platform assembly which is not a direct binding have // to set the correct value in their constructors. IsDirectBinding = (this.GetType ().Assembly == PlatformAssembly); - Runtime.RegisterNSObject (this, handle); bool native_ref = (flags & Flags.NativeRef) == Flags.NativeRef; - CreateManagedRef (!alloced || native_ref); + + if (!Runtime.TryGetIsUserType (handle, out var isUserType, out var error_message)) + throw new InvalidOperationException ($"Unable to create a managed reference for the pointer {handle} whose managed type is {GetType ().FullName} because it wasn't possible to get the class of the pointer: {error_message}"); + + // Issue #25861: when we've just alloc'd a user type, defer adding it to the + // object_map until 'init' has completed. A native 'init' may free this handle + // and return a different one; we don't want a pointer to freed memory lingering + // in the map. User types carry their gchandle in a native ivar (set by + // CreateManagedRef below), which serves as a fallback lookup during 'init', so + // deferring their object_map registration is safe. The final handle is registered + // later (via InitializeHandle for the generated alloc+init constructors, or right + // after this call for the parameterless NSObject constructor which doesn't send + // 'init'). Direct bindings have no ivar, so they must remain registered throughout + // 'init' (e.g. so a native 'init' that surfaces 'self' to managed code resolves to + // the wrapper being constructed) and are registered eagerly here. + if (!alloced || !isUserType || Runtime.RegisterObjectsBeforeInit) + Runtime.RegisterNSObject (this, handle); + + CreateManagedRef (isUserType, !alloced || native_ref); } [DllImport ("__Internal")] static extern byte xamarin_set_gchandle_with_flags_safe (IntPtr handle, IntPtr gchandle, XamarinGCHandleFlags gchandle_flags, IntPtr data); - void CreateManagedRef (bool retain) + void CreateManagedRef (bool isUserType, bool retain) { HasManagedRef = true; - if (!Runtime.TryGetIsUserType (handle, out var isUserType, out var error_message)) - throw new InvalidOperationException ($"Unable to create a managed reference for the pointer {handle} whose managed type is {GetType ().FullName} because it wasn't possible to get the class of the pointer: {error_message}"); if (isUserType) { var gchandle_flags = XamarinGCHandleFlags.HasManagedRef | XamarinGCHandleFlags.InitialSet; @@ -543,6 +563,37 @@ void CreateManagedRef (bool retain) DangerousRetain (); } + // Issue #25861: if 'init' returned a different handle than 'alloc' for a user type, + // the gchandle ivar was set on the (now typically freed) alloc'd handle. Make sure + // the final handle also has a gchandle ivar pointing back at this managed object, so + // it can be resolved native->managed. Does nothing for direct bindings (no ivar) or + // if the ivar is already set. + void EnsureManagedReference (NativeHandle newHandle) + { + if (!Runtime.TryGetIsUserType (newHandle, out var isUserType, out var _) || !isUserType) + return; + if (Runtime.GetGCHandleForObject (newHandle) != IntPtr.Zero) + return; + HasManagedRef = true; + var gchandle_flags = XamarinGCHandleFlags.HasManagedRef | XamarinGCHandleFlags.InitialSet; + var gchandle = GCHandle.Alloc (this, GCHandleType.WeakTrackResurrection); + var h = GCHandle.ToIntPtr (gchandle); + byte rv; + unsafe { + rv = xamarin_set_gchandle_with_flags_safe (newHandle, h, gchandle_flags, (IntPtr) GetData ()); + } + if (rv == 0) { + // The ivar slot was already claimed (e.g. another managed wrapper won a race + // to represent this native object). Free the gchandle we allocated. We keep + // HasManagedRef set (it was already set by CreateManagedRef): this object + // still owns the +1 that 'init' transferred to 'newHandle', and that +1 must + // still be released via ReleaseManagedRef on disposal. This mirrors the same + // case in CreateManagedRef. + Runtime.NSLog ($"Tried to create a managed reference from an object that already has a managed reference (type: {GetType ()})"); + gchandle.Free (); + } + } + void ReleaseManagedRef () { var handle = this.Handle; // Get a copy of the handle, because it will be cleared out when calling Runtime.NativeObjectHasDied, and we still need the handle later. @@ -800,8 +851,15 @@ public NativeHandle Handle { if (handle == value) return; - if (handle != IntPtr.Zero) - Runtime.UnregisterNSObject (handle); + if (handle != IntPtr.Zero) { + // Issue #25861: use the ownership-aware unregister so we don't remove an + // object_map entry that another object created after reusing this (freed) + // address. The legacy switch restores the previous unconditional removal. + if (Runtime.RegisterObjectsBeforeInit) + Runtime.UnregisterNSObject (handle); + else + Runtime.UnregisterNSObject (handle, this); + } handle = value; @@ -843,7 +901,24 @@ protected internal void InitializeHandle (NativeHandle handle, string initSelect throw new Exception ($"Could not initialize an instance of the type '{GetType ().FullName}': the native '{initSelector}' method returned nil.\n{Constants.SetThrowOnInitFailureToFalse}."); } + // Transition to the final (post-'init') handle. The Handle setter (ownership-aware) + // unregisters the previous handle if needed and registers the new one. + var previousHandle = this.handle; this.Handle = handle; + + // Issue #25861: registration for user types was deferred in InitializeObject. + if (!Runtime.RegisterObjectsBeforeInit && handle != NativeHandle.Zero) { + if (handle == previousHandle) { + // 'init' returned the same handle, so the setter above was a no-op. + // Complete the deferred registration now (no-op if already registered). + Runtime.RegisterNSObject (this, handle, onlyIfNeeded: true); + } else { + // 'init' returned a different handle; the gchandle ivar was set on the + // previous (now typically freed) handle, so re-establish it on the final + // handle for user types. + EnsureManagedReference (handle); + } + } } private bool AllocIfNeeded () diff --git a/src/ILLink.Substitutions.MacCatalyst.xml b/src/ILLink.Substitutions.MacCatalyst.xml index ee43aef3feb0..989dd10b8356 100644 --- a/src/ILLink.Substitutions.MacCatalyst.xml +++ b/src/ILLink.Substitutions.MacCatalyst.xml @@ -16,6 +16,8 @@ + + @@ -28,6 +30,7 @@ + diff --git a/src/ILLink.Substitutions.iOS.xml b/src/ILLink.Substitutions.iOS.xml index 46917dd3ff18..3a18271bc5a3 100644 --- a/src/ILLink.Substitutions.iOS.xml +++ b/src/ILLink.Substitutions.iOS.xml @@ -18,6 +18,8 @@ + + @@ -45,6 +47,7 @@ + diff --git a/src/ILLink.Substitutions.macOS.xml b/src/ILLink.Substitutions.macOS.xml index 2a96f0fa3ea1..99c2763bb8bb 100644 --- a/src/ILLink.Substitutions.macOS.xml +++ b/src/ILLink.Substitutions.macOS.xml @@ -15,6 +15,8 @@ + + @@ -27,6 +29,7 @@ + diff --git a/src/ILLink.Substitutions.tvOS.xml b/src/ILLink.Substitutions.tvOS.xml index 58f1561ee741..c8934a1251ae 100644 --- a/src/ILLink.Substitutions.tvOS.xml +++ b/src/ILLink.Substitutions.tvOS.xml @@ -18,6 +18,8 @@ + + @@ -45,6 +47,7 @@ + diff --git a/src/MapKit/MKEnums.cs b/src/MapKit/MKEnums.cs index 93d24613dd84..fdd8223ab817 100644 --- a/src/MapKit/MKEnums.cs +++ b/src/MapKit/MKEnums.cs @@ -37,7 +37,6 @@ public enum MKDirectionsTransportType : ulong { // NSUInteger -> MKTypes.h /// The type of map. - /// To be added. [MacCatalyst (13, 1)] [Native] public enum MKMapType : ulong { @@ -51,7 +50,7 @@ public enum MKMapType : ulong { SatelliteFlyover, /// A flyover that combines satellite and cartographic imagery. HybridFlyover, - /// A muted map that emphasized developer data. + /// A muted map that emphasizes developer data. [MacCatalyst (13, 1)] MutedStandard, } diff --git a/src/ObjCRuntime/Runtime.cs b/src/ObjCRuntime/Runtime.cs index 64f06cbeaedc..6ce5724594d4 100644 --- a/src/ObjCRuntime/Runtime.cs +++ b/src/ObjCRuntime/Runtime.cs @@ -10,6 +10,7 @@ #nullable enable +using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; @@ -290,6 +291,34 @@ public static bool DynamicRegistrationSupported { [BindingImpl (BindingImplOptions.Optimizable)] internal static bool UseCFNetworkHandler => AppContext.TryGetSwitch ("System.Net.Http.NativeHandler.UseCFNetworkHandler", out bool isDefault) ? isDefault : false; + // Issue #25861: when false (the default), NSObjects created via alloc/init are + // added to the object_map only after 'init' has completed. This way a native + // 'init' that frees the alloc'd handle (and returns a different one) can't leave + // a stale pointer to freed memory in the map, which could later be clobbered when + // the memory is reused by another object. Set this AppContext switch to true to + // restore the previous behavior (register the object right after 'alloc'). + internal static bool RegisterObjectsBeforeInit => AppContext.TryGetSwitch ("ObjCRuntime.Runtime.RegisterObjectsBeforeInit", out var value) && value; + + // The linker may turn calls to this property into a constant + /// Determines whether the debug builds will enforce that calls done to AppKit/UIKit APIs are only issued from the UI thread. + /// + /// + /// On debug builds, the runtime will enforce that calls made to + /// AppKit/UIKit APIs are only done from the main thread. This is + /// useful to spot code that could inadvertently use AppKit/UIKit from + /// a non-UI thread which can corrupt state and could lead to + /// very hard to debug problems. + /// + /// + /// But sometimes it might be useful to disable this check, + /// either because you can ensure that AppKit/UIKit is not in use at + /// this point or because the APIs in question might have later been + /// relaxed or made thread safe by Apple. + /// + /// + [BindingImpl (BindingImplOptions.Optimizable)] + internal static bool CheckForIllegalCrossThreadCalls => AppContext.TryGetSwitch ("ObjCRuntime.Runtime.CheckForIllegalCrossThreadCalls", out bool enabled) ? enabled : true; + internal static bool Initialized { get { return initialized; } } @@ -1184,6 +1213,21 @@ internal static void UnregisterNSObject (IntPtr ptr) } } + // Ownership-aware variant of UnregisterNSObject: only removes the entry if it + // still refers to `managed` (or is dead). This avoids clobbering an entry that + // another object created after reusing a freed native pointer (issue #25861). + internal static void UnregisterNSObject (IntPtr ptr, NSObject managed) + { + lock (lock_obj) { + if (object_map.TryGetValue (ptr, out var value)) { + if (value.Target is null || object.ReferenceEquals (value.Target, managed)) { + object_map.Remove (ptr); + value.Free (); + } + } + } + } + internal static void NativeObjectHasDied (IntPtr ptr, NSObject? managed_obj) { lock (lock_obj) { @@ -1204,7 +1248,12 @@ internal static void NativeObjectHasDied (IntPtr ptr, NSObject? managed_obj) } } - internal static void RegisterNSObject (NSObject obj, IntPtr ptr) + // Completes deferred object_map registration (issue #25861): when 'onlyIfNeeded' is + // true, registers the object only if the pointer isn't already present, and leaves + // any existing entry untouched. This avoids redundantly re-registering objects that + // were registered eagerly (e.g. direct bindings), and avoids clobbering a concurrent + // registration (e.g. another object reusing a freed native pointer). + internal static void RegisterNSObject (NSObject obj, IntPtr ptr, bool onlyIfNeeded = false) { GCHandle handle; if (Runtime.IsCoreCLR) { @@ -1214,8 +1263,17 @@ internal static void RegisterNSObject (NSObject obj, IntPtr ptr) } lock (lock_obj) { - if (object_map.Remove (ptr, out var existing)) - existing.Free (); + if (onlyIfNeeded) { + if (object_map.ContainsKey (ptr)) { + // Already registered; don't touch the existing entry, just free the + // handle we speculatively allocated. + handle.Free (); + return; + } + } else { + if (object_map.Remove (ptr, out var existing)) + existing.Free (); + } object_map [ptr] = handle; #pragma warning disable RBI0014 obj.Handle = ptr; @@ -1845,6 +1903,12 @@ internal static bool RemoveFromObjectMap (NSObject obj) var o = TryGetNSObject (ptr, evenInFinalizerQueue); + // Fallback for issue #25861: a user type still executing its own 'init' isn't in + // the object_map yet (deferred until 'init' completes), but carries its gchandle + // in a native ivar. Safe here because GetNSObject is only called for Objective-C + // objects. See TryGetNSObjectFromIvar for why this can't live in TryGetNSObject. + o ??= TryGetNSObjectFromIvar (ptr, evenInFinalizerQueue); + if (o is not null) { if (owns) o.DangerousRelease (); @@ -1901,6 +1965,11 @@ internal static bool RemoveFromObjectMap (NSObject obj) var obj = TryGetNSObject (ptr, evenInFinalizerQueue: evenInFinalizerQueue); + // Fallback for issue #25861: resolve a user type still executing its own 'init' + // (not yet in the object_map) via its native gchandle ivar. See the non-generic + // GetNSObject for why this is safe here. + obj ??= TryGetNSObjectFromIvar (ptr, evenInFinalizerQueue); + // First check if we got an object of the expected type if (obj is T o) return o; @@ -2689,6 +2758,85 @@ internal static Type FindClosedParameterType (object instance, RuntimeTypeHandle return parameters [parameter].ParameterType.GetElementType ()!; // FIX NAMING } + // Caches the closed generic helper method per (open helper method, closed instance type), so + // that the reflection cost (FindClosedTypeInHierarchy + MakeGenericMethod) is only paid once + // per instantiation instead of on every call. + // + // The cache lives in a nested type (rather than as a field initializer on Runtime) so its + // ConcurrentDictionary instantiation is constructed by the nested type's static constructor + // - which only runs the first time InvokeGenericRegistrarTrampoline actually accesses it. + // InvokeGenericRegistrarTrampoline is only ever reachable under a Hot-Reload-compatible + // build, so in every other configuration (e.g. Release/NativeAOT) the trampoline is trimmed + // and this nested type - together with the ConcurrentDictionary instantiation - is trimmed + // with it, keeping it out of Runtime's static constructor and out of the app. + static class ClosedGenericRegistrarTrampolines { + internal static readonly ConcurrentDictionary<(RuntimeMethodHandle OpenImplMethod, RuntimeTypeHandle ClosedInstanceType), MethodInfo> Cache = new (); + } + + // Invokes a relocated generic registrar trampoline helper. + // + // When the trimmable static registrar relocates the registrar trampolines into a companion + // assembly (for Hot Reload, so the user assembly stays unmodified), the trampoline for a + // method declared in a generic type can't be relocated as-is: the static UnmanagedCallersOnly + // callback doesn't know the generic parameters of the instance, and we can't add the + // virtual-dispatch proxy to the user type (that would modify the user assembly). Instead we + // emit a *generic* helper method ('open_impl' below) into the companion assembly whose body + // performs the type-parameter-aware conversions, and the static callback dispatches to it + // here: we close the generic helper over the instance's actual generic arguments and invoke + // it. This reflection-based dispatch is only ever used under a Hot-Reload-compatible build, + // which always runs under the JIT (never NativeAOT), so MakeGenericMethod is safe. + // + // 'args' holds all the arguments of the helper: the instance, followed by the native + // arguments, followed by the trailing 'out IntPtr exception_gchandle' slot. The callback + // allocates the array with that extra slot so that no copy is needed here. This method + // invokes the closed helper and returns its (boxed) native return value. Any failure is + // caught and reported through 'exception_gchandle' so no exception escapes the + // UnmanagedCallersOnly boundary. + internal static object? InvokeGenericRegistrarTrampoline (object instance, RuntimeTypeHandle open_user_type_handle, RuntimeMethodHandle open_impl_method_handle, object? [] args, out IntPtr exception_gchandle) + { + // This method uses reflection (MakeGenericMethod + MethodInfo.Invoke), which requires + // dynamic code and isn't supported by NativeAOT. It's only ever reached under a + // Hot-Reload-compatible build, which always runs under the JIT (never NativeAOT). The + // IsNativeAOT check is optimizable, so the linker folds it to a constant and removes the + // reflection code below as unreachable in a NativeAOT build - which also elides the + // IL2060/IL3050 trimmer/AOT warnings that MakeGenericMethod would otherwise produce. + if (IsNativeAOT) + throw CreateNativeAOTNotSupportedException (); + + exception_gchandle = IntPtr.Zero; + try { + var closed_instance_type = instance.GetType (); + var cache_key = (open_impl_method_handle, closed_instance_type.TypeHandle); + MethodInfo closed_impl; + if (ClosedGenericRegistrarTrampolines.Cache.TryGetValue (cache_key, out var cached_impl)) { + closed_impl = cached_impl; + } else { + var open_user_type = Type.GetTypeFromHandle (open_user_type_handle); + if (open_user_type is null) + throw new InvalidOperationException ("Could not resolve the open generic type of a relocated registrar trampoline."); + var closed_user_type = FindClosedTypeInHierarchy (open_user_type, closed_instance_type); + if (closed_user_type is null) + throw new InvalidOperationException ($"Could not find the type '{open_user_type.FullName}' in the type hierarchy of '{closed_instance_type.FullName}'."); + if (MethodBase.GetMethodFromHandle (open_impl_method_handle) is not MethodInfo open_impl) + throw new InvalidOperationException ("Could not resolve the generic helper method of a relocated registrar trampoline."); + closed_impl = open_impl.MakeGenericMethod (closed_user_type.GetGenericArguments ()); + ClosedGenericRegistrarTrampolines.Cache.TryAdd (cache_key, closed_impl); + } + + // The trailing 'out IntPtr exception_gchandle' slot is pre-initialized to IntPtr.Zero so + // that the (success) code path, which leaves the byref output untouched, reports "no + // exception". + var exception_slot = args.Length - 1; + args [exception_slot] = IntPtr.Zero; + var rv = closed_impl.Invoke (null, args); + exception_gchandle = (IntPtr) (args [exception_slot] ?? IntPtr.Zero); + return rv; + } catch (Exception e) { + exception_gchandle = AllocGCHandle (e); + return null; + } + } + // This method might be called by the generated code from the managed static registrar. static void TraceCaller (string message) { @@ -2774,6 +2922,44 @@ static bool GetIsARM64CallingConvention () return GCHandle.FromIntPtr (ptr).Target; } + // Returns the gchandle stored in the native object's gchandle ivar (user types + // only; INVALID_GCHANDLE/zero otherwise). + [DllImport ("__Internal")] + static extern IntPtr xamarin_get_gchandle (IntPtr obj); + + internal static IntPtr GetGCHandleForObject (IntPtr ptr) + { + return xamarin_get_gchandle (ptr); + } + + // Fallback lookup for issue #25861: a user-type object that hasn't been added to + // the object_map yet (e.g. it's still executing its own 'init') can still be + // resolved via the gchandle stored in its native ivar. Returns null for direct + // bindings (which have no ivar) and for objects without a managed reference. + internal static NSObject? TryGetNSObjectFromIvar (IntPtr ptr) + { + var gchandle = xamarin_get_gchandle (ptr); + if (gchandle == IntPtr.Zero) + return null; + return GetGCHandleTarget (gchandle) as NSObject; + } + + // Guarded ivar fallback for issue #25861: resolve a user type that's still executing + // its own 'init' (and so isn't in the object_map yet) via its native gchandle ivar, + // only returning it if it still owns 'ptr' and isn't queued for finalization (unless + // asked otherwise). MUST only be called with an Objective-C object pointer: it sends + // the xamarinGetGCHandle message, which crashes on non-Objective-C native handles. + // That's why this isn't folded into the general TryGetNSObject (which can be called + // with arbitrary native handles, e.g. from GetINativeObject); it's only safe from + // GetNSObject/GetNSObject, which are only ever called for Objective-C objects. + static NSObject? TryGetNSObjectFromIvar (IntPtr ptr, bool evenInFinalizerQueue) + { + var fromIvar = TryGetNSObjectFromIvar (ptr); + if (fromIvar is not null && fromIvar.Handle == ptr && (evenInFinalizerQueue || !fromIvar.InFinalizerQueue)) + return fromIvar; + return null; + } + // Allocate a GCHandle and return the IntPtr to it. internal static IntPtr AllocGCHandle (object? value) { diff --git a/src/PdfKit/Enums.cs b/src/PdfKit/Enums.cs index 109a8710547b..261685431eea 100644 --- a/src/PdfKit/Enums.cs +++ b/src/PdfKit/Enums.cs @@ -33,8 +33,7 @@ namespace PdfKit { - /// Enumerates named PDF action names. - /// To be added. + /// Enumerates named actions that can be performed in a PDF document. [Native] [TV (18, 2)] public enum PdfActionNamedName : long { @@ -65,7 +64,6 @@ public enum PdfActionNamedName : long { } /// Enumerates annotation widget controls. - /// To be added. [Native] [TV (18, 2)] public enum PdfWidgetControlType : long { @@ -79,8 +77,7 @@ public enum PdfWidgetControlType : long { CheckBox = 2, } - /// Enumerates line ending styles - /// To be added. + /// Enumerates line ending styles. [Native] [TV (18, 2)] public enum PdfLineStyle : long { @@ -98,8 +95,7 @@ public enum PdfLineStyle : long { ClosedArrow = 5, } - /// Indicates annotation markup types. - /// To be added. + /// Enumerates annotation markup types. [Native] [TV (18, 2)] public enum PdfMarkupType : long { @@ -109,11 +105,11 @@ public enum PdfMarkupType : long { StrikeOut = 1, /// Indicates an underline markup. Underline = 2, + /// Indicates a redaction markup. Redact = 3, } /// Enumerates annotation icon types. - /// To be added. [Native] [TV (18, 2)] public enum PdfTextAnnotationIconType : long { @@ -134,7 +130,6 @@ public enum PdfTextAnnotationIconType : long { } /// Enumerates annotation border styles. - /// To be added. [Native] [TV (18, 2)] public enum PdfBorderStyle : long { @@ -176,7 +171,6 @@ public enum PdfDocumentPermissions : long { } /// Enumerates Adobe-specified PDF display box boundaries. - /// To be added. [Native] [TV (18, 2)] public enum PdfDisplayBox : long { @@ -192,8 +186,7 @@ public enum PdfDisplayBox : long { Art = 4, } - /// Enumerated PDF display modes. - /// To be added. + /// Enumerates PDF display modes. [Native] [TV (18, 2)] public enum PdfDisplayMode : long { @@ -207,8 +200,7 @@ public enum PdfDisplayMode : long { TwoUpContinuous = 3, } - /// Orable flags that describe areas of interest for a touch position. - /// To be added. + /// Bitwise flags that describe areas of interest for a touch position. [Flags] [Native] [TV (18, 2)] @@ -233,6 +225,7 @@ public enum PdfAreaOfInterest : long { PopupArea = 1 << 7, /// Indicates that the touch position is over an image. ImageArea = 1 << 8, + /// Indicates that all areas of interest are included. [iOS (15, 0), MacCatalyst (15, 0)] AnyArea = Int64.MaxValue, } diff --git a/src/SafariServices/SSEnums.cs b/src/SafariServices/SSEnums.cs index 234cfc8ecc8a..76447906bfee 100644 --- a/src/SafariServices/SSEnums.cs +++ b/src/SafariServices/SSEnums.cs @@ -11,13 +11,13 @@ namespace SafariServices { // NSInteger -> SSReadingList.h - /// An enumeration that specify possible errors associated with adding a URL to the Safari Reading List. + /// Enumerates errors that can occur when adding a URL to the Safari Reading List. [NoMac] [MacCatalyst (14, 0)] [Native ("SSReadingListErrorCode")] [ErrorDomain ("SSReadingListErrorDomain")] public enum SSReadingListError : long { - /// To be added. + /// The URL scheme is not supported by the Safari Reading List. UrlSchemeNotAllowed = 1, } diff --git a/src/SceneKit/Defs.cs b/src/SceneKit/Defs.cs index b46af23fb6d0..61c81b5e15bd 100644 --- a/src/SceneKit/Defs.cs +++ b/src/SceneKit/Defs.cs @@ -12,11 +12,12 @@ namespace SceneKit { + /// Identifies errors reported by SceneKit. [MacCatalyst (13, 1)] [Native] // untyped enum (SceneKitTypes.h) but described as the value of `code` for `NSError` which is an NSInteger [ErrorDomain ("SCNErrorDomain")] public enum SCNErrorCode : long { - /// To be added. + /// A shader program failed to compile. ProgramCompilationError = 1, } diff --git a/src/UIKit/UIApplication.cs b/src/UIKit/UIApplication.cs index 2a90338217f8..b8df746455f9 100644 --- a/src/UIKit/UIApplication.cs +++ b/src/UIKit/UIApplication.cs @@ -26,25 +26,8 @@ public UIKitThreadAccessException () : base ("UIKit Consistency error: you are c public partial class UIApplication : UIResponder { - /// Determines whether the debug builds of MonoTouch will enforce that calls done to UIKit are only issued from the UI thread. - /// - /// - /// On debug builds, MonoTouch will enforce that calls made to - /// UIKit APIs are only done from the UIKit thread. This is - /// useful to spot code that could inadvertently use UIKit from - /// a non-UI thread which can corrupt the UIKit state and could - /// lead to very hard to debug problems. - /// - /// - /// But sometimes it might be useful to disable this check, - /// either because you can ensure that UIKit is not in use at - /// this point or because MonoTouch might be enforcing the - /// checks in APIs that might have later been relaxed or made - /// thread safe by iOS. - /// - /// - /// - public static bool CheckForIllegalCrossThreadCalls = true; + /// + public static bool CheckForIllegalCrossThreadCalls; /// If , the system will try to diagnose potential mistakes where events and delegate-object overrides are in conflict. public static bool CheckForEventAndDelegateMismatches = true; @@ -70,6 +53,12 @@ static int UIApplicationMain (int argc, /* char[]* */ string []? argv, /* NSStri // NOTE: must be called from the main thread, e.g. for extensions internal static void InitializeApplication () { + // The linker replaces the 'Runtime.CheckForIllegalCrossThreadCalls' getter with a constant value, so when the UI + // thread checks are disabled the assignment below (and the 'CheckForIllegalCrossThreadCalls' field + // itself, unless something else references it) is trimmed away. + if (Runtime.CheckForIllegalCrossThreadCalls) + CheckForIllegalCrossThreadCalls = true; + SynchronizationContext.SetSynchronizationContext (new UIKitSynchronizationContext ()); } diff --git a/src/VideoSubscriberAccount/VSAccountProviderAuthenticationScheme.cs b/src/VideoSubscriberAccount/VSAccountProviderAuthenticationScheme.cs index 26ee7306d99b..34e07a9ddfb1 100644 --- a/src/VideoSubscriberAccount/VSAccountProviderAuthenticationScheme.cs +++ b/src/VideoSubscriberAccount/VSAccountProviderAuthenticationScheme.cs @@ -5,14 +5,15 @@ namespace VideoSubscriberAccount { + /// Provides conversions between authentication scheme values and their native constants. public static partial class VSAccountProviderAuthenticationSchemeExtensions { // these are less common pattern so it's not automatically generated - /// The instance on which this method operates. - /// To be added. - /// To be added. - /// To be added. + /// Gets the native constants for the specified authentication schemes. + /// The authentication schemes to convert. + /// The native constant for each authentication scheme. An element is if the corresponding authentication scheme has no associated native constant on the current platform. + /// is . public static NSString? [] GetConstants (this VSAccountProviderAuthenticationScheme [] self) { if (self is null) @@ -24,10 +25,11 @@ public static partial class VSAccountProviderAuthenticationSchemeExtensions { return array; } - /// To be added. - /// To be added. - /// To be added. - /// To be added. + /// Gets the authentication schemes for the specified native constants. + /// The native constants to convert. + /// The authentication scheme for each native constant. + /// is . + /// An element in has no associated authentication scheme on the current platform. public static VSAccountProviderAuthenticationScheme [] GetValues (NSString [] constants) { if (constants is null) diff --git a/src/VideoToolbox/VTDefs.cs b/src/VideoToolbox/VTDefs.cs index f2dc82494ef1..c073028ed0a8 100644 --- a/src/VideoToolbox/VTDefs.cs +++ b/src/VideoToolbox/VTDefs.cs @@ -140,10 +140,10 @@ public enum VTEncodeInfoFlags : uint { } // uint32_t -> VTCompressionSession.h - /// Flags to control encoder in multi pass compression sessions + /// Specifies options for controlling an encoder in multipass compression sessions. [Flags] public enum VTCompressionSessionOptionFlags : uint { - /// To be added. + /// Begins the final pass of a multipass compression session. BeginFinalPass = 1 << 0, } diff --git a/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj index 28395182c78c..96964b97bdea 100644 --- a/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj +++ b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj @@ -14,7 +14,7 @@ - + diff --git a/system-dependencies.sh b/system-dependencies.sh index 0857e30c7997..a0d3921f49c8 100755 --- a/system-dependencies.sh +++ b/system-dependencies.sh @@ -368,6 +368,87 @@ function delete_all_simulator_runtimes () rm -rf "$TMPFILE" } +# Checks whether a simulator runtime for the given platform is installed and +# available (this is the same kind of check as in check_old_simulators). +# $1: the platform (iOS, tvOS, ...) +# $2: (optional) the version to look for. A runtime matches if its version is +# equal to this value or is a patch release of it (e.g. a "$2" of "26.5" +# matches both "26.5" and "26.5.1"), because simctl reports a patch version +# for the most recent runtimes. If empty, any version of the platform +# qualifies. +# Returns 0 if a matching, available runtime is installed, non-zero otherwise. +function is_simulator_runtime_installed () +{ + local platform="$1" + local version="$2" + local tmpfile + tmpfile=$(mktemp) + + xcrun simctl list runtimes --json --json-output "$tmpfile" >/dev/null 2>&1 + + local selector=".platform == \"$platform\" and .isAvailable == true and .isInternal == false" + if [[ -n "$version" ]]; then + selector="$selector and (.version == \"$version\" or (.version | startswith(\"$version.\")))" + fi + + local count + count=$(jq "[ .runtimes[] | select($selector) ] | length" < "$tmpfile") + rm -f "$tmpfile" + + [[ -n "$count" && "$count" -gt 0 ]] +} + +# Downloads a simulator platform using 'xcodebuild -downloadPlatform', retrying a +# few times in case of transient network failures. +# +# When the requested simulator runtime isn't available through the normal +# mechanism, xcodebuild falls back to downloading it from Apple's downloadable +# simulator index, and that transport occasionally stalls until curl fails (e.g. +# 'curl: (56) Recv failure: Operation timed out'). In that fallback case +# xcodebuild frequently still exits 0 while only printing the failure to stdout, +# so instead of trusting xcodebuild's exit code (or its output) we check the +# desired result directly: is the simulator runtime actually installed afterwards? +# If not, we retry the download. +# +# $1: the platform to download (iOS, tvOS, ...) +# $2: the expected runtime version, used *only* to verify the install afterwards +# (see is_simulator_runtime_installed for how it's matched). If empty, the +# download is accepted as long as any runtime for the platform is installed. +# $3...: the arguments to pass to 'xcodebuild -downloadPlatform' after the +# platform (e.g. '-buildVersion 16.0' or '-architectureVariant universal'). +function xcodebuild_download_platform () +{ + local platform="$1" + local version="$2" + shift 2 + + local XCODE_DEVELOPER_ROOT + XCODE_DEVELOPER_ROOT=$(get_xcode_developer_root) + + local attempts=5 + local attempt=1 + while true; do + log "Executing (attempt $attempt of $attempts) '$XCODE_DEVELOPER_ROOT/usr/bin/xcodebuild -downloadPlatform $platform $*'" + # We intentionally ignore xcodebuild's exit code here (see the comment + # above) and check whether the runtime got installed instead. + set +e + "$XCODE_DEVELOPER_ROOT/usr/bin/xcodebuild" -downloadPlatform "$platform" "$@" 2>&1 | sed 's/^/ /' + set -e + + if is_simulator_runtime_installed "$platform" "$version"; then + return 0 + fi + + if [[ $attempt -ge $attempts ]]; then + warn "The $platform ${version:+$version }simulator runtime was still not installed after $attempts download attempts." + return 1 + fi + warn "The $platform ${version:+$version }simulator runtime was not installed (attempt $attempt of $attempts); retrying in 15 seconds..." + sleep 15 + attempt=$((attempt + 1)) + done +} + function xcodebuild_download_selected_platforms () { local XCODE_DEVELOPER_ROOT @@ -394,6 +475,11 @@ function xcodebuild_download_selected_platforms () TVOS_BUILD_VERSION=" -architectureVariant arm64" fi + # The expected simulator runtime versions for the current Xcode, so we can + # verify the downloads below actually installed the runtimes we need. + IOS_NUGET_OS_VERSION=$(grep ^IOS_NUGET_OS_VERSION= Make.versions | sed 's/.*=//') + TVOS_NUGET_OS_VERSION=$(grep ^TVOS_NUGET_OS_VERSION= Make.versions | sed 's/.*=//') + local TMPFILE TMPFILE=$(mktemp) log "Checking if there are any simulator runtimes that aren't ready..." @@ -412,13 +498,16 @@ function xcodebuild_download_selected_platforms () log " none found." fi - log "Executing '$XCODE_DEVELOPER_ROOT/usr/bin/xcodebuild -downloadPlatform iOS$IOS_BUILD_VERSION' $1" - "$XCODE_DEVELOPER_ROOT/usr/bin/xcodebuild" -downloadPlatform iOS $IOS_BUILD_VERSION 2>&1 | sed 's/^/ /' + local RC=0 + if ! xcodebuild_download_platform iOS "$IOS_NUGET_OS_VERSION" $IOS_BUILD_VERSION; then + RC=1 + fi - log "Executing '$XCODE_DEVELOPER_ROOT/usr/bin/xcodebuild -downloadPlatform tvOS$TVOS_BUILD_VERSION' $1" - "$XCODE_DEVELOPER_ROOT/usr/bin/xcodebuild" -downloadPlatform tvOS $TVOS_BUILD_VERSION 2>&1 | sed 's/^/ /' + if ! xcodebuild_download_platform tvOS "$TVOS_NUGET_OS_VERSION" $TVOS_BUILD_VERSION; then + RC=1 + fi - return 0 + return $RC } function download_xcode_platforms () diff --git a/tests/assembly-preparer/BaseClass.cs b/tests/assembly-preparer/BaseClass.cs index 52e3a390841f..db4436192584 100644 --- a/tests/assembly-preparer/BaseClass.cs +++ b/tests/assembly-preparer/BaseClass.cs @@ -136,9 +136,9 @@ public void AssertPrepareHotReloadTrimmableStatic (ApplePlatform platform, bool } // returns true if the test assembly was modified - public bool AssertPrepareCode (ApplePlatform platform, bool isCoreCLR, Action? configure, string code, out string outputPath, bool hotReloadCompatibleBuild = false, string testAssemblyTrimMode = "link", string? inlineDlfcnMethods = null, string? extraConfig = null) + public bool AssertPrepareCode (ApplePlatform platform, bool isCoreCLR, Action? configure, string code, out string outputPath, bool hotReloadCompatibleBuild = false, string testAssemblyTrimMode = "link", string? inlineDlfcnMethods = null, string? extraConfig = null, string extraCsproj = "") { - using var preparer = CreatePreparer (platform, isCoreCLR, configure, code, out var testInfo, hotReloadCompatibleBuild: hotReloadCompatibleBuild, testAssemblyTrimMode: testAssemblyTrimMode, inlineDlfcnMethods: inlineDlfcnMethods, extraConfig: extraConfig ?? ""); + using var preparer = CreatePreparer (platform, isCoreCLR, configure, code, out var testInfo, hotReloadCompatibleBuild: hotReloadCompatibleBuild, testAssemblyTrimMode: testAssemblyTrimMode, inlineDlfcnMethods: inlineDlfcnMethods, extraConfig: extraConfig ?? "", extraCsproj: extraCsproj); AssertPrepare (preparer); outputPath = testInfo.OutputPath; diff --git a/tests/assembly-preparer/OptimizeGeneratedCodeHandlerTests.cs b/tests/assembly-preparer/OptimizeGeneratedCodeHandlerTests.cs index 5a5ee83d47e4..32855a9746d5 100644 --- a/tests/assembly-preparer/OptimizeGeneratedCodeHandlerTests.cs +++ b/tests/assembly-preparer/OptimizeGeneratedCodeHandlerTests.cs @@ -7,94 +7,6 @@ namespace AssemblyPreparerTests; public class OptimizeGeneratedCodeHandlerTests : BaseClass { - [Test] - [TestCase (ApplePlatform.MacCatalyst, false)] - [TestCase (ApplePlatform.iOS, false)] - [TestCase (ApplePlatform.TVOS, false)] - [TestCase (ApplePlatform.MacOSX, true)] - public void RemoveEnsureUIThread (ApplePlatform platform, bool isCoreCLR) - { - var ensureUIThreadCall = platform == ApplePlatform.MacOSX - ? "AppKit.NSApplication.EnsureUIThread ();" - : "UIKit.UIApplication.EnsureUIThread ();"; - - var usingDirective = platform == ApplePlatform.MacOSX - ? "using AppKit;" - : "using UIKit;"; - - var code = $@" - using System; - using Foundation; - using ObjCRuntime; - {usingDirective} - - class MyClass : NSObject {{ - [BindingImpl (BindingImplOptions.Optimizable)] - [Export (""myMethod"")] - public void MyMethod () {{ - {ensureUIThreadCall} - }} - }}"; - - AssertPrepareCode (platform, isCoreCLR, preparer => { - preparer.Registrar = RegistrarMode.Dynamic; - preparer.Optimizations.RemoveUIThreadChecks = true; - }, code, out var outputPath); - - using var assemblyDefinition = AssemblyDefinition.ReadAssembly (outputPath); - var type = assemblyDefinition.MainModule.Types.Single (v => v.Name == "MyClass"); - var method = type.Methods.Single (v => v.Name == "MyMethod"); - - var hasEnsureUIThread = method.Body.Instructions.Any (i => - i.OpCode.Code == Code.Call && - (i.Operand as MethodReference)?.Name == "EnsureUIThread"); - Assert.That (hasEnsureUIThread, Is.False, "EnsureUIThread call should be removed"); - } - - [Test] - [TestCase (ApplePlatform.MacCatalyst, false)] - [TestCase (ApplePlatform.iOS, false)] - [TestCase (ApplePlatform.TVOS, false)] - [TestCase (ApplePlatform.MacOSX, true)] - public void KeepEnsureUIThreadWhenOptimizationDisabled (ApplePlatform platform, bool isCoreCLR) - { - var ensureUIThreadCall = platform == ApplePlatform.MacOSX - ? "AppKit.NSApplication.EnsureUIThread ();" - : "UIKit.UIApplication.EnsureUIThread ();"; - - var usingDirective = platform == ApplePlatform.MacOSX - ? "using AppKit;" - : "using UIKit;"; - - var code = $@" - using System; - using Foundation; - using ObjCRuntime; - {usingDirective} - - class MyClass : NSObject {{ - [BindingImpl (BindingImplOptions.Optimizable)] - [Export (""myMethod"")] - public void MyMethod () {{ - {ensureUIThreadCall} - }} - }}"; - - AssertPrepareCode (platform, isCoreCLR, preparer => { - preparer.Registrar = RegistrarMode.Dynamic; - preparer.Optimizations.RemoveUIThreadChecks = false; - }, code, out var outputPath); - - using var assemblyDefinition = AssemblyDefinition.ReadAssembly (outputPath); - var type = assemblyDefinition.MainModule.Types.Single (v => v.Name == "MyClass"); - var method = type.Methods.Single (v => v.Name == "MyMethod"); - - var hasEnsureUIThread = method.Body.Instructions.Any (i => - i.OpCode.Code == Code.Call && - (i.Operand as MethodReference)?.Name == "EnsureUIThread"); - Assert.That (hasEnsureUIThread, Is.True, "EnsureUIThread call should be preserved when optimization is disabled"); - } - [Test] [TestCase (ApplePlatform.MacCatalyst, false)] [TestCase (ApplePlatform.iOS, false)] @@ -175,40 +87,37 @@ class MyClass : NSObject, IMyProtocol { [TestCase (ApplePlatform.MacOSX, true)] public void NoOptimizationWithoutBindingAttributes (ApplePlatform platform, bool isCoreCLR) { - var ensureUIThreadCall = platform == ApplePlatform.MacOSX - ? "AppKit.NSApplication.EnsureUIThread ();" - : "UIKit.UIApplication.EnsureUIThread ();"; - - var usingDirective = platform == ApplePlatform.MacOSX - ? "using AppKit;" - : "using UIKit;"; - - var code = $@" + // The method deliberately has no [BindingImpl (BindingImplOptions.Optimizable)] attribute, so + // the optimizer must leave it untouched: the IsDirectBinding condition must not be inlined + // and the dead 'return 2' must not be eliminated. + var code = @" using System; using Foundation; using ObjCRuntime; - {usingDirective} - class MyClass : NSObject {{ + class MyClass : NSObject { [Export (""myMethod"")] - public void MyMethod () {{ - {ensureUIThreadCall} - }} - }}"; + public int MyMethod () { + if (!IsDirectBinding) { + return 1; + } + return 2; + } + }"; AssertPrepareCode (platform, isCoreCLR, preparer => { preparer.Registrar = RegistrarMode.Dynamic; - preparer.Optimizations.RemoveUIThreadChecks = true; - }, code, out var outputPath); + preparer.Optimizations.DeadCodeElimination = true; + preparer.Optimizations.InlineIsDirectBinding = true; + }, code, out var outputPath, extraCsproj: "true"); using var assemblyDefinition = AssemblyDefinition.ReadAssembly (outputPath); var type = assemblyDefinition.MainModule.Types.Single (v => v.Name == "MyClass"); var method = type.Methods.Single (v => v.Name == "MyMethod"); - var hasEnsureUIThread = method.Body.Instructions.Any (i => - i.OpCode.Code == Code.Call && - (i.Operand as MethodReference)?.Name == "EnsureUIThread"); - Assert.That (hasEnsureUIThread, Is.True, "EnsureUIThread call should be preserved without [BindingImpl(Optimizable)]"); + var hasDeadCode = method.Body.Instructions.Any (i => + i.OpCode.Code == Code.Ldc_I4_2); + Assert.That (hasDeadCode, Is.True, "Dead code (return 2) should be preserved without [BindingImpl(Optimizable)]"); } [Test] @@ -218,6 +127,8 @@ public void MyMethod () {{ [TestCase (ApplePlatform.MacOSX, true)] public void DeadCodeElimination (ApplePlatform platform, bool isCoreCLR) { + // MyClass is a user type, so IsDirectBinding is inlined to a constant (false), after which the + // unreachable 'return 2' branch is eliminated (the method is optimizable via [BindingImpl]). var code = @" using System; using Foundation; @@ -227,7 +138,7 @@ class MyClass : NSObject { [BindingImpl (BindingImplOptions.Optimizable)] [Export (""myMethod"")] public int MyMethod () { - if (true) { + if (!IsDirectBinding) { return 1; } return 2; @@ -237,7 +148,8 @@ public int MyMethod () { AssertPrepareCode (platform, isCoreCLR, preparer => { preparer.Registrar = RegistrarMode.Dynamic; preparer.Optimizations.DeadCodeElimination = true; - }, code, out var outputPath); + preparer.Optimizations.InlineIsDirectBinding = true; + }, code, out var outputPath, extraCsproj: "true"); using var assemblyDefinition = AssemblyDefinition.ReadAssembly (outputPath); var type = assemblyDefinition.MainModule.Types.Single (v => v.Name == "MyClass"); diff --git a/tests/assembly-preparer/PreserveBlockCodeHandlerTests.cs b/tests/assembly-preparer/PreserveBlockCodeHandlerTests.cs index ad39cd811c5c..f775a21fc656 100644 --- a/tests/assembly-preparer/PreserveBlockCodeHandlerTests.cs +++ b/tests/assembly-preparer/PreserveBlockCodeHandlerTests.cs @@ -45,8 +45,9 @@ static internal void Invoke (IntPtr block, int magic_number) Assert.That ((string) attribs [0].ConstructorArguments [1].Value, Is.EqualTo ("ObjCRuntime.Trampolines.SDInnerBlock"), "First attribute's second argument"); Assert.That ((string) attribs [0].ConstructorArguments [2].Value, Is.EqualTo ("Test"), "First attribute's third argument"); - // Invoke method: DDA(string memberSignature) - same declaring type, so simpler constructor + // Invoke method: DDA(string memberSignature) - same declaring type, so simpler constructor. + // The signature doesn't include the parameter list, because there's only one method named 'Invoke'. Assert.That (attribs [1].ConstructorArguments.Count, Is.EqualTo (1), "Second attribute's argument count"); - Assert.That ((string) attribs [1].ConstructorArguments [0].Value, Is.EqualTo ("Invoke(System.IntPtr,System.Int32)"), "Second attribute's first argument"); + Assert.That ((string) attribs [1].ConstructorArguments [0].Value, Is.EqualTo ("Invoke"), "Second attribute's first argument"); } } diff --git a/tests/assembly-preparer/PreserveSmartEnumConversionsTest.cs b/tests/assembly-preparer/PreserveSmartEnumConversionsTest.cs index a380f3cb30e4..8fe86714feb7 100644 --- a/tests/assembly-preparer/PreserveSmartEnumConversionsTest.cs +++ b/tests/assembly-preparer/PreserveSmartEnumConversionsTest.cs @@ -48,6 +48,11 @@ public void Method3 ([BindAs (typeof (CAToneMapMode), OriginalType = typeof (NSS var cctor = type.GetStaticConstructor (); Assert.That (cctor, Is.Null, "No static constructor should be needed."); + AssertHasDynamicDependencies (platform, type, "get_RWProperty", "set_RWProperty", "get_ROProperty", "set_WOProperty", "Method1", "Method2", "Method3", "Method4"); + } + + static void AssertHasDynamicDependencies (ApplePlatform platform, TypeDefinition type, params string [] methodNames) + { void AssertHasDynamicDependency (ICustomAttributeProvider provider, string memberSignature, string typeName, string assemblyName) { var ddaAttributes = provider.CustomAttributes.Where (v => v.AttributeType.FullName == "System.Diagnostics.CodeAnalysis.DynamicDependencyAttribute").ToArray (); @@ -101,21 +106,16 @@ void AssertHasDynamicDependency (ICustomAttributeProvider provider, string membe Assert.Fail (msg); } - void AssertHasDynamicDependencies (ICustomAttributeProvider provider) + void AssertMethodHasDynamicDependencies (ICustomAttributeProvider provider) { - AssertHasDynamicDependency (provider, "GetConstant(CoreAnimation.CAToneMapMode)", "CoreAnimation.CAToneMapModeExtensions", $"Microsoft.{platform.AsString ()}"); + // 'GetConstant' has no parameter list, because it's the only method with that name (unlike 'GetValue'). + AssertHasDynamicDependency (provider, "GetConstant", "CoreAnimation.CAToneMapModeExtensions", $"Microsoft.{platform.AsString ()}"); AssertHasDynamicDependency (provider, "GetValue(Foundation.NSString)", "CoreAnimation.CAToneMapModeExtensions", $"Microsoft.{platform.AsString ()}"); } Assert.Multiple (() => { - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "get_RWProperty")); - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "set_RWProperty")); - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "get_ROProperty")); - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "set_WOProperty")); - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "Method1")); - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "Method2")); - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "Method3")); - AssertHasDynamicDependencies (type.Methods.Single (v => v.Name == "Method4")); + foreach (var methodName in methodNames) + AssertMethodHasDynamicDependencies (type.Methods.Single (v => v.Name == methodName)); }); } @@ -126,9 +126,9 @@ void AssertHasDynamicDependencies (ICustomAttributeProvider provider) [TestCase (ApplePlatform.MacOSX, true)] public void HotReloadCompatibleBuildTest (ApplePlatform platform, bool isCoreCLR) { - // When $(HotReloadCompatibleBuild) is enabled, the step must not modify the referencing - // (possibly user/reloadable) assembly - otherwise Hot Reload breaks. Instead it must emit an - // ILLink root-descriptor XML that preserves the framework-side conversion methods. + // When $(HotReloadCompatibleBuild) is enabled and the referencing assembly isn't trimmed, the step + // must not modify that (possibly user/reloadable) assembly - otherwise Hot Reload breaks. Instead it + // must emit an ILLink root-descriptor XML that preserves the framework-side conversion methods. var code = @" using System; using CoreAnimation; @@ -146,9 +146,9 @@ public void Method2 ([BindAs (typeof (CAToneMapMode), OriginalType = typeof (NSS }"; var cacheDirectory = Xamarin.Cache.CreateTemporaryDirectory (); - var extraConfig = $"HotReloadCompatibleBuild=true\n\t\tCacheDirectory={cacheDirectory}"; + var extraConfig = $"CacheDirectory={cacheDirectory}"; - AssertPrepare (platform, isCoreCLR, code, out var assemblyDefinition, extraConfig); + AssertPrepare (platform, isCoreCLR, RegistrarMode.Dynamic, code, out var assemblyDefinition, hotReloadCompatibleBuild: true, testAssemblyTrimMode: "copy", extraConfig: extraConfig); var type = assemblyDefinition.MainModule.Types.Single (v => v.Name == "MyClass"); @@ -179,4 +179,52 @@ public void Method2 ([BindAs (typeof (CAToneMapMode), OriginalType = typeof (NSS Assert.That (signatures, Does.Contain ("Foundation.NSString GetConstant(CoreAnimation.CAToneMapMode)"), "GetConstant must be preserved."); Assert.That (signatures, Does.Contain ("CoreAnimation.CAToneMapMode GetValue(Foundation.NSString)"), "GetValue must be preserved."); } + + [Test] + [TestCase (ApplePlatform.MacCatalyst, false)] + [TestCase (ApplePlatform.iOS, false)] + [TestCase (ApplePlatform.TVOS, false)] + [TestCase (ApplePlatform.MacOSX, true)] + public void HotReloadCompatibleBuildTrimmedAssemblyTest (ApplePlatform platform, bool isCoreCLR) + { + // Assemblies that are trimmed can't be hot reloaded, so even when $(HotReloadCompatibleBuild) is + // enabled we must inject [DynamicDependency] attributes into them (instead of preserving the + // conversion methods unconditionally using the root-descriptor XML). + var code = @" + using System; + using CoreAnimation; + using Foundation; + using ObjCRuntime; + + class MyClass : NSObject { + [BindAs (typeof (CAToneMapMode), OriginalType = typeof (NSString))] + public CAToneMapMode RWProperty { get; set; } + + [return: BindAs (typeof (CAToneMapMode), OriginalType = typeof (NSString))] + public CAToneMapMode Method1 () { return default; } + + public void Method2 ([BindAs (typeof (CAToneMapMode), OriginalType = typeof (NSString))] CAToneMapMode p1) {} + }"; + + var cacheDirectory = Xamarin.Cache.CreateTemporaryDirectory (); + var extraConfig = $"CacheDirectory={cacheDirectory}"; + + AssertPrepare (platform, isCoreCLR, RegistrarMode.Dynamic, code, out var assemblyDefinition, hotReloadCompatibleBuild: true, testAssemblyTrimMode: "link", extraConfig: extraConfig); + + var type = assemblyDefinition.MainModule.Types.Single (v => v.Name == "MyClass"); + var cctor = type.GetStaticConstructor (); + Assert.That (cctor, Is.Null, "No static constructor should be needed."); + + AssertHasDynamicDependencies (platform, type, "get_RWProperty", "set_RWProperty", "Method1", "Method2"); + + // The root-descriptor XML must not mention the smart enum from the trimmed assembly. + var xmlPath = Path.Combine (cacheDirectory, "preserve-smart-enum-conversions.xml"); + if (File.Exists (xmlPath)) { + var document = XDocument.Load (xmlPath); + var extensionType = document + .Descendants ("type") + .SingleOrDefault (v => (string?) v.Attribute ("fullname") == "CoreAnimation.CAToneMapModeExtensions"); + Assert.That (extensionType, Is.Null, "The extension type must not be present in the root-descriptor XML."); + } + } } diff --git a/tests/assembly-preparer/RelocateRegistrarTrampolinesTests.cs b/tests/assembly-preparer/RelocateRegistrarTrampolinesTests.cs index 1b71efbf71b7..8254a1e17163 100644 --- a/tests/assembly-preparer/RelocateRegistrarTrampolinesTests.cs +++ b/tests/assembly-preparer/RelocateRegistrarTrampolinesTests.cs @@ -75,6 +75,119 @@ public string Name { Assert.That (ignoresAccessChecksTo, Does.Contain ("Test"), "The companion should have [IgnoresAccessChecksTo(\"Test\")]"); } + // When HotReloadCompatibleBuild is enabled with the TrimmableStatic registrar, the registrar + // trampolines for methods declared in a *generic* NSObject subclass must also be relocated into + // the companion assembly, without modifying the user assembly. Historically these were handled + // by adding a proxy interface (and its implementation) onto the user type, which modified the + // user assembly; instead they must now be dispatched via a generic helper + reflection emitted + // entirely into the companion. + [Test] + [TestCase (ApplePlatform.iOS, false)] + [TestCase (ApplePlatform.MacCatalyst, false)] + [TestCase (ApplePlatform.MacOSX, true)] + public void GenericTrampolinesAreRelocated (ApplePlatform platform, bool isCoreCLR) + { + var code = @" + using System; + using Foundation; + using ObjCRuntime; + + public class MyGeneric : NSObject where T : NSObject { + [Export (""doSomething:"")] + public void DoSomething (T value) + { + } + + [Export (""roundtrip:"")] + public T Roundtrip (T value) + { + return value; + } + + [Export (""computeValue:result:"")] + public void ComputeValue (int value, out T result) + { + result = null; + } + } + "; + + AssertPrepareHotReloadTrimmableStatic (platform, isCoreCLR, code, out var userAssemblyWasSaved, out var userAssembly, out var companionAssembly); + + // The whole point of relocating the trampolines is to keep the user assembly + // byte-unmodified, so the assembly-preparer must not re-save it. + Assert.That (userAssemblyWasSaved, Is.False, "The user assembly should not have been modified/re-saved"); + + // The user assembly must not contain any registrar callback trampolines. + var userCallbackTypes = AllTypes (userAssembly).Where (v => v.Name == "__Registrar_Callbacks__").ToList (); + Assert.That (userCallbackTypes, Is.Empty, "The user assembly should not contain any __Registrar_Callbacks__ type"); + + // The user assembly must not contain any generated proxy interface type. + var proxyInterfaceTypes = AllTypes (userAssembly).Where (v => v.Name.StartsWith ("__IRegistrarGenericTypeProxy__", StringComparison.Ordinal)).ToList (); + Assert.That (proxyInterfaceTypes, Is.Empty, "The user assembly should not contain any generated proxy interface type"); + + var myGeneric = AllTypes (userAssembly).Single (v => v.Name == "MyGeneric`1"); + + // The user type must not implement any generated proxy interface. + var proxyInterfaceImpls = myGeneric.Interfaces.Where (v => v.InterfaceType.Name.StartsWith ("__IRegistrarGenericTypeProxy__", StringComparison.Ordinal)).ToList (); + Assert.That (proxyInterfaceImpls, Is.Empty, "The user type should not implement any generated proxy interface"); + + // The user type must not have a generated proxy implementation method. + var proxyImplMethods = myGeneric.Methods.Where (v => v.Name.StartsWith ("__IRegistrarGenericTypeProxy__", StringComparison.Ordinal)).ToList (); + Assert.That (proxyImplMethods, Is.Empty, "The user type should not have a generated proxy implementation method"); + + // The user methods must not have [DynamicDependency] attributes pointing at the trampolines. + foreach (var method in myGeneric.Methods) { + var dda = method.CustomAttributes.Where (v => v.AttributeType.Name == "DynamicDependencyAttribute" && v.ConstructorArguments.Any (a => a.Value is string s && s.StartsWith ("callback_", StringComparison.Ordinal))).ToList (); + Assert.That (dda, Is.Empty, $"The user method {method.Name} should not have a [DynamicDependency] attribute pointing at a trampoline"); + } + + // The user type's static constructor must not have been given a [DynamicDependency] attribute + // (that's how the proxy interface used to be kept alive - it modified the user assembly). + var staticCtor = myGeneric.Methods.SingleOrDefault (v => v.IsConstructor && v.IsStatic); + if (staticCtor is not null) { + var dda = staticCtor.CustomAttributes.Where (v => v.AttributeType.Name == "DynamicDependencyAttribute").ToList (); + Assert.That (dda, Is.Empty, "The user type's static constructor should not have a [DynamicDependency] attribute"); + } + + // The companion assembly must contain a top-level __Registrar_Callbacks__ type. + var companionCallbackType = companionAssembly.MainModule.Types.SingleOrDefault (v => v.Name == "__Registrar_Callbacks__" && v.DeclaringType is null); + Assert.That (companionCallbackType, Is.Not.Null, "The companion assembly should contain a top-level __Registrar_Callbacks__ type"); + + // The companion must contain the UnmanagedCallersOnly trampolines... + var trampolines = companionCallbackType.Methods.Where (v => v.CustomAttributes.Any (a => a.AttributeType.Name == "UnmanagedCallersOnlyAttribute")).ToList (); + Assert.That (trampolines.Count, Is.GreaterThanOrEqualTo (1), "The companion should contain at least one [UnmanagedCallersOnly] trampoline"); + + // ...as well as the generic helper methods the trampolines dispatch to via reflection. + var genericHelpers = companionCallbackType.Methods.Where (v => v.HasGenericParameters).ToList (); + Assert.That (genericHelpers.Count, Is.GreaterThanOrEqualTo (1), "The companion should contain at least one generic dispatch helper method"); + + // The generic helper's first parameter is the instance (self), typed as the user generic type + // closed over the helper's own generic parameters. The remaining parameters are the native + // arguments ('sel', p0, ...), followed by the exception GCHandle. + var doSomethingHelper = genericHelpers.Single (v => v.Name.Contains ("DoSomething")); + Assert.That (doSomethingHelper.Parameters.Count, Is.GreaterThanOrEqualTo (1), "The generic helper should have at least an instance parameter"); + Assert.That (doSomethingHelper.Parameters [0].ParameterType.Name, Is.EqualTo ("MyGeneric`1"), "The generic helper's first parameter should be the instance"); + + // A generic helper for a method with an out/ref parameter represents that parameter as a + // plain IntPtr: a pointer can't round-trip through reflection's object[] (it isn't boxable + // and MethodInfo.Invoke can't marshal it), so the out/ref (native pointer) parameter is + // passed as an IntPtr and the write-back happens through that pointer inside the helper body. + var computeHelper = genericHelpers.Single (v => v.Name.Contains ("ComputeValue")); + var outParameter = computeHelper.Parameters [3]; + Assert.That (outParameter.ParameterType.FullName, Is.EqualTo ("System.IntPtr"), "The generic helper's out parameter should be typed IntPtr"); + // A normal by-value parameter is unaffected: it keeps its native value type. + var valueParameter = computeHelper.Parameters [2]; + Assert.That (valueParameter.ParameterType.FullName, Is.EqualTo ("System.Int32"), "The generic helper's by-value parameter should keep its native value type"); + + // The companion must be granted access to the user assembly. + var ignoresAccessChecksTo = companionAssembly.CustomAttributes + .Where (v => v.AttributeType.Name == "IgnoresAccessChecksToAttribute") + .Select (v => (string) v.ConstructorArguments [0].Value) + .ToList (); + Assert.That (ignoresAccessChecksTo, Does.Contain ("Test"), "The companion should have [IgnoresAccessChecksTo(\"Test\")]"); + } + static IEnumerable AllTypes (AssemblyDefinition assembly) { foreach (var type in assembly.MainModule.Types) { diff --git a/tests/bindings-test/ApiDefinition.cs b/tests/bindings-test/ApiDefinition.cs index e3b238543555..f718794bbc08 100644 --- a/tests/bindings-test/ApiDefinition.cs +++ b/tests/bindings-test/ApiDefinition.cs @@ -886,4 +886,38 @@ interface Hitchhiker { [Export ("buildHighway")] void BuildHighway (); } + + // Helper for the issue #25861 design work: its native 'init' calls a method that + // can be overridden in managed code, to verify the overridden managed method is + // invoked (on the correct instance) while 'init' is still executing. + [BaseType (typeof (NSObject))] + interface InitCallsVirtualMethod { + [Export ("virtualMethodCalledDuringInit:")] + void VirtualMethodCalledDuringInit (int value); + } + + // Helper for the issue #25861 design work: a directly-bound native class whose + // native 'init' synchronously surfaces 'self' to managed code via a C callback. + [BaseType (typeof (NSObject))] + interface InitSurfacesSelfToManaged { + } + + // Helpers for a deterministic reproduction of the alloc/init handle-reuse race in + // issue #25861 (and #9478): ReuseSlotClassA's 'init' frees its own instance and forces + // the next allocation to reuse that exact address, so a ReuseSlotClassB allocated from + // managed code during that 'init' deterministically lands on the address freed by the + // ReuseSlotClassA instance. + [BaseType (typeof (NSObject))] + interface ReuseSlotClassA { + } + + [BaseType (typeof (NSObject))] + interface ReuseSlotClassB { + } + + // Helper for issue #23679: a native class whose 'init' fails (releases self and + // returns nil), so constructing the managed wrapper throws. + [BaseType (typeof (NSObject))] + interface InitReturnsNilClass { + } } diff --git a/tests/cecil-tests/Documentation.KnownFailures.txt b/tests/cecil-tests/Documentation.KnownFailures.txt index 11996a7269f7..d95d836b7e0c 100644 --- a/tests/cecil-tests/Documentation.KnownFailures.txt +++ b/tests/cecil-tests/Documentation.KnownFailures.txt @@ -2891,7 +2891,6 @@ F:CoreSpotlight.CSUserInteraction.Focus F:CoreSpotlight.CSUserInteraction.Select F:CoreTelephony.CTCellularPlanCapability.AndVoice F:CoreTelephony.CTCellularPlanCapability.Only -F:CoreTelephony.CTCellularPlanProvisioningAddPlanResult.Cancel F:CoreText.CTFontManagerError.AssetNotFound F:CoreText.CTFontManagerError.CancelledByUser F:CoreText.CTFontManagerError.DuplicatedName @@ -5993,8 +5992,6 @@ F:PdfKit.PdfAccessPermissions.DocumentChanges F:PdfKit.PdfAccessPermissions.FormFieldEntry F:PdfKit.PdfAccessPermissions.HighQualityPrinting F:PdfKit.PdfAccessPermissions.LowQualityPrinting -F:PdfKit.PdfAreaOfInterest.AnyArea -F:PdfKit.PdfMarkupType.Redact F:PdfKit.PdfSelectionGranularity.Character F:PdfKit.PdfSelectionGranularity.Line F:PdfKit.PdfSelectionGranularity.Word @@ -54216,7 +54213,6 @@ T:AppKit.NSApplicationFile T:AppKit.NSApplicationFileCommand T:AppKit.NSApplicationHandlesKey T:AppKit.NSApplicationMenu -T:AppKit.NSApplicationOcclusionState T:AppKit.NSApplicationPredicate T:AppKit.NSApplicationPresentationOptions T:AppKit.NSApplicationPrint @@ -54398,9 +54394,7 @@ T:AppKit.NSFocusRingPlacement T:AppKit.NSFocusRingType T:AppKit.NSFont T:AppKit.NSFontAssetRequest -T:AppKit.NSFontAssetRequestOptions T:AppKit.NSFontCollection -T:AppKit.NSFontCollectionOptions T:AppKit.NSFontCollectionVisibility T:AppKit.NSFontDescriptor T:AppKit.NSFontDescriptorSystemDesign @@ -54542,7 +54536,6 @@ T:AppKit.NSPanel T:AppKit.NSPanGestureRecognizer T:AppKit.NSPasteboard T:AppKit.NSPasteboardAccessBehavior -T:AppKit.NSPasteboardContentsOptions T:AppKit.NSPasteboardDetectionPattern T:AppKit.NSPasteboardDetectMetadataCompletionHandler T:AppKit.NSPasteboardDetectMetadataHandler @@ -54557,7 +54550,6 @@ T:AppKit.NSPasteboardReadingOptions T:AppKit.NSPasteboardType T:AppKit.NSPasteboardTypeFindPanelSearchOptionKey T:AppKit.NSPasteboardTypeTextFinderOptionKey -T:AppKit.NSPasteboardWritingOptions T:AppKit.NSPathCell T:AppKit.NSPathComponentCell T:AppKit.NSPathControl @@ -54954,11 +54946,9 @@ T:AppKit.NSWindowDocumentDrag T:AppKit.NSWindowFrame T:AppKit.NSWindowFramePredicate T:AppKit.NSWindowLevel -T:AppKit.NSWindowListOptions T:AppKit.NSWindowMenu T:AppKit.NSWindowNSWindow T:AppKit.NSWindowNumberListOptions -T:AppKit.NSWindowOcclusionState T:AppKit.NSWindowOrderingMode T:AppKit.NSWindowResize T:AppKit.NSWindowSharingType @@ -55073,14 +55063,12 @@ T:AudioToolbox.AUVoiceIOOtherAudioDuckingLevel T:AudioUnit.AU3DMixerRenderingFlags T:AudioUnit.AudioAggregateDriftCompensation T:AudioUnit.AudioComponentValidationResult -T:AudioUnit.AudioObjectPropertyElement T:AudioUnit.AudioObjectPropertyScope T:AudioUnit.AudioObjectPropertySelector T:AudioUnit.AudioUnitBusType T:AudioUnit.AudioUnitEventType T:AudioUnit.AudioUnitParameterOptions T:AudioUnit.AudioUnitSubType -T:AudioUnit.AUEventSampleTime T:AudioUnit.AUImplementorStringFromValueCallback T:AudioUnit.AUInternalRenderBlock T:AudioUnit.AUMidiCIProfileChangedCallback @@ -55308,7 +55296,6 @@ T:AVFoundation.AVAudioRoutingArbiter T:AVFoundation.AVAudioRoutingArbitrationCategory T:AVFoundation.AVAudioSequencerInfoDictionary T:AVFoundation.AVAudioSequencerUserCallback -T:AVFoundation.AVAudioSessionActivationOptions T:AVFoundation.AVAudioSessionCapability T:AVFoundation.AVAudioSessionDeactivationOptions T:AVFoundation.AVAudioSessionDeactivationSource @@ -56602,7 +56589,6 @@ T:CoreTelephony.CTCellularPlanCapability T:CoreTelephony.CTCellularPlanProperties T:CoreTelephony.CTCellularPlanProvisioning T:CoreTelephony.CTCellularPlanProvisioningAddPlanCompletionHandler -T:CoreTelephony.CTCellularPlanProvisioningAddPlanResult T:CoreTelephony.CTCellularPlanProvisioningRequest T:CoreTelephony.CTCellularPlanProvisioningUpdateCellularPlanCompletionHandler T:CoreTelephony.CTCellularPlanStatus @@ -56890,7 +56876,6 @@ T:Foundation.NSInputStream T:Foundation.NSInvocation T:Foundation.NSIso8601DateFormatter T:Foundation.NSItemProvider -T:Foundation.NSItemProviderFileOptions T:Foundation.NSItemProviderRepresentationVisibility T:Foundation.NSItemProviderUTTypeLoadDelegate T:Foundation.NSJsonSerialization @@ -59459,7 +59444,6 @@ T:SceneKit.SCNCameraController T:SceneKit.SCNCameraProjectionDirection T:SceneKit.SCNColorMask T:SceneKit.SCNDistanceConstraint -T:SceneKit.SCNErrorCode T:SceneKit.SCNFillMode T:SceneKit.SCNGeometryTessellator T:SceneKit.SCNHitTestSearchMode diff --git a/tests/dotnet/EnsureUIThreadApp/Directory.Build.props b/tests/dotnet/EnsureUIThreadApp/Directory.Build.props new file mode 100644 index 000000000000..b0a9da2ac729 --- /dev/null +++ b/tests/dotnet/EnsureUIThreadApp/Directory.Build.props @@ -0,0 +1,3 @@ + + + diff --git a/tests/dotnet/EnsureUIThreadApp/EnsureUIThreadApp.cs b/tests/dotnet/EnsureUIThreadApp/EnsureUIThreadApp.cs new file mode 100644 index 000000000000..24b672e086c2 --- /dev/null +++ b/tests/dotnet/EnsureUIThreadApp/EnsureUIThreadApp.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; + +namespace EnsureUIThreadApp { + public class Program { + static int Main (string [] args) + { + // Reference [NS|UI]Application.EnsureUIThread so the linker keeps the method (this makes it + // possible to inspect the method body in the linked platform assembly). The call is guarded + // so that it never actually executes (which could otherwise throw when not on the UI thread) - + // the linker only needs to see the call instruction to keep the method reachable. + if (args.Length > 1_000_000) { +#if __MACOS__ + AppKit.NSApplication.EnsureUIThread (); +#else + UIKit.UIApplication.EnsureUIThread (); +#endif + } + + Console.WriteLine (Environment.GetEnvironmentVariable ("MAGIC_WORD")); + + return args.Length; + } + } +} diff --git a/tests/dotnet/EnsureUIThreadApp/MacCatalyst/EnsureUIThreadApp.csproj b/tests/dotnet/EnsureUIThreadApp/MacCatalyst/EnsureUIThreadApp.csproj new file mode 100644 index 000000000000..6b0e2c773180 --- /dev/null +++ b/tests/dotnet/EnsureUIThreadApp/MacCatalyst/EnsureUIThreadApp.csproj @@ -0,0 +1,7 @@ + + + + net$(BundledNETCoreAppTargetFrameworkVersion)-maccatalyst + + + diff --git a/tests/dotnet/EnsureUIThreadApp/iOS/EnsureUIThreadApp.csproj b/tests/dotnet/EnsureUIThreadApp/iOS/EnsureUIThreadApp.csproj new file mode 100644 index 000000000000..86d408734aa8 --- /dev/null +++ b/tests/dotnet/EnsureUIThreadApp/iOS/EnsureUIThreadApp.csproj @@ -0,0 +1,7 @@ + + + + net$(BundledNETCoreAppTargetFrameworkVersion)-ios + + + diff --git a/tests/dotnet/EnsureUIThreadApp/macOS/EnsureUIThreadApp.csproj b/tests/dotnet/EnsureUIThreadApp/macOS/EnsureUIThreadApp.csproj new file mode 100644 index 000000000000..a77287b9ba00 --- /dev/null +++ b/tests/dotnet/EnsureUIThreadApp/macOS/EnsureUIThreadApp.csproj @@ -0,0 +1,7 @@ + + + + net$(BundledNETCoreAppTargetFrameworkVersion)-macos + + + diff --git a/tests/dotnet/EnsureUIThreadApp/shared.csproj b/tests/dotnet/EnsureUIThreadApp/shared.csproj new file mode 100644 index 000000000000..601de3de580b --- /dev/null +++ b/tests/dotnet/EnsureUIThreadApp/shared.csproj @@ -0,0 +1,16 @@ + + + + Exe + + EnsureUIThreadApp + com.xamarin.ensureuithreadapp + 3.14 + + + + + + + + diff --git a/tests/dotnet/EnsureUIThreadApp/tvOS/EnsureUIThreadApp.csproj b/tests/dotnet/EnsureUIThreadApp/tvOS/EnsureUIThreadApp.csproj new file mode 100644 index 000000000000..bd487ddcd88d --- /dev/null +++ b/tests/dotnet/EnsureUIThreadApp/tvOS/EnsureUIThreadApp.csproj @@ -0,0 +1,7 @@ + + + + net$(BundledNETCoreAppTargetFrameworkVersion)-tvos + + + diff --git a/tests/dotnet/UnitTests/EnsureUIThreadChecksTest.cs b/tests/dotnet/UnitTests/EnsureUIThreadChecksTest.cs new file mode 100644 index 000000000000..dd03f306242b --- /dev/null +++ b/tests/dotnet/UnitTests/EnsureUIThreadChecksTest.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using Microsoft.Build.Framework; +using Microsoft.Build.Logging.StructuredLogger; + +using Mono.Cecil; +using Mono.Cecil.Cil; + +#nullable enable + +namespace Xamarin.Tests { + [TestFixture] + public class EnsureUIThreadChecksTest : TestBaseClass { + [Test] + [TestCase (ApplePlatform.iOS, "iossimulator-arm64", "true")] + [TestCase (ApplePlatform.iOS, "iossimulator-arm64", "false")] + [TestCase (ApplePlatform.MacOSX, "osx-arm64", "true")] + [TestCase (ApplePlatform.MacOSX, "osx-arm64", "false")] + public void UserSpecifiedValue (ApplePlatform platform, string runtimeIdentifiers, string ensureUIThreadChecks) + { + // When the user sets $(CheckForIllegalCrossThreadCalls), the value must be passed straight through to the + // 'ObjCRuntime.Runtime.CheckForIllegalCrossThreadCalls' trimmer feature switch (which controls whether ILLink + // stubs the [NS|UI]Application.EnsureUIThread method body). + var project = "EnsureUIThreadApp"; + Configuration.IgnoreIfIgnoredPlatform (platform); + Configuration.AssertRuntimeIdentifiersAvailable (platform, runtimeIdentifiers); + + var project_path = GetProjectPath (project, runtimeIdentifiers: runtimeIdentifiers, platform: platform, out var appPath); + Clean (project_path); + var properties = GetDefaultProperties (runtimeIdentifiers); + properties ["MtouchLink"] = "SdkOnly"; + properties ["LinkMode"] = "SdkOnly"; + properties ["CheckForIllegalCrossThreadCalls"] = ensureUIThreadChecks; + var rv = DotNet.AssertBuild (project_path, properties); + + var featureSwitch = GetRuntimeHostConfigurationOption (rv.BinLogPath, "ObjCRuntime.Runtime.CheckForIllegalCrossThreadCalls"); + Assert.That (featureSwitch, Is.Not.Null, "The CheckForIllegalCrossThreadCalls feature switch must be set."); + Assert.That (featureSwitch?.GetMetadata ("Value"), Is.EqualTo (ensureUIThreadChecks), "The feature switch value must match the user-specified value."); + + AssertEnsureUIThreadBody (platform, appPath, checksKept: ensureUIThreadChecks == "true"); + } + + [Test] + [TestCase (ApplePlatform.iOS, "iossimulator-arm64", "Debug", "true")] + [TestCase (ApplePlatform.iOS, "iossimulator-arm64", "Release", "false")] + [TestCase (ApplePlatform.MacOSX, "osx-arm64", "Debug", "true")] + [TestCase (ApplePlatform.MacOSX, "osx-arm64", "Release", "false")] + public void DefaultValue (ApplePlatform platform, string runtimeIdentifiers, string configuration, string expectedValue) + { + // By default the UI thread checks are kept in debug builds and removed in release builds. + var project = "EnsureUIThreadApp"; + Configuration.IgnoreIfIgnoredPlatform (platform); + Configuration.AssertRuntimeIdentifiersAvailable (platform, runtimeIdentifiers); + + var project_path = GetProjectPath (project, runtimeIdentifiers: runtimeIdentifiers, platform: platform, out var appPath, configuration: configuration); + Clean (project_path); + var properties = GetDefaultProperties (runtimeIdentifiers); + properties ["MtouchLink"] = "SdkOnly"; + properties ["LinkMode"] = "SdkOnly"; + properties ["Configuration"] = configuration; + + var rv = DotNet.AssertBuild (project_path, properties); + + var featureSwitch = GetRuntimeHostConfigurationOption (rv.BinLogPath, "ObjCRuntime.Runtime.CheckForIllegalCrossThreadCalls"); + Assert.That (featureSwitch, Is.Not.Null, "The CheckForIllegalCrossThreadCalls feature switch must be set."); + Assert.That (featureSwitch?.GetMetadata ("Value"), Is.EqualTo (expectedValue), "The feature switch value must match the expected default."); + + AssertEnsureUIThreadBody (platform, appPath, checksKept: expectedValue == "true"); + } + + // Inspects the linked platform assembly in the app bundle and verifies that the UI thread check is kept + // or removed. The public [NS|UI]Application.EnsureUIThread entry point delegates to the internal + // ObjCRuntime.Runtime.EnsureUIThread method, which performs the actual thread check (and throw). When the + // checks are removed, the entry point is stubbed to a no-op via ILLink substitutions, which makes + // Runtime.EnsureUIThread unreferenced (and thus trimmed away) together with the + // CheckForIllegalCrossThreadCalls field. + void AssertEnsureUIThreadBody (ApplePlatform platform, string appPath, bool checksKept) + { + var platformAssembly = Path.Combine (appPath, GetRelativeAssemblyDirectory (platform), Configuration.GetBaseLibraryName (platform)); + Assert.That (platformAssembly, Does.Exist, "The platform assembly must exist in the app bundle."); + + using var ad = AssemblyDefinition.ReadAssembly (platformAssembly, new ReaderParameters { ReadingMode = ReadingMode.Deferred }); + var typeName = platform == ApplePlatform.MacOSX ? "AppKit.NSApplication" : "UIKit.UIApplication"; + var type = ad.MainModule.Types.Single (v => v.FullName == typeName); + var runtimeType = ad.MainModule.Types.Single (v => v.FullName == "ObjCRuntime.Runtime"); + + var hasRuntimeCheck = runtimeType.Methods.Any (m => m.Name == "EnsureUIThread" && m.Parameters.Count == 0); + var checkField = type.Fields.SingleOrDefault (f => f.Name == "CheckForIllegalCrossThreadCalls"); + if (checksKept) { + var runtimeMethod = runtimeType.Methods.Single (m => m.Name == "EnsureUIThread" && m.Parameters.Count == 0); + var throwCount = runtimeMethod.Body.Instructions.Count (i => i.OpCode == OpCodes.Throw); + Assert.That (throwCount, Is.GreaterThan (0), "The ObjCRuntime.Runtime.EnsureUIThread body must still throw when the UI thread checks are kept."); + Assert.That (checkField, Is.Not.Null, $"The {typeName}.CheckForIllegalCrossThreadCalls field must be present when the UI thread checks are kept."); + } else { + Assert.That (hasRuntimeCheck, Is.False, "The ObjCRuntime.Runtime.EnsureUIThread method must be trimmed away when the UI thread checks are removed."); + Assert.That (checkField, Is.Null, $"The {typeName}.CheckForIllegalCrossThreadCalls field must be trimmed away when the UI thread checks are removed."); + } + } + + // Returns the last RuntimeHostConfigurationOption item with the given name (ItemSpec) added during the build. + static ITaskItem? GetRuntimeHostConfigurationOption (string binLogPath, string name) + { + ITaskItem? rv = null; + foreach (var args in BinLog.ReadBuildEvents (binLogPath)) { + if (args is not TaskParameterEventArgs tpea) + continue; + if (tpea.Kind != TaskParameterMessageKind.AddItem) + continue; + if (tpea.ItemType != "RuntimeHostConfigurationOption") + continue; + foreach (var item in tpea.Items) { + if (item is ITaskItem taskItem && taskItem.ItemSpec == name) + rv = taskItem; + } + } + return rv; + } + } +} diff --git a/tests/dotnet/UnitTests/Extensions.cs b/tests/dotnet/UnitTests/Extensions.cs index 1f9a5165cbe0..6d6b5859937b 100644 --- a/tests/dotnet/UnitTests/Extensions.cs +++ b/tests/dotnet/UnitTests/Extensions.cs @@ -131,13 +131,13 @@ public static bool IsFilteredWarning (BuildLogEvent evt, ApplePlatform platform, return true; if (filterXcodeLocation) { - if (v.Contains ("The environment variable 'MD_APPLE_SDK_ROOT' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use.")) + if (v.Contains ("The environment variable 'MD_APPLE_SDK_ROOT' is deprecated, and will be ignored. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode.")) return true; - if (v.Contains ("The environment variable 'MD_APPLE_SDK_ROOT' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use.")) + if (v.Contains ("The environment variable 'MD_APPLE_SDK_ROOT' is deprecated, and will be ignored in .NET 11+. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode.")) return true; - if (Regex.IsMatch (v, @"The settings file '/.*/Library/Preferences/maui/Settings\.plist' is deprecated, and will be ignored\. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use\.")) + if (Regex.IsMatch (v, @"The settings file '/.*/Library/Preferences/maui/Settings\.plist' is deprecated, and will be ignored\. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode\.")) return true; - if (Regex.IsMatch (v, @"The settings file '/.*/Library/Preferences/Xamarin/Settings\.plist' is deprecated, and will be ignored\. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use\.")) + if (Regex.IsMatch (v, @"The settings file '/.*/Library/Preferences/Xamarin/Settings\.plist' is deprecated, and will be ignored\. Use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to use an Xcode other than the system's current default Xcode\.")) return true; } diff --git a/tests/linker/link all/PreserveTest.cs b/tests/linker/link all/PreserveTest.cs index 48b05ae3dd49..483a0378f7b7 100644 --- a/tests/linker/link all/PreserveTest.cs +++ b/tests/linker/link all/PreserveTest.cs @@ -107,7 +107,7 @@ public void Runtime_Unconditional () // Initialize and a few other methods are unconditionally preserved var method = klass.GetMethod ("Initialize", BindingFlags.NonPublic | BindingFlags.Static); Assert.That (method, Is.Not.Null, "Initialize"); - method = klass.GetMethod ("RegisterNSObject", BindingFlags.NonPublic | BindingFlags.Static, null, new Type [] { typeof (NSObject), typeof (IntPtr) }, null); + method = klass.GetMethod ("RegisterNSObject", BindingFlags.NonPublic | BindingFlags.Static, null, new Type [] { typeof (NSObject), typeof (IntPtr), typeof (bool) }, null); Assert.That (method, Is.Not.Null, "RegisterNSObject"); } @@ -137,19 +137,9 @@ public void SmartEnumTest () Assert.That (smartExtensions.GetMethod ("GetConstant"), Is.Not.Null, "GetConstant"); Assert.That (smartExtensions.GetMethod ("GetValue"), Is.Not.Null, "GetValue"); -#if HOTRELOAD_COMPATIBLE_BUILD && PREPARE_ASSEMBLIES - // In a hot-reload-compatible build (the assembly-preparer runs with - // HotReloadCompatibleBuild=true, which is the default for Debug builds), - // smart enum conversions are preserved unconditionally via a root-descriptor - // XML instead of by modifying user assemblies. Root descriptors can't express - // conditional preservation, so unused smart enums are intentionally kept. - Assert.That (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypes"), Is.Not.Null, "AVMediaTypes"); - Assert.That (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypesExtensions"), Is.Not.Null, "AVMediaTypesExtensions"); -#else // Unused smart enums and their extensions should be linked away Assert.That (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypes"), Is.Null, "AVMediaTypes"); Assert.That (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypesExtensions"), Is.Null, "AVMediaTypesExtensions"); -#endif } [Test] diff --git a/tests/monotouch-test/ObjCRuntime/AllocInitRaceTest.cs b/tests/monotouch-test/ObjCRuntime/AllocInitRaceTest.cs new file mode 100644 index 000000000000..c455c679d1ea --- /dev/null +++ b/tests/monotouch-test/ObjCRuntime/AllocInitRaceTest.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; + +using ObjCRuntime; + +using Bindings.Test; + +using NUnit.Framework; + +namespace MonoTouchFixtures.ObjCRuntime { + [TestFixture] + [Preserve (AllMembers = true)] + public class AllocInitRaceTest { + // Deterministic reproduction for issue #25861 (and #9478). + // + // While ReuseSlotClassA is executing its native 'init', it frees the alloc'd + // instance and forces the next allocation to reuse that exact address, then calls + // back into managed code which allocates a ReuseSlotClassB that deterministically + // lands on that address. The managed runtime now maps the address to the + // ReuseSlotClassB. ReuseSlotClassA's 'init' then returns a different instance, so + // the ReuseSlotClassA wrapper rebinds its handle; a non-ownership-aware unregister + // would, at that point, remove the ReuseSlotClassB (which now occupies the old + // address) from the object_map. This makes the race deterministic, so we can assert + // the outcome directly instead of stress-testing. + [DllImport ("__Internal")] + unsafe static extern void x_set_reuse_alloc_callback (delegate* unmanaged callback); + + static ReuseSlotClassB reuseCreatedB; + static IntPtr reuseReusedAddress; + static IntPtr reuseOriginalAddress; + + [UnmanagedCallersOnly] + static void OnReuseAlloc (IntPtr originalPtr) + { + // Allocate a ReuseSlotClassB; it deterministically reuses 'originalPtr'. + reuseOriginalAddress = originalPtr; + var b = new ReuseSlotClassB (); + reuseCreatedB = b; + reuseReusedAddress = b.Handle; + } + + static void RunClobberScenario () + { + reuseCreatedB = null; + reuseReusedAddress = IntPtr.Zero; + reuseOriginalAddress = IntPtr.Zero; + unsafe { + x_set_reuse_alloc_callback (&OnReuseAlloc); + } + try { + GC.KeepAlive (new ReuseSlotClassA ()); + } finally { + unsafe { + x_set_reuse_alloc_callback (null); + } + } + } + + [Test] + public void ReusedAddressSurvivesAllocInitClobber () + { + RunClobberScenario (); + + Assert.IsNotNull (reuseCreatedB, "the reused-address object was created"); + Assert.AreEqual (reuseOriginalAddress, reuseReusedAddress, "the ReuseSlotClassB reused the freed address"); + + // The object_map entry for the reused address must still point at the very + // ReuseSlotClassB we created (it must not have been clobbered when + // ReuseSlotClassA rebound its handle). + var resolved = Runtime.GetNSObject (reuseReusedAddress); + Assert.AreSame (reuseCreatedB, resolved, "the reused address still resolves to the original object (issue #25861)"); + } + + [Test] + public void ReusedAddressClobberedWithLegacySwitch () + { + // With the legacy behavior (unconditional unregister on handle rebind), the + // same scenario removes the reused-address object from the object_map, so it + // no longer resolves to the original instance. This documents the bug and + // proves the scenario genuinely exercises the code path the fix changes. + var switchName = "ObjCRuntime.Runtime.RegisterObjectsBeforeInit"; + var hadSwitch = AppContext.TryGetSwitch (switchName, out var previous); + AppContext.SetSwitch (switchName, true); + try { + RunClobberScenario (); + + Assert.IsNotNull (reuseCreatedB, "the reused-address object was created"); + Assert.AreEqual (reuseOriginalAddress, reuseReusedAddress, "the ReuseSlotClassB reused the freed address"); + var resolved = Runtime.GetNSObject (reuseReusedAddress); + Assert.AreNotSame (reuseCreatedB, resolved, "with the legacy switch, the reused address was clobbered and resolves to a different (duplicate) wrapper"); + } finally { + if (hadSwitch) + AppContext.SetSwitch (switchName, previous); + else + AppContext.SetSwitch (switchName, false); + } + } + + [Test] + public void InitReturnsNilDoesNotCrashOnGC () + { + // Issue #23679: a failed 'init' (returns nil) that throws must not leave a + // dangling managed reference that crashes during a later garbage collection. + for (var i = 0; i < 100; i++) { + Assert.Catch (() => GC.KeepAlive (new InitReturnsNilClass ()), "failed init should throw"); + } + GC.Collect (); + GC.WaitForPendingFinalizers (); + GC.Collect (); + GC.WaitForPendingFinalizers (); + // Getting here without crashing is the assertion (issue #23679). + Assert.Pass (); + } + } +} diff --git a/tests/monotouch-test/ObjCRuntime/InitCallbackProbeTest.cs b/tests/monotouch-test/ObjCRuntime/InitCallbackProbeTest.cs new file mode 100644 index 000000000000..0231d746be86 --- /dev/null +++ b/tests/monotouch-test/ObjCRuntime/InitCallbackProbeTest.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Runtime.InteropServices; + +using Foundation; +using ObjCRuntime; + +using Bindings.Test; + +using NUnit.Framework; + +namespace MonoTouchFixtures.ObjCRuntime { + // Probe tests for the issue #25861 redesign. They capture the current (baseline) + // behavior of two scenarios that any redesigned object registration must preserve: + // + // 1. A user type whose native 'init' calls a method overridden in managed code: + // the overridden managed method must be invoked on the correct instance while + // 'init' is still executing. + // 2. A directly-bound (platform-like, no gchandle ivar) type whose native 'init' + // synchronously surfaces 'self' to managed code: managed code must resolve + // 'self' to the very wrapper being constructed (no duplicate wrapper). + [TestFixture] + [Preserve (AllMembers = true)] + public class InitCallbackProbeTest { + // --- Scenario 1: init calls an overridden managed method -------------------- + + class OverridingSubclass : InitCallsVirtualMethod { + public bool OverrideCalled; + public NSObject InstanceAtCall; + public int ValueReceived; + + public override void VirtualMethodCalledDuringInit (int value) + { + OverrideCalled = true; + InstanceAtCall = this; + ValueReceived = value; + } + } + + [Test] + public void InitCallsOverriddenManagedMethod () + { + var obj = new OverridingSubclass (); + + Assert.IsTrue (obj.OverrideCalled, "overridden managed method was called during init"); + Assert.AreSame (obj, obj.InstanceAtCall, "overridden method was called on the instance being constructed"); + Assert.AreEqual (0x1234, obj.ValueReceived, "the argument was marshalled correctly"); + } + + // --- Scenario 2: platform-like init surfaces self to managed ---------------- + + [DllImport ("__Internal")] + unsafe static extern void x_set_init_self_callback (delegate* unmanaged callback); + + static NSObject resolvedDuringInit; + + [UnmanagedCallersOnly] + static void OnInitSelf (IntPtr self) + { + resolvedDuringInit = Runtime.GetNSObject (self); + } + + [Test] + public unsafe void PlatformInitSurfacingSelfResolvesToSameWrapper () + { + resolvedDuringInit = null; + x_set_init_self_callback (&OnInitSelf); + try { + var obj = new InitSurfacesSelfToManaged (); + + Assert.IsNotNull (resolvedDuringInit, "self was resolved to a managed wrapper during init"); + Assert.AreSame (obj, resolvedDuringInit, "self resolved to the wrapper being constructed (no duplicate wrapper)"); + } finally { + x_set_init_self_callback (null); + resolvedDuringInit = null; + } + } + } +} diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/MergeRuntimeConfigFilesTaskTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/MergeRuntimeConfigFilesTaskTest.cs new file mode 100644 index 000000000000..ded7dc3c5584 --- /dev/null +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/MergeRuntimeConfigFilesTaskTest.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; + +using NUnit.Framework; + +#nullable enable + +namespace Xamarin.MacDev.Tasks { + + // Note: we can't use System.Text.Json types here to inspect the output, because the + // Xamarin.MacDev.Tasks assembly under test is ILMerged and also exposes System.Text.Json, + // which causes ambiguous type references. We assert on the raw JSON text instead. + [TestFixture] + public class MergeRuntimeConfigFilesTaskTest : TestBase { + + string RunMerge (string mainJson, string? devJson) + { + var tmp = Cache.CreateTemporaryDirectory (); + var mainFile = Path.Combine (tmp, "app.runtimeconfig.json"); + File.WriteAllText (mainFile, mainJson); + + string? devFile = null; + if (devJson is not null) { + devFile = Path.Combine (tmp, "app.runtimeconfig.dev.json"); + File.WriteAllText (devFile, devJson); + } + + var outputFile = Path.Combine (tmp, "obj", "runtimeconfig.merged.json"); + + var task = CreateTask (); + task.RuntimeConfigFile = mainFile; + task.RuntimeConfigDevFile = devFile; + task.OutputFile = outputFile; + + ExecuteTask (task); + + Assert.That (outputFile, Does.Exist, "output file created"); + return File.ReadAllText (outputFile); + } + + [Test] + public void MergesDevPropertiesOntoMain () + { + var mainJson = @"{ + ""runtimeOptions"": { + ""tfm"": ""net10.0"", + ""configProperties"": { + ""OnlyInMain"": true, + ""InBoth"": ""main-value"" + } + } +}"; + var devJson = @"{ + ""runtimeOptions"": { + ""configProperties"": { + ""OnlyInDev"": ""dev-only"", + ""InBoth"": ""dev-value"" + } + } +}"; + + var merged = RunMerge (mainJson, devJson); + + // (a) properties only in main are preserved + Assert.That (merged, Does.Contain ("\"OnlyInMain\": true"), "OnlyInMain preserved"); + // (b) properties only in dev are added + Assert.That (merged, Does.Contain ("\"OnlyInDev\": \"dev-only\""), "OnlyInDev added"); + // (c) properties in both are taken from dev (dev wins) + Assert.That (merged, Does.Contain ("\"InBoth\": \"dev-value\""), "dev wins for InBoth"); + Assert.That (merged, Does.Not.Contain ("main-value"), "main value for InBoth is gone"); + } + + [Test] + public void NoDevFile () + { + var mainJson = @"{ + ""runtimeOptions"": { + ""configProperties"": { + ""OnlyInMain"": true + } + } +}"; + + var merged = RunMerge (mainJson, null); + + Assert.That (merged, Does.Contain ("\"OnlyInMain\": true"), "OnlyInMain preserved"); + } + + [Test] + public void DevFileWithoutConfigProperties () + { + var mainJson = @"{ + ""runtimeOptions"": { + ""configProperties"": { + ""OnlyInMain"": true + } + } +}"; + var devJson = @"{ + ""runtimeOptions"": { + ""additionalProbingPaths"": [ ""/some/path"" ] + } +}"; + + var merged = RunMerge (mainJson, devJson); + + Assert.That (merged, Does.Contain ("\"OnlyInMain\": true"), "OnlyInMain preserved"); + // The dev file had no configProperties, so nothing from it should have leaked in. + Assert.That (merged, Does.Not.Contain ("additionalProbingPaths"), "dev-only non-configProperties content is not merged"); + } + + [Test] + public void InvalidMainJsonLogsError () + { + var tmp = Cache.CreateTemporaryDirectory (); + var mainFile = Path.Combine (tmp, "app.runtimeconfig.json"); + File.WriteAllText (mainFile, "this is not json {"); + + var task = CreateTask (); + task.RuntimeConfigFile = mainFile; + task.OutputFile = Path.Combine (tmp, "obj", "runtimeconfig.merged.json"); + + // The task must report an MSBuild error rather than throwing. + ExecuteTask (task, 1); + } + } +} diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj b/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj index 0656372608c8..65d218b13222 100644 --- a/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj @@ -13,7 +13,7 @@ - + diff --git a/tests/test-libraries/libtest.h b/tests/test-libraries/libtest.h index 1797a6379b7b..0b2822a47e1f 100644 --- a/tests/test-libraries/libtest.h +++ b/tests/test-libraries/libtest.h @@ -24,6 +24,20 @@ typedef void (^x_block_callback)(); void x_call_block (x_block_callback block); void* x_call_func_3 (void* (*fptr)(void*, void*, void*), void* p1, void* p2, void* p3); +// Helper for the issue #25861 design work: a C callback invoked from +// InitSurfacesSelfToManaged's 'init' with the 'self' pointer, used to verify that +// managed code can resolve 'self' to the wrapper being constructed while 'init' +// is still executing (see InitSurfacesSelfToManaged below). +typedef void (*init_self_callback) (void *self_ptr); +void x_set_init_self_callback (init_self_callback callback); + +// Helper for the issue #25861 deterministic test: a C callback invoked from +// ReuseSlotClassA's 'init' (after it has freed the alloc'd instance) with the freed +// address, so managed code can allocate a ReuseSlotClassB that deterministically +// reuses that address (see ReuseSlotClassA/ReuseSlotClassB below). +typedef void (*reuse_alloc_callback) (void *original_ptr); +void x_set_reuse_alloc_callback (reuse_alloc_callback callback); + void x_get_matrix_float2x2 (id self, const char *sel, float* r0c0, float* r0c1, float* r1c0, float* r1c1); void x_get_matrix_float3x3 (id self, const char *sel, float* r0c0, float* r0c1, float* r0c2, float* r1c0, float* r1c1, float* r1c2, float* r2c0, float* r2c1, float* r2c2); void x_get_matrix_float4x4 (id self, const char *sel, float* r0c0, float* r0c1, float* r0c2, float* r0c3, float* r1c0, float* r1c1, float* r1c2, float* r1c3, float* r2c0, float* r2c1, float* r2c2, float* r2c3, float* r3c0, float* r3c1, float* r3c2, float* r3c3); @@ -381,6 +395,52 @@ typedef void (^outerBlock) (innerBlock callback); -(void) buildHighway; @end +// Helper for the issue #25861 design work: a native class whose 'init' calls a +// method that can be overridden in managed code. Used to verify that an overridden +// managed method is invoked (on the correct instance) while 'init' is still +// executing. +@interface InitCallsVirtualMethod : NSObject { +} +-(instancetype) init; +-(void) virtualMethodCalledDuringInit: (int) value; +@end + +// Helper for the issue #25861 design work: a directly-bound native class (no managed +// subclass, so no gchandle ivar) whose 'init' synchronously surfaces 'self' to +// managed code via a C callback. Used to verify that managed code resolves 'self' +// to the wrapper being constructed (and doesn't create a duplicate wrapper) while +// 'init' is still executing. +@interface InitSurfacesSelfToManaged : NSObject { +} +-(instancetype) init; +@end + +// Helpers for a deterministic reproduction of the alloc/init handle-reuse race in +// issue #25861 (and #9478). ReuseSlotClassA's 'init' frees its own instance and forces +// the next allocation to reuse that exact address, so a ReuseSlotClassB allocated from +// managed code during that 'init' deterministically lands on the freed address. Both are +// directly-bound native classes (no managed subclass), so their alloc/dealloc aren't +// managed by the registrar and this address-reuse trick works. This reproduces the exact +// object_map clobber of issue #25861: while ReuseSlotClassA is executing its 'init', its +// (still-registered) alloc address is reused by a ReuseSlotClassB; when ReuseSlotClassA +// then rebinds its handle to the value 'init' returns, a non-ownership-aware unregister +// would remove the ReuseSlotClassB that now occupies that address from the object_map. +@interface ReuseSlotClassA : NSObject { +} +-(instancetype) init; +@end + +@interface ReuseSlotClassB : NSObject { +} +@end + +// Helper for issue #23679: a native class whose 'init' fails by raising an Objective-C +// exception. Constructing the managed wrapper throws; a later GC must not crash. +@interface InitReturnsNilClass : NSObject { +} +-(instancetype) init; +@end + #pragma clang diagnostic pop // NS_ASSUME_NONNULL_END diff --git a/tests/test-libraries/libtest.m b/tests/test-libraries/libtest.m index 19807b9bf5cd..566dbdca0782 100644 --- a/tests/test-libraries/libtest.m +++ b/tests/test-libraries/libtest.m @@ -4,6 +4,7 @@ #include #include #include +#include #include #include "libtest.h" @@ -1553,4 +1554,134 @@ -(void) buildHighway } @end +@implementation InitCallsVirtualMethod +-(instancetype) init +{ + if ((self = [super init]) != NULL) { + // Call a method that may be overridden in managed code, while 'init' is still + // executing. If a managed subclass overrides it, the overridden managed method + // must be invoked on this very instance. + [self virtualMethodCalledDuringInit: 0x1234]; + } + return self; +} +-(void) virtualMethodCalledDuringInit: (int) value +{ + // Default (native) implementation; overridden in managed code by the test. +} +@end + +static init_self_callback x_init_self_callback = NULL; +void x_set_init_self_callback (init_self_callback callback) +{ + x_init_self_callback = callback; +} + +@implementation InitSurfacesSelfToManaged +-(instancetype) init +{ + if ((self = [super init]) != NULL) { + // Synchronously surface 'self' to managed code while 'init' is still executing. + if (x_init_self_callback != NULL) + x_init_self_callback ((void *) self); + } + return self; +} +@end + +// A tiny custom "allocator" used to deterministically reproduce the alloc/init +// handle-reuse race in issue #25861. When x_forced_next_alloc is set, the next +// allocation reuses that exact address (instead of calloc'ing a fresh one), so a +// ReuseSlotClassB can be made to occupy the address a ReuseSlotClassA just vacated. +static void *x_forced_next_alloc = NULL; + +static id x_reuse_alloc (Class cls) +{ + void *mem; + if (x_forced_next_alloc != NULL) { + mem = x_forced_next_alloc; + x_forced_next_alloc = NULL; + } else { + mem = calloc (1, 256); + } + memset (mem, 0, 256); + return objc_constructInstance (cls, mem); +} + +static void x_reuse_dealloc (id self) +{ + // Destruct the instance but intentionally do NOT free its memory: the address may + // be deterministically reused by another object (that's the whole point of the + // issue #25861 reproduction), and leaking a few small buffers in a test is fine. + objc_destructInstance (self); +} + +static reuse_alloc_callback x_reuse_alloc_callback = NULL; +void x_set_reuse_alloc_callback (reuse_alloc_callback callback) +{ + x_reuse_alloc_callback = callback; +} + +// The dealloc methods below intentionally don't call [super dealloc]: they manage the +// object's memory manually (see x_reuse_dealloc) so an address can be reused. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-missing-super-calls" +@implementation ReuseSlotClassA ++(instancetype) allocWithZone: (NSZone *) zone +{ + return x_reuse_alloc (self); +} +-(void) dealloc +{ + x_reuse_dealloc (self); +} +-(instancetype) init +{ + void *x = (void *) self; + Class cls = object_getClass (self); + // Free this instance (its memory is not actually released, see x_reuse_dealloc). At + // this point the managed runtime still maps 'x' to the wrapper being constructed. + [self release]; + // Force the next allocation to reuse 'x', then let managed code allocate a + // ReuseSlotClassB; it will land exactly at 'x', so the managed runtime now maps 'x' + // to that new object instead. + x_forced_next_alloc = x; + if (x_reuse_alloc_callback != NULL) + x_reuse_alloc_callback (x); + x_forced_next_alloc = NULL; + void *fresh = objc_constructInstance (cls, calloc (1, 256)); + // Return a distinct, valid ReuseSlotClassA instance at a fresh address (not 'x'). + // Rebinding this wrapper's handle to that address is what would, with a + // non-ownership-aware unregister, remove the ReuseSlotClassB now living at 'x'. + return (ReuseSlotClassA *) fresh; +} +@end + +@implementation ReuseSlotClassB ++(instancetype) allocWithZone: (NSZone *) zone +{ + return x_reuse_alloc (self); +} +-(void) dealloc +{ + x_reuse_dealloc (self); +} +@end +#pragma clang diagnostic pop + +// Helper for issue #23679: a directly-bound native class whose 'init' fails by raising an +// Objective-C exception (as e.g. an invalid AVAssetWriterInput does). Constructing the +// managed wrapper throws, and a later GC must not crash trying to release a managed +// reference for the alloc'd instance. +@implementation InitReturnsNilClass +-(instancetype) init +{ + // Reproduce issue #23679: a native initializer that raises an Objective-C exception + // (as e.g. an invalid AVAssetWriterInput does). The managed runtime marshals this to + // a managed ObjCException; the alloc'd instance must be cleaned up so a later GC + // doesn't crash releasing a managed reference for it. + @throw [NSException exceptionWithName: @"InitReturnsNilClassException" reason: @"init failed" userInfo: nil]; +} +@end + #include "libtest.decompile.m" diff --git a/tests/xharness/AppRunner.cs b/tests/xharness/AppRunner.cs index 8f79f259d1ae..2285c2043452 100644 --- a/tests/xharness/AppRunner.cs +++ b/tests/xharness/AppRunner.cs @@ -274,7 +274,7 @@ public async Task RunAsync () listener.StartAsync (); // object that will take care of capturing and parsing the results - ICrashSnapshotReporter crashReporter = snapshotReporterFactory.Create (MainLog, Logs, isDevice: !isSimulator, deviceName); + ICrashSnapshotReporter crashReporter = snapshotReporterFactory.Create (MainLog, Logs, isDevice: !isSimulator, deviceName, AppInformation); var testReporterTimeout = TimeSpan.FromMinutes (harness.Timeout * timeoutMultiplier); var testReporter = testReporterFactory.Create (MainLog, @@ -288,8 +288,7 @@ public async Task RunAsync () harness.XmlJargon, deviceName, testReporterTimeout, - buildTask?.Logs?.Directory, - (level, message) => harness.Log (level, message)); + buildTask?.Logs?.Directory); listener.ConnectedTask .TimeoutAfter (TimeSpan.FromMinutes (harness.LaunchTimeout)) diff --git a/tests/xharness/CrashSnapshotReporterFactory.cs b/tests/xharness/CrashSnapshotReporterFactory.cs index d2bc2158570d..5f0001212e3b 100644 --- a/tests/xharness/CrashSnapshotReporterFactory.cs +++ b/tests/xharness/CrashSnapshotReporterFactory.cs @@ -13,7 +13,7 @@ public CrashSnapshotReporterFactory (IMlaunchProcessManager processManager) this.processManager = processManager ?? throw new ArgumentNullException (nameof (processManager)); } - public ICrashSnapshotReporter Create (ILog log, ILogs logs, bool isDevice, string? deviceName) => - new CrashSnapshotReporter (processManager, log, logs, isDevice, deviceName); + public ICrashSnapshotReporter Create (ILog log, ILogs logs, bool isDevice, string? deviceName, AppBundleInformation appInformation) => + new CrashSnapshotReporter (processManager, log, logs, isDevice, deviceName, appInformation); } } diff --git a/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs b/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs index 38f48645f457..74758e3518c9 100644 --- a/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs +++ b/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs @@ -676,7 +676,7 @@ internal static bool TryWriteStructuredTestReport (StreamWriter writer, string f if (string.IsNullOrEmpty (failedTest.Message)) { writer.WriteLine ("{0}
", failedTest.Name.AsHtml ()); } else { - writer.WriteLine ("{0}: {1}
", failedTest.Name.AsHtml (), failedTest.Message.AsHtml ()); + writer.WriteLine ("{0}: {1}
", failedTest.Name.AsHtml (), failedTest.Message.Cap (1024).AsHtml ()); } writer.WriteLine (""); } diff --git a/tests/xharness/Jenkins/TestTasks/MacExecuteTask.cs b/tests/xharness/Jenkins/TestTasks/MacExecuteTask.cs index 6b43a0205eba..b0f3ef1c9a49 100644 --- a/tests/xharness/Jenkins/TestTasks/MacExecuteTask.cs +++ b/tests/xharness/Jenkins/TestTasks/MacExecuteTask.cs @@ -53,6 +53,8 @@ public override async Task RunTestAsync () var assemblyName = project.GetAssemblyName (); Path = System.IO.Path.Combine (System.IO.Path.GetDirectoryName (ProjectFile)!, outputPath!, assemblyName + ".app", "Contents", "MacOS", assemblyName); } + var appBundlePath = System.IO.Path.GetFullPath (System.IO.Path.Combine (System.IO.Path.GetDirectoryName (Path)!, "..", "..")); + var appInformation = new AppBundleInformation (name!, "N/A", appBundlePath, appBundlePath, true, null, System.IO.Path.GetFileName (Path)); using (var resource = await NotifyAndAcquireDesktopResourceAsync ()) { using (var proc = new Process ()) { @@ -92,7 +94,7 @@ public override async Task RunTestAsync () if (!Jenkins.Harness.DryRun) { ExecutionResult = TestExecutingResult.Running; - snapshot = CrashReportSnapshotFactory.Create (log, Logs, isDevice: false, deviceName: null); + snapshot = CrashReportSnapshotFactory.Create (log, Logs, isDevice: false, deviceName: null, appInformation); await snapshot.StartCaptureAsync (); ProcessExecutionResult? result = null; @@ -120,7 +122,7 @@ public override async Task RunTestAsync () if (IsUnitTest) { var reporterFactory = new TestReporterFactory (ProcessManager); var listener = new Microsoft.DotNet.XHarness.iOS.Shared.Listeners.SimpleFileListener (xmlLog!.FullPath, log, xmlLog, useXmlOutput); - var reporter = reporterFactory.Create (Harness.HarnessLog!, log, Logs, snapshot!, listener, Harness.ResultParser, new AppBundleInformation ("N/A", "N/A", "N/A", "N/A", true, null), RunMode.MacOS, Harness.XmlJargon, "no device here", TimeSpan.Zero); + var reporter = reporterFactory.Create (Harness.HarnessLog!, log, Logs, snapshot!, listener, Harness.ResultParser, appInformation, RunMode.MacOS, Harness.XmlJargon, "no device here", TimeSpan.Zero); var rv = await reporter.ParseResult (); if (ExecutionResult == TestExecutingResult.Succeeded) { diff --git a/tests/xharness/Jenkins/TestVariationsFactory.cs b/tests/xharness/Jenkins/TestVariationsFactory.cs index 17daa9815743..284ece6a86d8 100644 --- a/tests/xharness/Jenkins/TestVariationsFactory.cs +++ b/tests/xharness/Jenkins/TestVariationsFactory.cs @@ -135,8 +135,10 @@ IEnumerable GetTestData (RunTestTask test) if (supports_coreclr) yield return new TestData { Variation = "Debug (trimmable static registrar)", TestVariation = "trimmable-static-registrar", Ignored = ignore }; yield return new TestData { Variation = "Release (managed static registrar, all optimizations)", TestVariation = "release|managed-static-registrar-all-optimizations-linkall", Ignored = ignore }; - if (supports_coreclr) - yield return new TestData { Variation = "Release (trimmable static registrar, all optimizations)", TestVariation = "trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + if (supports_coreclr) { + yield return new TestData { Variation = "Debug (trimmable static registrar, all optimizations)", TestVariation = "trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + yield return new TestData { Variation = "Release (trimmable static registrar, all optimizations)", TestVariation = "release|trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + } yield return new TestData { Variation = "Release (NativeAOT)", TestVariation = "release|nativeaot", Ignored = ignore }; yield return new TestData { Variation = "Release (trimmable static registrar, NativeAOT)", TestVariation = "trimmable-static-registrar|release|nativeaot", Ignored = ignore }; break; @@ -156,10 +158,12 @@ IEnumerable GetTestData (RunTestTask test) if (supports_coreclr) yield return new TestData { Variation = "Debug (trimmable static registrar)", TestVariation = "trimmable-static-registrar", Ignored = ignore }; yield return new TestData { Variation = "Release (managed static registrar, all optimizations)", TestVariation = "release|managed-static-registrar-all-optimizations-linkall", Ignored = ignore }; - if (supports_coreclr) - yield return new TestData { Variation = "Release (trimmable static registrar, all optimizations)", TestVariation = "trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; - yield return new TestData { Variation = "Release (NativeAOT, x64)", TestVariation = "release|nativeaot", Ignored = !supports_x64_simulator ? true : ignore, RuntimeIdentifier = x64_sim_runtime_identifier }; - yield return new TestData { Variation = "Release (trimmable static registrar, NativeAOT, x64)", TestVariation = "trimmable-static-registrar|release|nativeaot", Ignored = !supports_x64_simulator ? true : ignore, RuntimeIdentifier = x64_sim_runtime_identifier }; + if (supports_coreclr) { + yield return new TestData { Variation = "Debug (trimmable static registrar, all optimizations)", TestVariation = "trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + yield return new TestData { Variation = "Release (trimmable static registrar, all optimizations)", TestVariation = "release|trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + } + yield return new TestData { Variation = "Release (NativeAOT, x64)", TestVariation = "release|nativeaot", Ignored = !supports_x64 ? true : ignore, RuntimeIdentifier = x64_sim_runtime_identifier }; + yield return new TestData { Variation = "Release (trimmable static registrar, NativeAOT, x64)", TestVariation = "trimmable-static-registrar|release|nativeaot", Ignored = !supports_x64 ? true : ignore, RuntimeIdentifier = x64_sim_runtime_identifier }; if (supports_interpreter) { yield return new TestData { Variation = "Debug (interpreter)", TestVariation = "interpreter", Ignored = ignore }; yield return new TestData { Variation = "Release (interpreter)", TestVariation = "release|interpreter", Ignored = ignore }; @@ -194,8 +198,10 @@ IEnumerable GetTestData (RunTestTask test) if (supports_coreclr) yield return new TestData { Variation = "Release (trimmable static registrar)", TestVariation = "trimmable-static-registrar", Ignored = ignore }; yield return new TestData { Variation = "Release (managed static registrar, all optimizations)", TestVariation = "release|managed-static-registrar-all-optimizations-linkall", Ignored = ignore }; - if (supports_coreclr) - yield return new TestData { Variation = "Release (trimmable static registrar, all optimizations)", TestVariation = "trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + if (supports_coreclr) { + yield return new TestData { Variation = "Debug (trimmable static registrar, all optimizations)", TestVariation = "trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + yield return new TestData { Variation = "Release (trimmable static registrar, all optimizations)", TestVariation = "release|trimmable-static-registrar-all-optimizations-linkall", Ignored = ignore }; + } yield return new TestData { Variation = "Release (NativeAOT)", TestVariation = "release|nativeaot", Ignored = ignore }; yield return new TestData { Variation = "Release (NativeAOT, x64)", TestVariation = "release|nativeaot", Ignored = !supports_x64 ? true : ignore, RuntimeIdentifier = x64_runtime_identifier }; yield return new TestData { Variation = $"Release (NativeAOT, .NET 11 defaults)", TestVariation = "release|nativeaot-net11-defaults", Ignored = ignore }; diff --git a/tests/xharness/TestReporter.cs b/tests/xharness/TestReporter.cs index fdbf2bc6efab..18ac94c2bcc2 100644 --- a/tests/xharness/TestReporter.cs +++ b/tests/xharness/TestReporter.cs @@ -60,7 +60,7 @@ public class TestReporter : ITestReporter { public bool ResultsUseXml => xmlJargon != XmlResultJargon.Missing; - bool TestExecutionStarted => listener.ConnectedTask.IsCompletedSuccessfully && listener.ConnectedTask.Result; + public bool TestProtocolConnected => listener.ConnectedTask.IsCompletedSuccessfully && listener.ConnectedTask.Result; public TestReporter ( IMlaunchProcessManager processManager, @@ -228,7 +228,7 @@ public void LaunchCallback (Task launchResult) cancellationTokenSource.Cancel (); timedout = true; - if (TestExecutionStarted) { + if (TestProtocolConnected) { mainLog.WriteLine ($"Test execution timed out after {timeoutWatch.Elapsed.TotalMinutes:0.##} minutes"); return; } @@ -464,7 +464,7 @@ async Task GenerateXmlFailures (string failure, bool crashed, string? crashReaso await crashReporter.EndCaptureAsync (TimeSpan.FromSeconds (crashLogWaitTime)); if (timedout) { - if (TestExecutionStarted) { + if (TestProtocolConnected) { result.ExecutingResult = TestExecutingResult.TimedOut; } else { result.ExecutingResult = TestExecutingResult.LaunchTimedOut; diff --git a/tests/xharness/TestReporterFactory.cs b/tests/xharness/TestReporterFactory.cs index 77adb724b219..b77da2c4880e 100644 --- a/tests/xharness/TestReporterFactory.cs +++ b/tests/xharness/TestReporterFactory.cs @@ -11,8 +11,6 @@ using Microsoft.DotNet.XHarness.iOS.Shared.Logging; using Microsoft.DotNet.XHarness.iOS.Shared.XmlResults; -using ExceptionLogger = System.Action; - namespace Xharness { public class TestReporterFactory : ITestReporterFactory { readonly IMlaunchProcessManager processManager; @@ -35,7 +33,6 @@ public ITestReporter Create ( string? device, TimeSpan timeout, string? additionalLogsDirectory = null, - ExceptionLogger? exceptionLogger = null, bool generateHtml = false) { return new TestReporter ( @@ -52,8 +49,7 @@ public ITestReporter Create ( device, timeout, additionalLogsDirectory, - exceptionLogger, - generateHtml); + generateHtml: generateHtml); } } } diff --git a/tools/api-tools/api-tools.slnx b/tools/api-tools/api-tools.slnx new file mode 100644 index 000000000000..b8af9596266e --- /dev/null +++ b/tools/api-tools/api-tools.slnx @@ -0,0 +1,5 @@ + + + + + diff --git a/tools/api-tools/mono-api-html-tests/ApiDiffTests.cs b/tools/api-tools/mono-api-html-tests/ApiDiffTests.cs new file mode 100644 index 000000000000..e48e10c04bdf --- /dev/null +++ b/tools/api-tools/mono-api-html-tests/ApiDiffTests.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.IO; + +using NUnit.Framework; + +using Mono.ApiTools; + +namespace MonoApiHtmlTests { + + [TestFixture] + public class ApiDiffTests { + + static string CreateApiInfo (string classes) + { + return $@" + + + + {classes} + + + +"; + } + + // A new type that implements generic interfaces used to leak the + // %LESSERTHANREPLACEMENT% / %GREATERTHANREPLACEMENT% placeholders into the + // generated output (see the MultiplexedFormatter raw Write path). + [Test] + public void GenericInterfacesDoNotLeakPlaceholders () + { + var source = CreateApiInfo (""); + var target = CreateApiInfo (@" + + + + + + "); + + var sourceFile = Path.GetTempFileName (); + var targetFile = Path.GetTempFileName (); + var htmlFile = Path.GetTempFileName (); + var markdownFile = Path.GetTempFileName (); + try { + File.WriteAllText (sourceFile, source); + File.WriteAllText (targetFile, target); + + var config = new ApiDiffFormattedConfig { + HtmlOutput = htmlFile, + MarkdownOutput = markdownFile, + }; + ApiDiffFormatted.Generate (sourceFile, targetFile, config); + + var html = File.ReadAllText (htmlFile); + var markdown = File.ReadAllText (markdownFile); + + Assert.That (html, Does.Not.Contain ("%LESSERTHANREPLACEMENT%"), "html LesserThan placeholder"); + Assert.That (html, Does.Not.Contain ("%GREATERTHANREPLACEMENT%"), "html GreaterThan placeholder"); + Assert.That (markdown, Does.Not.Contain ("%LESSERTHANREPLACEMENT%"), "markdown LesserThan placeholder"); + Assert.That (markdown, Does.Not.Contain ("%GREATERTHANREPLACEMENT%"), "markdown GreaterThan placeholder"); + + Assert.That (html, Does.Contain ("IEnumerable<AuthorizationRight>"), "html generic"); + Assert.That (markdown, Does.Contain ("IEnumerable"), "markdown generic"); + } finally { + File.Delete (sourceFile); + File.Delete (targetFile); + File.Delete (htmlFile); + File.Delete (markdownFile); + } + } + } +} diff --git a/tools/api-tools/mono-api-html-tests/mono-api-html-tests.csproj b/tools/api-tools/mono-api-html-tests/mono-api-html-tests.csproj new file mode 100644 index 000000000000..060fb629fa5e --- /dev/null +++ b/tools/api-tools/mono-api-html-tests/mono-api-html-tests.csproj @@ -0,0 +1,18 @@ + + + + net$(BundledNETCoreAppTargetFrameworkVersion) + false + + + + + + + + + + + + + diff --git a/tools/api-tools/mono-api-html/MultiplexedFormatter.cs b/tools/api-tools/mono-api-html/MultiplexedFormatter.cs index cc8556c93424..f3304e35c954 100644 --- a/tools/api-tools/mono-api-html/MultiplexedFormatter.cs +++ b/tools/api-tools/mono-api-html/MultiplexedFormatter.cs @@ -237,19 +237,21 @@ public override void WriteLine () public override void WriteLine (string line) { foreach (var formatter in formatters) - formatter.WriteLine (line); + formatter.WriteLine (Replace (formatter, line)); } public override void WriteLine (string format, params object [] arguments) { + var line = string.Format (format, arguments); foreach (var formatter in formatters) - formatter.WriteLine (format, arguments); + formatter.WriteLine (Replace (formatter, line)); } public override void WriteLine (StringBuilder sb) { + var line = sb.ToString (); foreach (var formatter in formatters) - formatter.WriteLine (sb); + formatter.WriteLine (Replace (formatter, line)); } public override void Write (char value) @@ -261,19 +263,21 @@ public override void Write (char value) public override void Write (string line) { foreach (var formatter in formatters) - formatter.Write (line); + formatter.Write (Replace (formatter, line)); } public override void Write (string format, params object [] arguments) { + var line = string.Format (format, arguments); foreach (var formatter in formatters) - formatter.Write (format, arguments); + formatter.Write (Replace (formatter, line)); } public override void Write (StringBuilder sb) { + var line = sb.ToString (); foreach (var formatter in formatters) - formatter.Write (sb); + formatter.Write (Replace (formatter, line)); } } } diff --git a/tools/api-tools/mono-api-info/mono-api-info.csproj b/tools/api-tools/mono-api-info/mono-api-info.csproj index 1a3f7362601b..19d81026fd7b 100644 --- a/tools/api-tools/mono-api-info/mono-api-info.csproj +++ b/tools/api-tools/mono-api-info/mono-api-info.csproj @@ -6,7 +6,7 @@
- + diff --git a/tools/common/Application.cs b/tools/common/Application.cs index 24085dedda40..fc10ae655f6b 100644 --- a/tools/common/Application.cs +++ b/tools/common/Application.cs @@ -286,6 +286,9 @@ public bool PackageManagedDebugSymbols { } set { package_managed_debug_symbols = value; } } + public bool GenerateTrustedPlatformAssemblies; + public bool IsMultiRidBuild; + public List TrustedPlatformAssemblies = new List (); public Version GetMacCatalystiOSVersion (Version macOSVersion) { diff --git a/tools/common/ErrorHelper.tools.cs b/tools/common/ErrorHelper.tools.cs index ae8c8ce88c02..0092f16535fb 100644 --- a/tools/common/ErrorHelper.tools.cs +++ b/tools/common/ErrorHelper.tools.cs @@ -321,12 +321,26 @@ static bool ShowInternal (IToolLog log, Exception e) if (!error && GetWarningLevel (log, mte.Code) == WarningLevel.Disable) return false; // This is an ignored warning. - log.LogError (mte.ToString ()); + // Report warnings as warnings, otherwise they'd end up failing the build when + // the log is an MSBuild task (which is the case for the assembly preparer). + if (error) { + log.LogError (mte); + } else { + log.LogWarning (mte); + } ShowInner (log, e); - if (log.Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) - log.LogError (e.StackTrace); + if (log.Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) { + // Report the stack trace as an error or a message depending on + // whether we're showing an error or a warning, otherwise warnings + // would end up failing the build when the log is an MSBuild task. + if (error) { + log.LogError (e.StackTrace); + } else { + log.Log (e.StackTrace); + } + } } else { log.LogError ("error " + GetPrefix (log) + "0000: Unexpected error - Please file a bug report at https://github.com/dotnet/macios/issues/new"); log.LogError (e.ToString ()); diff --git a/tools/common/Optimizations.cs b/tools/common/Optimizations.cs index 63e22af33e07..770d2412466a 100644 --- a/tools/common/Optimizations.cs +++ b/tools/common/Optimizations.cs @@ -11,7 +11,7 @@ namespace Xamarin.Bundler { public class Optimizations { static readonly string [] opt_names = { - "remove-uithread-checks", + "remove-uithread-checks", // this optimization has been replaced by the 'CheckForIllegalCrossThreadCalls' MSBuild property (the 'ObjCRuntime.Runtime.CheckForIllegalCrossThreadCalls' feature switch), but leave it here so that we won't break customers trying to enable/disable it "dead-code-elimination", "inline-isdirectbinding", "inline-intptr-size", // this optimization has been removed, but leave it here so that we won't break customers trying to enable/disable it @@ -32,7 +32,7 @@ public class Optimizations { }; static readonly ApplePlatform [] [] valid_platforms = new ApplePlatform [] [] { - /* Opt.RemoveUIThreadChecks */ new ApplePlatform [] { ApplePlatform.iOS, ApplePlatform.MacOSX, ApplePlatform.TVOS, ApplePlatform.MacCatalyst }, + /* Opt.RemoveUIThreadChecks */ new ApplePlatform [] { }, /* Opt.DeadCodeElimination */ new ApplePlatform [] { ApplePlatform.iOS, ApplePlatform.MacOSX, ApplePlatform.TVOS, ApplePlatform.MacCatalyst }, /* Opt.InlineIsDirectBinding */ new ApplePlatform [] { ApplePlatform.iOS, ApplePlatform.MacOSX, ApplePlatform.TVOS, ApplePlatform.MacCatalyst }, /* Opt.InlineIntPtrSize */ new ApplePlatform [] { }, @@ -222,11 +222,6 @@ public void Initialize (Application app, out List messages) } } - // by default we keep the code to ensure we're executing on the UI thread (for UI code) for debug builds - // but this can be overridden to either (a) remove it from debug builds or (b) keep it in release builds - if (!RemoveUIThreadChecks.HasValue) - RemoveUIThreadChecks = !app.EnableDebug; - // By default we always eliminate dead code. if (!DeadCodeElimination.HasValue) DeadCodeElimination = true; diff --git a/tools/common/StaticRegistrar.cs b/tools/common/StaticRegistrar.cs index de9ec3ca58fb..e8be7ec7f96d 100644 --- a/tools/common/StaticRegistrar.cs +++ b/tools/common/StaticRegistrar.cs @@ -2480,6 +2480,8 @@ string ToObjCParameterType (TypeReference type, string descriptiveMethodName, Li if (!IsPlatformType (td)) return "id"; + CheckNamespace (td, exceptions); + if (HasProtocolAttribute (td)) { return "id<" + GetExportedTypeName (td) + ">"; } else { diff --git a/tools/common/Target.cs b/tools/common/Target.cs index 88b005b8574c..9ea63a176898 100644 --- a/tools/common/Target.cs +++ b/tools/common/Target.cs @@ -273,9 +273,33 @@ void GenerateMainImpl (StringWriter sw, Abi abi) sw.WriteLine ($"\tNULL"); sw.WriteLine ("};"); + var trusted_platform_assembly_names = app.TrustedPlatformAssemblies + .Distinct (StringComparer.Ordinal) + // Any .exe files must be at the end, due to https://github.com/dotnet/runtime/issues/62735 + .OrderBy (v => Path.GetExtension (v).Equals (".exe", StringComparison.OrdinalIgnoreCase)) + .ThenBy (v => v, StringComparer.Ordinal) + .ToArray (); + if (app.GenerateTrustedPlatformAssemblies && trusted_platform_assembly_names.Length > 0) { + sw.WriteLine (); + sw.WriteLine ("static const char * const xamarin_trusted_platform_assembly_names_array[] = {"); + foreach (var name in trusted_platform_assembly_names) + sw.WriteLine ("\t\"{0}\",", EscapeCString (name)); + sw.WriteLine ("\tNULL"); + sw.WriteLine ("};"); + } + sw.WriteLine ("void xamarin_setup_impl ()"); sw.WriteLine ("{"); + if (app.GenerateTrustedPlatformAssemblies && trusted_platform_assembly_names.Length > 0) { + sw.WriteLine ("\txamarin_trusted_platform_assembly_names = xamarin_trusted_platform_assembly_names_array;"); + if (app.IsMultiRidBuild) { + sw.WriteLine ("#if defined (SUPPORTS_UNIVERSAL_BUILDS)"); + sw.WriteLine ("\txamarin_is_multi_rid_build = true;"); + sw.WriteLine ("#endif"); + } + } + if (app.UseInterpreter) { sw.WriteLine ("\tmono_icall_table_init ();"); sw.WriteLine ("\tmono_marshal_ilgen_init ();"); @@ -376,6 +400,29 @@ void GenerateMainImpl (StringWriter sw, Abi abi) sw.WriteLine ("}"); } + static string EscapeCString (string value) + { + var sb = new StringBuilder (); + foreach (var b in Encoding.UTF8.GetBytes (value)) { + switch (b) { + case (byte) '\\': + sb.Append ("\\\\"); + break; + case (byte) '"': + sb.Append ("\\\""); + break; + default: + if (b >= 0x20 && b <= 0x7e) { + sb.Append ((char) b); + } else { + sb.Append ('\\').Append (Convert.ToString (b, 8).PadLeft (3, '0')); + } + break; + } + } + return sb.ToString (); + } + static readonly char [] charsToReplaceAot = new [] { '.', '-', '+', '<', '>' }; static string EncodeAotSymbol (string symbol) { diff --git a/tools/devops/automation/scripts/bash/configure-decisions.sh b/tools/devops/automation/scripts/bash/configure-decisions.sh index dac588bafaed..09aa726c66e9 100755 --- a/tools/devops/automation/scripts/bash/configure-decisions.sh +++ b/tools/devops/automation/scripts/bash/configure-decisions.sh @@ -23,7 +23,8 @@ elif [[ "${LABELS_RUN_PACKAGED_MACOS_TESTS:-}" == "True" ]]; then elif [[ "${LABELS_SKIP_ALL_TESTS:-}" == "True" ]]; then # All tests have been skipped RUN_MAC_TESTS=false -elif [[ "${CONFIGURE_PLATFORMS_INCLUDE_DOTNET_MACOS:-}" != "" ]]; then +elif [[ "${CONFIGURE_PLATFORMS_INCLUDE_DOTNET_MACOS:-}" != "" ]] || + [[ "${CONFIGURE_PLATFORMS_INCLUDE_DOTNET_MACCATALYST:-}" != "" ]]; then # Run mac tests if a .NET desktop platform is enabled RUN_MAC_TESTS=true else diff --git a/tools/dotnet-linker/AppBundleRewriter.cs b/tools/dotnet-linker/AppBundleRewriter.cs index 8e79a5b8f32a..6e478c732ab5 100644 --- a/tools/dotnet-linker/AppBundleRewriter.cs +++ b/tools/dotnet-linker/AppBundleRewriter.cs @@ -1133,6 +1133,20 @@ public MethodReference Runtime_CreateRuntimeException { } } + public MethodReference Runtime_InvokeGenericRegistrarTrampoline { + get { + return GetMethodReference (PlatformAssembly, + ObjCRuntime_Runtime, "InvokeGenericRegistrarTrampoline", + nameof (Runtime_InvokeGenericRegistrarTrampoline), + isStatic: true, + System_Object, + System_RuntimeTypeHandle, + System_RuntimeMethodHandle, + new ArrayType (System_Object), + new ByReferenceType (System_IntPtr)); + } + } + public MethodReference BlockLiteral_CreateBlockForDelegate { get { return GetMethodReference (PlatformAssembly, @@ -1533,19 +1547,52 @@ bool IsAssemblyTrimmed (IMemberDefinition member) return action == AssemblyAction.Link; } + /// + /// Returns the signature to use in a [DynamicDependency] attribute for a method: the + /// method name (and generic arity) if no other method in the same type has that name and + /// arity, otherwise the full signature (including the parameter list). + /// + /// + /// + /// The trimmer only compares the parameter lists when the signature has one, and computing + /// the signature of a parameter crashes the trimmer if the parameter's type is a nested type + /// reference (see ), + /// so use the name alone whenever it's unambiguous. + /// + /// + /// The trimmer matches a signature without a parameter list on both the name and the generic + /// arity, so methods that differ in arity (Foo () vs Foo<T> ()) don't + /// collide and don't need a parameter list either. + /// + /// + static string GetDynamicDependencySignature (MethodDefinition method) + { + var count = 0; + foreach (var candidate in method.DeclaringType.Methods) { + if (candidate.Name != method.Name) + continue; + if (candidate.GenericParameters.Count != method.GenericParameters.Count) + continue; + if (++count > 1) + return DocumentationComments.GetSignature (method); + } + return DocumentationComments.GetNameSignature (method); + } + public bool AddDynamicDependencyAttribute (MethodDefinition addToMethod, MethodDefinition dependsOn) { if (!IsAssemblyTrimmed (dependsOn)) return false; + var signature = GetDynamicDependencySignature (dependsOn); if (addToMethod.DeclaringType == dependsOn.DeclaringType) { - var attribute = CreateDynamicDependencyAttribute (DocumentationComments.GetSignature (dependsOn)); + var attribute = CreateDynamicDependencyAttribute (signature); return AddAttributeOnlyOnce (addToMethod, attribute); } else if (addToMethod.DeclaringType.Module == dependsOn.DeclaringType.Module) { - var attribute = CreateDynamicDependencyAttribute (DocumentationComments.GetSignature (dependsOn), dependsOn.DeclaringType); + var attribute = CreateDynamicDependencyAttribute (signature, dependsOn.DeclaringType); return AddAttributeOnlyOnce (addToMethod, attribute); } else { - var attribute = CreateDynamicDependencyAttribute (DocumentationComments.GetSignature (dependsOn), dependsOn.DeclaringType, dependsOn.DeclaringType.Module.Assembly); + var attribute = CreateDynamicDependencyAttribute (signature, dependsOn.DeclaringType, dependsOn.DeclaringType.Module.Assembly); return AddAttributeOnlyOnce (addToMethod, attribute); } } @@ -1611,6 +1658,11 @@ public CustomAttribute CreateDynamicDependencyAttribute (DynamicallyAccessedMemb /// Instead add one DynamicDependency attribute per member declared on the type itself, and a single /// DynamicDependency attribute for the interfaces the type implements. /// + /// + /// Methods are preserved by name (without the parameter list), which preserves every overload - + /// which is what we want here anyway (and it avoids a trimmer crash, see + /// ). + /// /// /// The method on which to add the dynamic dependency attributes. /// The type whose members should be preserved. @@ -1624,7 +1676,7 @@ public bool AddPreserveAllMembersDynamicDependencyAttributes (MethodDefinition a } foreach (var method in type.Methods) { if (!method.HasCustomAttribute ("System.Runtime.CompilerServices", "CompilerGeneratedAttribute")) - signatures.Add (DocumentationComments.GetSignature (method)); + signatures.Add (DocumentationComments.GetNameSignature (method)); } // Properties and events don't have a documentation comment signature helper, but the trimmer will // match any member with the given name, which is good enough (and it's what we want here anyway). @@ -1683,13 +1735,14 @@ static bool HasAnyInterfaces (TypeDefinition? type) public bool AddDynamicDependencyAttributeToStaticConstructor (TypeDefinition onType, MethodDefinition forMethod) { CustomAttribute attrib; + var signature = GetDynamicDependencySignature (forMethod); if (onType == forMethod.DeclaringType) { - attrib = CreateDynamicDependencyAttribute (DocumentationComments.GetSignature (forMethod)); + attrib = CreateDynamicDependencyAttribute (signature); } else if (onType.Module == forMethod.DeclaringType.Module) { - attrib = CreateDynamicDependencyAttribute (DocumentationComments.GetSignature (forMethod), forMethod.DeclaringType); + attrib = CreateDynamicDependencyAttribute (signature, forMethod.DeclaringType); } else { - attrib = CreateDynamicDependencyAttribute (DocumentationComments.GetSignature (forMethod), forMethod.DeclaringType, forMethod.Module.Assembly); + attrib = CreateDynamicDependencyAttribute (signature, forMethod.DeclaringType, forMethod.Module.Assembly); } return AddAttributeToStaticConstructor (onType, attrib); @@ -1951,7 +2004,7 @@ internal bool ImplementConstructNSObjectFactoryMethod (Tuner.DerivedLinkContext il.Emit (OpCodes.Newobj, ctor); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); // make sure the trimmer doesn't trim it away if the type is kept if (context.App.Registrar == RegistrarMode.TrimmableStatic) { @@ -2035,7 +2088,7 @@ internal bool ImplementConstructINativeObjectFactoryMethod (Tuner.DerivedLinkCon throw new UnreachableException (); } - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); // make sure the trimmer doesn't trim it away if the type is kept if (context.App.Registrar == RegistrarMode.TrimmableStatic) { diff --git a/tools/dotnet-linker/CecilExtensions.cs b/tools/dotnet-linker/CecilExtensions.cs index eabb02a43cad..b42e30ca22eb 100644 --- a/tools/dotnet-linker/CecilExtensions.cs +++ b/tools/dotnet-linker/CecilExtensions.cs @@ -4,6 +4,7 @@ using Mono.Cecil; using Mono.Cecil.Cil; +using Mono.Cecil.Rocks; using Xamarin.Bundler; @@ -76,8 +77,15 @@ public static MethodBody CreateBody (this MethodDefinition self, out ILProcessor return body; } - public static void GenerateILOffsets (this MethodBody body) + // Call this method once a generated method body is complete. + public static void FinalizeGeneratedBody (this MethodBody body) { + // Use the macro/short form of instructions whenever possible. This makes the generated IL + // smaller, and it also works around a bug in the CoreCLR interpreter, which reads the operand + // of the long form of the ldloc/stloc instructions at the wrong offset (the bug was fixed in + // https://github.com/dotnet/runtime/pull/131547). + body.OptimizeMacros (); + // This does not compute precise offsets, it just assigns a unique number to each instruction // The trimmer relies on unique offsets to identify instructions int instructionOffset = 0; @@ -164,7 +172,7 @@ public static MethodDefinition AddDefaultConstructor (this TypeDefinition type, il.Emit (OpCodes.Ldarg_0); il.Emit (OpCodes.Call, abr.System_Object__ctor); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); return defaultCtor; } diff --git a/tools/dotnet-linker/DocumentionComments.cs b/tools/dotnet-linker/DocumentionComments.cs index 002023176561..0a3373d7fae8 100644 --- a/tools/dotnet-linker/DocumentionComments.cs +++ b/tools/dotnet-linker/DocumentionComments.cs @@ -55,5 +55,30 @@ public static string GetSignature (MethodDefinition method) return docCommentId.Substring (methodNameStart); } + + /// + /// Returns the signature for a method without the parameter list (the method name, and the + /// generic arity if the method is generic). The trimmer will match any method with the given + /// name (and arity), which means every overload is preserved. + /// + /// + /// + /// This must be used when every overload should be preserved anyway, because the trimmer + /// crashes (NullReferenceException in DocumentationSignatureGenerator) when computing the + /// signature of a method whose parameters are nested types from another assembly, because + /// it only handles nested type definitions, not nested type references. + /// + /// + /// Ref: https://github.com/dotnet/runtime/issues/131892 + /// + /// + public static string GetNameSignature (MethodDefinition method) + { + var signature = GetSignature (method); + var parameterListStart = signature.IndexOf ('('); + if (parameterListStart == -1) + return signature; + return signature.Substring (0, parameterListStart); + } } } diff --git a/tools/dotnet-linker/LinkerConfiguration.cs b/tools/dotnet-linker/LinkerConfiguration.cs index db23d5510749..5770852228ac 100644 --- a/tools/dotnet-linker/LinkerConfiguration.cs +++ b/tools/dotnet-linker/LinkerConfiguration.cs @@ -359,6 +359,10 @@ Configurator GetConfigurator (string linker_file) new LoadValue ((key, value) => FrameworkAssemblies.Add (value)), new SaveValue ((key, storage) => storage.AddRange (FrameworkAssemblies.OrderBy (v => v).Select (v => $"{key}={v}"))) )}, + { "GenerateTrustedPlatformAssemblies", ( + new LoadValue ((key, value) => loadBool (key, value, out Application.GenerateTrustedPlatformAssemblies)), + new SaveValue ((key, storage) => saveOptionalDefaultFalseBool (key, Application.GenerateTrustedPlatformAssemblies, storage)) + )}, { "HotReloadCompatibleBuild", ( new LoadValue ((key, value) => HotReloadCompatibleBuild = string.Equals ("true", value, StringComparison.OrdinalIgnoreCase)), new SaveValue ((key, storage) => saveOptionalDefaultFalseBool (key, HotReloadCompatibleBuild, storage)) @@ -408,6 +412,10 @@ Configurator GetConfigurator (string linker_file) new LoadValue ((key, value) => Application.IsExtension = string.Equals ("true", value, StringComparison.OrdinalIgnoreCase)), new SaveValue ((key, storage) => storage.Add ($"{key}={(Application.IsExtension ? "true" : "false")}")) )}, + { "IsMultiRidBuild", ( + new LoadValue ((key, value) => loadBool (key, value, out Application.IsMultiRidBuild)), + new SaveValue ((key, storage) => saveOptionalDefaultFalseBool (key, Application.IsMultiRidBuild, storage)) + )}, { "ItemsDirectory", ( new LoadValue ((key, value) => ItemsDirectory = value), new SaveValue ((key, storage) => saveNonEmpty (key, ItemsDirectory, storage)) diff --git a/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs b/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs index 9c81ced16891..15e869095fdd 100644 --- a/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs +++ b/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs @@ -18,20 +18,23 @@ public class PreserveSmartEnumConversionsStep : AssemblyModifierStep { protected override string Name { get; } = "Smart Enum Conversion Preserver"; protected override int ErrorCode { get; } = 2200; - // When set, we can't modify user assemblies (that would break Hot Reload), so instead of injecting - // [DynamicDependency] attributes into the referencing (possibly user) assembly, we collect the - // framework-side conversion methods and emit an ILLink root-descriptor XML that preserves them + // When set for a given assembly, we can't modify it (that would break Hot Reload), so instead of + // injecting [DynamicDependency] attributes into the referencing (possibly user) assembly, we collect + // the framework-side conversion methods and emit an ILLink root-descriptor XML that preserves them // unconditionally. This only makes sense in the assembly-preparer, where the descriptor is consumed // by the subsequent trimmer pass (in the trimmer itself we keep the current attribute-injection // behaviour, which doesn't affect Hot Reload since Hot Reload requires the assembly-preparer). - bool UseXmlDescriptionFile { - get { + // + // Assemblies that are trimmed can't be hot reloaded, so we can modify those, and it's important that + // we do: preserving every smart enum conversion in our platform assembly unconditionally would keep + // a lot of code (and thus native frameworks) alive that should have been trimmed away. + bool UseXmlDescriptionFile (AssemblyDefinition assembly) + { #if ASSEMBLY_PREPARER - return Configuration.HotReloadCompatibleBuild; + return Configuration.HotReloadCompatibleBuild && Annotations.GetAction (assembly) != AssemblyAction.Link; #else - return false; + return false; #endif - } } // The framework-side conversion methods to preserve via the root-descriptor XML. @@ -71,16 +74,16 @@ bool Preserve (Tuple pair, bool alreadyProce if (conds.Length == 0) return false; - if (UseXmlDescriptionFile) { - // Don't modify the (possibly user) assembly: collect the framework-side conversion methods so - // they can be preserved unconditionally via a root-descriptor XML instead. - xmlDescriptor.PreserveMethod (pair.Item1); - xmlDescriptor.PreserveMethod (pair.Item2); - return false; - } - var modified = false; foreach (var condition in conds) { + if (UseXmlDescriptionFile (condition.Module.Assembly)) { + // Don't modify the (possibly user) assembly: collect the framework-side conversion methods + // so they can be preserved unconditionally via a root-descriptor XML instead. + xmlDescriptor.PreserveMethod (pair.Item1); + xmlDescriptor.PreserveMethod (pair.Item2); + continue; + } + modified |= abr.AddDynamicDependencyAttribute (condition, pair.Item1); modified |= abr.AddDynamicDependencyAttribute (condition, pair.Item2); } @@ -90,7 +93,7 @@ bool Preserve (Tuple pair, bool alreadyProce protected override void TryEndProcess () { - if (!UseXmlDescriptionFile || xmlDescriptor.IsEmpty) + if (xmlDescriptor.IsEmpty) return; var xmlPath = Path.Combine (Configuration.CacheDirectory, "preserve-smart-enum-conversions.xml"); diff --git a/tools/dotnet-linker/Steps/GenerateMainStep.cs b/tools/dotnet-linker/Steps/GenerateMainStep.cs index ce690fe4828c..ce835b27f02b 100644 --- a/tools/dotnet-linker/Steps/GenerateMainStep.cs +++ b/tools/dotnet-linker/Steps/GenerateMainStep.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text; using Xamarin.Linker; @@ -21,6 +22,13 @@ protected override void TryEndProcess () var app = Configuration.Application; + if (app.GenerateTrustedPlatformAssemblies) { + app.TrustedPlatformAssemblies.AddRange (app.Assemblies.Select (v => v.FileName)); +#if ASSEMBLY_PREPARER + app.TrustedPlatformAssemblies.AddRange (Configuration.AddedAssemblies.Select (v => Path.GetFileName (v.Path))); +#endif + } + // We want this called before any other initialization methods. registration_methods.Insert (0, "xamarin_initialize_dotnet"); diff --git a/tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs b/tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs index 3622e5faec61..fd1993f07597 100644 --- a/tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs +++ b/tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs @@ -403,6 +403,9 @@ MethodDefinition GetOrCreateGetNativeFieldMethod (MethodDefinition callingMethod } il.Append (il.Create (OpCodes.Ret)); + // See the comment in CecilExtensions.FinalizeGeneratedBody for why this is needed. + body.FinalizeGeneratedBody (); + return rv; } @@ -504,6 +507,9 @@ MethodDefinition GetOrCreateSetNativeFieldMethod (MethodDefinition callingMethod } il.Append (il.Create (OpCodes.Ret)); + // See the comment in CecilExtensions.FinalizeGeneratedBody for why this is needed. + body.FinalizeGeneratedBody (); + return rv; } @@ -558,6 +564,9 @@ MethodDefinition GetOrCreateSetNativeStringMethod (MethodDefinition callingMetho il.Append (il.Create (OpCodes.Stind_I)); il.Append (il.Create (OpCodes.Ret)); + // See the comment in CecilExtensions.FinalizeGeneratedBody for why this is needed. + body.FinalizeGeneratedBody (); + return rv; } @@ -909,6 +918,9 @@ protected override bool ProcessMethod (MethodDefinition method) il.Append (il.Create (OpCodes.Ldind_I)); il.Append (il.Create (OpCodes.Ret)); + // See the comment in CecilExtensions.FinalizeGeneratedBody for why this is needed. + method.Body.FinalizeGeneratedBody (); + modified = true; return modified; // we replace the whole method body, so no need to continue processing the method } diff --git a/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs b/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs index 4a5dd9acc19e..1d0b9794bc1a 100644 --- a/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs +++ b/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs @@ -289,7 +289,7 @@ void GenerateLookupTypeId (AssemblyTrampolineInfo infos, TypeDefinition registra il.Emit (OpCodes.Ldc_I4_M1); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } void GenerateLookupType (AssemblyTrampolineInfo infos, TypeDefinition registrarType, List types) @@ -331,7 +331,7 @@ void GenerateLookupType (AssemblyTrampolineInfo infos, TypeDefinition registrarT il.Emit (OpCodes.Ldloc, temporary); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } void GenerateConstructNSObject (TypeDefinition registrarType) @@ -388,7 +388,7 @@ void GenerateConstructNSObject (TypeDefinition registrarType) il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } void GenerateConstructINativeObject (TypeDefinition registrarType) @@ -446,7 +446,7 @@ void GenerateConstructINativeObject (TypeDefinition registrarType) il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } // We need to preserve the constructor because it might not be used anywhere else. @@ -502,7 +502,7 @@ void GenerateRegisterWrapperTypes (TypeDefinition type) il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } void GenerateLookupUnmanagedFunction (TypeDefinition registrar_type, IList trampolineInfos) @@ -536,7 +536,7 @@ void GenerateLookupUnmanagedFunction (TypeDefinition registrar_type, IList.TypeMap.dll) instead of being emitted into the // user assembly. This is required for Hot Reload (user assemblies must stay unmodified). - // Only non-generic types are relocated for now; generic-type proxies are a follow-up. + // This applies to both non-generic and generic declaring types (generic types dispatch to + // a relocated generic helper by reflection, see the generic branch in + // CreateUnmanagedCallersMethod). bool ShouldRelocateTrampolines (MethodDefinition method) { return Configuration.HotReloadCompatibleBuild - && App.Registrar == RegistrarMode.TrimmableStatic - && !method.DeclaringType.HasGenericParameters; + && App.Registrar == RegistrarMode.TrimmableStatic; } // Finds the companion assembly (_.TypeMap) for the given user assembly among the loaded @@ -483,6 +484,15 @@ bool CreateUnmanagedCallersMethod (MethodDefinition method, AssemblyTrampolineIn var isGeneric = method.DeclaringType.HasGenericParameters; if (isGeneric && method.IsStatic) { throw ErrorHelper.CreateError (4130 /* The registrar cannot export static methods in generic classes ('{0}'). */, method.FullName); + } else if (relocate && isGeneric && !method.IsConstructor) { + // When relocating trampolines for Hot Reload we must not modify the user assembly, + // so the proxy-interface trick used below (which adds an interface implementation to + // the user type) is not an option. Instead we emit a *generic* helper method into + // the companion whose body performs the same type-parameter-aware conversions, and + // the static UnmanagedCallersOnly callback dispatches to it by reflection (closing + // the helper over the instance's actual generic arguments at runtime). This is only + // used under a Hot-Reload-compatible build, which always runs under the JIT. + EmitGenericCompanionTrampoline (method, callback, callbackType); } else if (isGeneric && !method.IsConstructor) { // We generate a proxy interface for each generic NSObject subclass. In the static UnmanagedCallersOnly methods we don't // know the generic parameters of the type we're working with and we need to use this trick to be able to call methods on the @@ -579,6 +589,207 @@ bool CreateUnmanagedCallersMethod (MethodDefinition method, AssemblyTrampolineIn return modified; } + // Emits the relocated generic trampoline for a method declared in a generic type, when + // relocating into the companion assembly for Hot Reload. Rather than adding a proxy + // interface implementation to the user type (which would modify the user assembly), we emit + // a generic helper method into the companion whose body performs the type-parameter-aware + // conversions, and make the static callback dispatch to it by reflection (closing the helper + // over the instance's actual generic arguments at runtime). The 'callback' passed in is the + // UnmanagedCallersOnly trampoline (with only its 'pobj' parameter added so far). + void EmitGenericCompanionTrampoline (MethodDefinition method, MethodDefinition callback, TypeDefinition callbackType) + { + var module = callback.Module; + var placeholderType = abr.System_IntPtr; + + // Create the generic helper method, mirroring the user type's generic parameters. + var implMethod = new MethodDefinition (callback.Name + "__impl", MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig, placeholderType); + callbackType.Methods.Add (implMethod); + + var genericParameterMap = new Dictionary (); + foreach (var userGenericParameter in method.DeclaringType.GenericParameters) { + var implGenericParameter = new GenericParameter (userGenericParameter.Name, implMethod) { + Attributes = userGenericParameter.Attributes, + }; + implMethod.GenericParameters.Add (implGenericParameter); + genericParameterMap [userGenericParameter] = implGenericParameter; + } + + // Copy the generic parameter constraints in a second pass, since a constraint may + // reference another generic parameter of the same type. Constraints must be copied so + // that the closed instantiations we create at runtime (via MakeGenericMethod) are valid, + // and so that the 'castclass' to the user generic type inside the body verifies. + for (var i = 0; i < method.DeclaringType.GenericParameters.Count; i++) { + var userGenericParameter = method.DeclaringType.GenericParameters [i]; + var implGenericParameter = implMethod.GenericParameters [i]; + foreach (var constraint in userGenericParameter.Constraints) { + var constraintType = ImportTypeReference (module, RemapGenericParameter (constraint.ConstraintType, genericParameterMap)); + implGenericParameter.Constraints.Add (new GenericParameterConstraint (constraintType)); + } + } + + // Add the 'self' parameter (arg0), typed as the user generic type closed over the + // helper's own generic parameters (e.g. CustomNSObject). This mirrors the 'this' of + // the instance implementation, so EmitCallToExportedMethod can push it with 'ldarg.0'. + var selfType = ImportTypeReference (module, method.DeclaringType.CreateGenericInstanceType (implMethod.GenericParameters.ToArray ())); + implMethod.AddParameter (selfType); // self + + // Emit the body (parameter/return conversions + the call to the exported method). Because + // implMethod has its own generic parameters, EmitCallToExportedMethod remaps the user + // type's generic parameters to the helper's parameters and uses them for the call. + EmitCallToExportedMethod (method, implMethod); + ImportCallbackReferences (implMethod); + + // Build the static UnmanagedCallersOnly callback that dispatches to the helper. Its + // signature mirrors the helper's (minus 'self', plus the native 'exception_gchandle' + // pointer): [pobj, sel, p0..., IntPtr* exception_gchandle]. + callback.ReturnType = implMethod.ReturnType; + for (var i = 1; i < implMethod.Parameters.Count - 1; i++) { + callback.AddParameter (implMethod.Parameters [i].ParameterType); + } + callback.AddParameter (new PointerType (abr.System_IntPtr)); // exception_gchandle + + EmitGenericReflectionDispatch (method, callback, implMethod); + + // Keep the helper (and everything its body references, including the user method) alive + // through trimming. This is emitted on the companion side only; the user assembly is not + // modified. The 'ldtoken' reference to implMethod from the callback also keeps it alive. + abr.AddDynamicDependencyAttribute (callback, implMethod); + } + + // Emits the body of the UnmanagedCallersOnly callback for a relocated generic trampoline. It + // resolves the instance, boxes the native arguments into an object array, and calls the + // runtime helper which closes the generic helper method over the instance's actual generic + // arguments and invokes it. The exception GCHandle is returned by the helper (reflection + // can't marshal an 'IntPtr*' output) and written back through the native pointer here. + void EmitGenericReflectionDispatch (MethodDefinition method, MethodDefinition callback, MethodDefinition implMethod) + { + var body = callback.CreateBody (out var il); + + // The helper's leading arguments: 'self' followed by the native arguments ('sel', p0...). + // This excludes the trailing 'out IntPtr exception_gchandle' slot. + var leadingCount = implMethod.Parameters.Count - 1; + + // var self = Runtime.GetNSObject (pobj); + var selfVar = body.AddVariable (abr.Foundation_NSObject); + il.Emit (OpCodes.Ldarg_0); + il.Emit (OpCodes.Call, abr.Runtime_GetNSObject__System_IntPtr); + il.Emit (OpCodes.Stloc, selfVar); + + // var args = new object [leadingCount + 1]; + // The array is allocated with one extra (trailing) slot for the helper's + // 'out IntPtr exception_gchandle' parameter, so that the runtime helper can pass the + // array straight to MethodInfo.Invoke without having to allocate and copy a larger one. + var argsVar = body.AddVariable (new ArrayType (abr.System_Object)); + il.Emit (OpCodes.Ldc_I4, leadingCount + 1); + il.Emit (OpCodes.Newarr, abr.System_Object); + il.Emit (OpCodes.Stloc, argsVar); + + // args [0] = self; + il.Emit (OpCodes.Ldloc, argsVar); + il.Emit (OpCodes.Ldc_I4_0); + il.Emit (OpCodes.Ldloc, selfVar); + il.Emit (OpCodes.Stelem_Ref); + + // args [i] = (object) ; (i: 1..leadingCount-1 -> sel, p0, ...) + for (var i = 1; i < leadingCount; i++) { + var parameterType = callback.Parameters [i].ParameterType; + il.Emit (OpCodes.Ldloc, argsVar); + il.Emit (OpCodes.Ldc_I4, i); + il.EmitLoadArgument (i); + il.Emit (OpCodes.Box, parameterType); + il.Emit (OpCodes.Stelem_Ref); + } + + // IntPtr exception_gchandle; + var exceptionVar = body.AddVariable (abr.System_IntPtr); + + // var rv = Runtime.InvokeGenericRegistrarTrampoline (self, ldtoken (UserType), ldtoken (implMethod), args, out exception_gchandle); + il.Emit (OpCodes.Ldloc, selfVar); + il.Emit (OpCodes.Ldtoken, method.DeclaringType); + il.Emit (OpCodes.Ldtoken, implMethod); + il.Emit (OpCodes.Ldloc, argsVar); + il.Emit (OpCodes.Ldloca, exceptionVar); + il.Emit (OpCodes.Call, abr.Runtime_InvokeGenericRegistrarTrampoline); + + var isVoid = callback.ReturnType.Is ("System", "Void"); + VariableDefinition? resultVar = null; + if (isVoid) { + il.Emit (OpCodes.Pop); + } else { + resultVar = body.AddVariable (abr.System_Object); + il.Emit (OpCodes.Stloc, resultVar); + } + + // *exception_gchandle = exception_gchandle; + il.EmitLoadArgument (callback.Parameters.Count - 1); + il.Emit (OpCodes.Ldloc, exceptionVar); + il.Emit (OpCodes.Stind_I); + + // return () rv; + if (!isVoid) { + var returnType = callback.ReturnType; + if (returnType.IsValueType) { + // InvokeGenericRegistrarTrampoline returns null on failure (the exception is + // reported through exception_gchandle). Unbox_Any on a null value type would + // throw a NullReferenceException that escapes the UnmanagedCallersOnly boundary, + // so return default () instead when the result is null. + var unboxResult = il.Create (OpCodes.Nop); + var returnResult = il.Create (OpCodes.Nop); + var defaultVar = body.AddVariable (returnType); + il.Emit (OpCodes.Ldloc, resultVar); + il.Emit (OpCodes.Brtrue, unboxResult); + // rv is null: return default () + il.Emit (OpCodes.Ldloca, defaultVar); + il.Emit (OpCodes.Initobj, returnType); + il.Emit (OpCodes.Ldloc, defaultVar); + il.Emit (OpCodes.Br, returnResult); + // rv is not null: return () rv + il.Append (unboxResult); + il.Emit (OpCodes.Ldloc, resultVar); + il.Emit (OpCodes.Unbox_Any, returnType); + il.Append (returnResult); + } else { + il.Emit (OpCodes.Ldloc, resultVar); + il.Emit (OpCodes.Unbox_Any, returnType); + } + } + il.Emit (OpCodes.Ret); + + body.FinalizeGeneratedBody (); + } + + // Recursively substitutes generic parameters in a type reference according to the given map. + // Used when relocating a generic type's trampoline into a companion generic helper method: + // the user type's generic parameters (owned by the type) are remapped to the helper method's + // generic parameters. + static TypeReference RemapGenericParameter (TypeReference type, IDictionary map) + { + switch (type) { + case GenericParameter genericParameter: + return map.TryGetValue (genericParameter, out var mapped) ? mapped : genericParameter; + case GenericInstanceType git: { + var result = new GenericInstanceType (RemapGenericParameter (git.ElementType, map)); + foreach (var argument in git.GenericArguments) + result.GenericArguments.Add (RemapGenericParameter (argument, map)); + return result; + } + case ArrayType array: + return new ArrayType (RemapGenericParameter (array.ElementType, map), array.Rank); + case PointerType pointer: + return new PointerType (RemapGenericParameter (pointer.ElementType, map)); + case ByReferenceType byReference: + return new ByReferenceType (RemapGenericParameter (byReference.ElementType, map)); + case PinnedType pinned: + return new PinnedType (RemapGenericParameter (pinned.ElementType, map)); + case RequiredModifierType required: + return new RequiredModifierType (RemapGenericParameter (required.ModifierType, map), RemapGenericParameter (required.ElementType, map)); + case OptionalModifierType optional: + return new OptionalModifierType (RemapGenericParameter (optional.ModifierType, map), RemapGenericParameter (optional.ElementType, map)); + default: + return type; + } + } + // Re-imports every type/method/field reference used by the trampoline (its signature, local // variables, instruction operands and exception handlers) into the module the trampoline // belongs to. This is needed when we relocate a trampoline into the companion assembly, @@ -718,7 +929,7 @@ public void EmitCallToProxyMethod (MethodDefinition method, MethodDefinition cal il.Emit (OpCodes.Callvirt, proxyInterfaceMethod); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition callback) @@ -742,6 +953,21 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition var isInstanceCategory = isCategory && StaticRegistrar.HasThisAttribute (method); var isGeneric = method.DeclaringType.HasGenericParameters; + // When 'callback' is itself a generic method (i.e. it has its own generic parameters), we + // are emitting the relocated generic helper into the companion assembly: a static method + // mirroring the user type's generic parameters, whose 'self' argument (arg0) is the user + // type closed over the helper's own generic parameters. The body is identical to the + // instance implementation, except every reference to the user type's generic parameters + // must be remapped to the helper's generic parameters. + var genericCompanionImpl = callback.HasGenericParameters; + Dictionary? genericParameterMap = null; + if (genericCompanionImpl) { + genericParameterMap = new Dictionary (); + for (var i = 0; i < method.DeclaringType.GenericParameters.Count; i++) + genericParameterMap [method.DeclaringType.GenericParameters [i]] = callback.GenericParameters [i]; + } + TypeReference RemapType (TypeReference tr) => genericParameterMap is null ? tr : RemapGenericParameter (tr, genericParameterMap); + Trace (il, $"ENTER"); if (!isVoid || method.IsConstructor) @@ -889,7 +1115,7 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition for (var p = parameterStart; p < managedParameterCount; p++) { var nativeParameter = callback.AddParameter (placeholderType); // p{p} var nativeParameterIndex = p + nativeParameterOffset; - var managedParameterType = method.Parameters [p].ParameterType; + var managedParameterType = RemapType (method.Parameters [p].ParameterType); var baseParameter = baseMethod.Parameters [p]; var isOutParameter = IsOutParameter (method, p, baseParameter); @@ -898,7 +1124,18 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition } if (EmitConversion (method, il, managedParameterType, true, p, out var nativeType, postProcessing, isOutParameter, nativeParameterIndex)) { - nativeParameter.ParameterType = nativeType; + // In the generic companion helper the trampoline is dispatched via reflection, + // which boxes each native argument into an 'object []' and calls + // MethodInfo.Invoke. A pointer-typed native parameter (which is what + // out/ref/pointer parameters produce) can't survive that round-trip: a pointer + // isn't boxable and Invoke can't marshal it. Represent such parameters as a + // plain 'IntPtr' instead - it's a boxable, pointer-sized value type, and loading + // it with 'ldarg' yields a native int that the already-emitted body uses + // directly as the pointer (native int is usable wherever an unmanaged pointer is + // expected, for both reads and writes). The native ABI is unchanged since a + // pointer and an IntPtr are both pointer-sized, and the out/ref write-back still + // happens through that same pointer value inside the helper body. + nativeParameter.ParameterType = genericCompanionImpl && nativeType is PointerType ? abr.System_IntPtr : nativeType; } else { nativeParameter.ParameterType = placeholderType; AddException (ErrorHelper.CreateError (99, "Unable to emit conversion for parameter {2} of type {0}. Method: {1}", method.Parameters [p].ParameterType, GetMethodSignatureWithSourceCode (method), p)); @@ -909,7 +1146,15 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition if (callSuperParameter is not null) callback.Parameters.Add (callSuperParameter); - callback.AddParameter (new PointerType (abr.System_IntPtr)); // exception_gchandle + // For the relocated generic companion helper the trampoline is dispatched via reflection, + // which can't marshal an 'IntPtr*' (pointer) argument, so we use a byref 'out IntPtr' + // (which reflection handles as a standard output parameter). The runtime helper writes the + // resulting GCHandle into the UnmanagedCallersOnly callback's native 'IntPtr*' pointer. + if (genericCompanionImpl) { + callback.AddParameter (new ByReferenceType (abr.System_IntPtr)); // exception_gchandle + } else { + callback.AddParameter (new PointerType (abr.System_IntPtr)); // exception_gchandle + } if (relocatedCtorObjVar is not null) { // The object was allocated earlier and pushed onto the stack (underneath the @@ -925,7 +1170,10 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition il.Emit (OpCodes.Ldnull); il.Emit (OpCodes.Newobj, ctor); } else if (isGeneric && !method.IsConstructor) { - var targetMethod = method.DeclaringType.CreateMethodReferenceOnGenericType (method, method.DeclaringType.GenericParameters.ToArray ()); + var genericArguments = genericCompanionImpl + ? callback.GenericParameters.ToArray () + : method.DeclaringType.GenericParameters.ToArray (); + var targetMethod = method.DeclaringType.CreateMethodReferenceOnGenericType (method, genericArguments); il.Emit (OpCodes.Call, targetMethod); } else if (method.IsStatic) { il.Emit (OpCodes.Call, method); @@ -934,7 +1182,7 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition } if (returnVariable is not null) { - if (EmitConversion (method, il, method.ReturnType, false, -1, out var nativeReturnType, postProcessing)) { + if (EmitConversion (method, il, RemapType (method.ReturnType), false, -1, out var nativeReturnType, postProcessing)) { returnVariable.VariableType = nativeReturnType; callback.ReturnType = nativeReturnType; } else { @@ -958,7 +1206,7 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition body.Instructions.RemoveAt (i); } - AddExceptionHandler (il, returnVariable, placeholderNextInstruction, isGeneric && !method.IsConstructor, out var eh, out var leaveEHInstruction); + AddExceptionHandler (il, returnVariable, placeholderNextInstruction, out var eh, out var leaveEHInstruction); // Generate code to return null/default value/void if (returnVariable is not null) { @@ -995,10 +1243,10 @@ public void EmitCallToExportedMethod (MethodDefinition method, MethodDefinition instr.Operand = leaveTryInstructionOperand; eh.HandlerEnd = (Instruction) leaveEHInstruction.Operand; - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } - void AddExceptionHandler (ILProcessor il, VariableDefinition? returnVariable, Instruction placeholderNextInstruction, bool isGeneric, out ExceptionHandler eh, out Instruction leaveEHInstruction) + void AddExceptionHandler (ILProcessor il, VariableDefinition? returnVariable, Instruction placeholderNextInstruction, out ExceptionHandler eh, out Instruction leaveEHInstruction) { var body = il.Body; var method = body.Method; @@ -1013,7 +1261,10 @@ void AddExceptionHandler (ILProcessor il, VariableDefinition? returnVariable, In il.Emit (OpCodes.Stloc, exceptionVariable); eh.HandlerStart = il.Body.Instructions.Last (); eh.TryEnd = eh.HandlerStart; - il.Emit (OpCodes.Ldarg, isGeneric ? method.Parameters.Count : method.Parameters.Count - 1); + // The exception_gchandle output pointer is always the last parameter of the trampoline + // (whether the trampoline is a static callback or an instance/static implementation + // method). Account for the implicit 'this' argument when the method has one. + il.Emit (OpCodes.Ldarg, (method.HasThis ? 1 : 0) + method.Parameters.Count - 1); il.Emit (OpCodes.Ldloc, exceptionVariable); il.Emit (OpCodes.Call, abr.Runtime_AllocGCHandle); il.Emit (OpCodes.Stind_I); @@ -1281,7 +1532,10 @@ bool EmitConversion (MethodDefinition method, ILProcessor il, TypeReference type if (toManaged) { var gim = new GenericInstanceMethod (abr.NSArray_ArrayFromHandle_1); if (gp is not null) { - var gemericParameter = method.DeclaringType.GenericParameters.Single (x => x.Name == gp.Name); + // When emitting the relocated generic companion helper, the generic parameter has + // already been remapped to one of the helper method's own generic parameters, and + // must be used as-is (a type generic parameter isn't valid in a static method). + var gemericParameter = gp.Type == GenericParameterType.Method ? gp : method.DeclaringType.GenericParameters.Single (x => x.Name == gp.Name); gim.GenericArguments.Add (gemericParameter); } else { gim.GenericArguments.Add (elementType); @@ -1785,7 +2039,7 @@ MethodDefinition CloneConstructorWithNativeHandle (MethodDefinition ctor) il.Emit (OpCodes.Call, ctor); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); return clonedCtor; } @@ -1805,7 +2059,7 @@ void ImplementNSObjectRegisterToggleRefMethodStub () var body = registerToggleRef!.CreateBody (out var il); il.Emit (OpCodes.Ret); - body.GenerateILOffsets (); + body.FinalizeGeneratedBody (); } } } diff --git a/tools/dotnet-linker/Steps/TrimmableRegistrarStep.cs b/tools/dotnet-linker/Steps/TrimmableRegistrarStep.cs index 39e0a2e4e426..dcc7e18a7c05 100644 --- a/tools/dotnet-linker/Steps/TrimmableRegistrarStep.cs +++ b/tools/dotnet-linker/Steps/TrimmableRegistrarStep.cs @@ -136,11 +136,23 @@ AssemblyDefinition CreateTypeMapRootAssembly (ModuleParameters moduleParameters, // We write the assembly here even if it hasn't changed, because otherwise we'll just end up re-creating // it again during the next incremental build. if (!useEntryAssemblyAsRootTypeMapAssembly) { - rootTypeMapAssembly.Write (createdRootTypeMapAssemblyPath); + WriteDeterministically (rootTypeMapAssembly, createdRootTypeMapAssemblyPath); } return rootTypeMapAssembly; } + // Writes the assembly to disk with a deterministic module version id (MVID) and timestamp. + // The MVIDs of the typemap assemblies end up in the generated registrar code, so if we let Cecil + // compute a new random MVID every time, the registrar code would change on every build, and we'd + // have to recompile (and relink) it every time. + static void WriteDeterministically (AssemblyDefinition assembly, string path) + { + assembly.Write (path, new WriterParameters { + DeterministicMvid = true, + Timestamp = 0, + }); + } + MethodReference CreateMethodReference (MethodReference methodReference, params TypeReference [] declaringTypeGenericArguments) { var methodDeclaringType = methodReference.DeclaringType; @@ -720,7 +732,7 @@ void addPostAction (AssemblyDefinition assembly, Action acti // We write the assembly here even if it hasn't changed, because otherwise we'll just end up re-creating // it again during the next incremental build. - typeMapAssembly.Write (typeMapAssemblyPath); + WriteDeterministically (typeMapAssembly, typeMapAssemblyPath); } foreach (var kvp in postActionsByAssembly) { diff --git a/tools/linker/OptimizeGeneratedCode.cs b/tools/linker/OptimizeGeneratedCode.cs index bed0043af180..32369392c302 100644 --- a/tools/linker/OptimizeGeneratedCode.cs +++ b/tools/linker/OptimizeGeneratedCode.cs @@ -563,9 +563,6 @@ static bool ProcessCalls (OptimizeGeneratedCodeData data, MethodDefinition calle instructionsAddedOrRemoved = 0; var mr = ins.Operand as MethodReference; switch (mr?.Name) { - case "EnsureUIThread": - modified |= ProcessEnsureUIThread (data, caller, ins); - break; case "get_IsDirectBinding": modified |= ProcessIsDirectBinding (data, caller, ins); break; @@ -582,28 +579,6 @@ static bool ProcessCalls (OptimizeGeneratedCodeData data, MethodDefinition calle return modified; } - static bool ProcessEnsureUIThread (OptimizeGeneratedCodeData data, MethodDefinition caller, Instruction ins) - { - if (data.Optimizations.RemoveUIThreadChecks != true) - return false; - - // Verify we're checking the right get_EnsureUIThread call - var declaringTypeNamespace = data.LinkContext.App.Platform == Utils.ApplePlatform.MacOSX ? Namespaces.AppKit : Namespaces.UIKit; - var declaringTypeName = data.LinkContext.App.Platform == Utils.ApplePlatform.MacOSX ? "NSApplication" : "UIApplication"; - var mr = ins.Operand as MethodReference; - if (mr is null || !mr.DeclaringType.Is (declaringTypeNamespace, declaringTypeName)) - return false; - - // Verify a few assumptions before doing anything - const string operation = "remove calls to [NS|UI]Application::EnsureUIThread"; - if (!ValidateInstruction (data.App, caller, ins, operation, Code.Call)) - return false; - - // This is simple: just remove the call - Nop (ins); // call void UIKit.UIApplication::EnsureUIThread() - return true; - } - static bool? IsDirectBindingConstant (OptimizeGeneratedCodeData data, TypeDefinition type) { return type.IsNSObject (data.LinkContext) ? type.GetIsDirectBindingConstant (data.LinkContext) : null;