repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/runtime
65,983
Update p/invoke source generator errors to use SYSLIB prefix
Use the established `SYSLIB` prefix convention, since the p/invoke source generator will be part of libraries.
elinor-fung
2022-03-01T01:37:49Z
2022-03-01T22:24:04Z
2a00ad862b4d43521297ab4f1d4946fd1e718b90
a7a4ed959365851d0f9f38f5dfb9b2fe7ef04a93
Update p/invoke source generator errors to use SYSLIB prefix. Use the established `SYSLIB` prefix convention, since the p/invoke source generator will be part of libraries.
./src/tests/Interop/DisabledRuntimeMarshalling/AutoLayout.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Xunit; using static DisabledRuntimeMarshallingNative; namespace DisabledRuntimeMarshalling; public unsafe class PInvokes_AutoLayout { [Fact] public static void AutoLayoutStruct() { short s = 42; bool b = true; Assert.Throws<MarshalDirectiveException>(() => DisabledRuntimeMarshallingNative.CallWithAutoLayoutStruct(new AutoLayoutStruct())); } [Fact] public static void StructWithAutoLayoutField() { short s = 42; bool b = true; AssertThrowsMarshalDirectiveOrTypeLoad(() => DisabledRuntimeMarshallingNative.CallWithAutoLayoutStruct(new SequentialWithAutoLayoutField())); } [Fact] public static void StructWithNestedAutoLayoutField() { short s = 42; bool b = true; AssertThrowsMarshalDirectiveOrTypeLoad(() => DisabledRuntimeMarshallingNative.CallWithAutoLayoutStruct(new SequentialWithAutoLayoutNestedField())); } private static void AssertThrowsMarshalDirectiveOrTypeLoad(Action testCode) { try { testCode(); return; } catch (Exception ex) when(ex is MarshalDirectiveException or TypeLoadException) { return; } catch (Exception ex) { Assert.False(true, $"Expected either a MarshalDirectiveException or a TypeLoadException, but received a '{ex.GetType().FullName}' exception: '{ex.ToString()}'"); } Assert.False(true, $"Expected either a MarshalDirectiveException or a TypeLoadException, but received no exception."); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Xunit; using static DisabledRuntimeMarshallingNative; namespace DisabledRuntimeMarshalling; public unsafe class PInvokes_AutoLayout { [Fact] public static void AutoLayoutStruct() { short s = 42; bool b = true; Assert.Throws<MarshalDirectiveException>(() => DisabledRuntimeMarshallingNative.CallWithAutoLayoutStruct(new AutoLayoutStruct())); } [Fact] public static void StructWithAutoLayoutField() { short s = 42; bool b = true; AssertThrowsMarshalDirectiveOrTypeLoad(() => DisabledRuntimeMarshallingNative.CallWithAutoLayoutStruct(new SequentialWithAutoLayoutField())); } [Fact] public static void StructWithNestedAutoLayoutField() { short s = 42; bool b = true; AssertThrowsMarshalDirectiveOrTypeLoad(() => DisabledRuntimeMarshallingNative.CallWithAutoLayoutStruct(new SequentialWithAutoLayoutNestedField())); } private static void AssertThrowsMarshalDirectiveOrTypeLoad(Action testCode) { try { testCode(); return; } catch (Exception ex) when(ex is MarshalDirectiveException or TypeLoadException) { return; } catch (Exception ex) { Assert.False(true, $"Expected either a MarshalDirectiveException or a TypeLoadException, but received a '{ex.GetType().FullName}' exception: '{ex.ToString()}'"); } Assert.False(true, $"Expected either a MarshalDirectiveException or a TypeLoadException, but received no exception."); } }
-1
dotnet/runtime
65,983
Update p/invoke source generator errors to use SYSLIB prefix
Use the established `SYSLIB` prefix convention, since the p/invoke source generator will be part of libraries.
elinor-fung
2022-03-01T01:37:49Z
2022-03-01T22:24:04Z
2a00ad862b4d43521297ab4f1d4946fd1e718b90
a7a4ed959365851d0f9f38f5dfb9b2fe7ef04a93
Update p/invoke source generator errors to use SYSLIB prefix. Use the established `SYSLIB` prefix convention, since the p/invoke source generator will be part of libraries.
./src/tests/JIT/Methodical/xxobj/sizeof/sizeof32_Target_64Bit_and_arm_il_d.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> <!-- There is a 32 and 64 version of this test to allow it to be compiled for all targets --> <CLRTestTargetUnsupported Condition="'$(TargetArchitecture)' == 'x86'">true</CLRTestTargetUnsupported> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="sizeof32_Target_64Bit_and_arm.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> <!-- There is a 32 and 64 version of this test to allow it to be compiled for all targets --> <CLRTestTargetUnsupported Condition="'$(TargetArchitecture)' == 'x86'">true</CLRTestTargetUnsupported> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="sizeof32_Target_64Bit_and_arm.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,983
Update p/invoke source generator errors to use SYSLIB prefix
Use the established `SYSLIB` prefix convention, since the p/invoke source generator will be part of libraries.
elinor-fung
2022-03-01T01:37:49Z
2022-03-01T22:24:04Z
2a00ad862b4d43521297ab4f1d4946fd1e718b90
a7a4ed959365851d0f9f38f5dfb9b2fe7ef04a93
Update p/invoke source generator errors to use SYSLIB prefix. Use the established `SYSLIB` prefix convention, since the p/invoke source generator will be part of libraries.
./src/tests/Loader/classloader/generics/Instantiation/Negative/abstract01.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="abstract01.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="abstract01.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/pipelines/libraries/enterprise/linux.yml
# Disable pipeline for ordinary pushes to the branches trigger: none # To reduce load on the pipeline, enable it only for PRs that affect critical networking code pr: branches: include: - main - release/*.* paths: # If you are changing these and start including eng/common, adjust the Maestro subscriptions # so that this build can block dependency auto-updates (this build is currently ignored) include: - eng/pipelines/libraries/enterprise/* - src/libraries/Common/src/System/Net/* - src/libraries/Common/tests/System/Net/* - src/native/libs/System.Net.Security.Native/* - src/libraries/System.Net.Http/* - src/libraries/System.Net.Security/* pool: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open variables: - template: ../variables.yml - name: enterpriseTestsSetup value: $(sourcesRoot)/Common/tests/System/Net/EnterpriseTests/setup - name: containerRunTestsCommand value: /repo/dotnet.sh build /t:test - name: containerLibrariesRoot value: /repo/src/libraries steps: - bash: | cd $(enterpriseTestsSetup) docker-compose build displayName: Build test machine images env: DOTNET_RUNTIME_REPO_ROOT: $(Build.SourcesDirectory) - bash: | cd $(enterpriseTestsSetup) docker-compose up -d displayName: Start test network and machines env: DOTNET_RUNTIME_REPO_ROOT: $(Build.SourcesDirectory) - bash: | docker exec linuxclient bash /setup/test-webserver.sh displayName: Test linuxclient connection to web server - bash: | docker exec linuxclient bash -c '/repo/build.sh -subset clr+libs -runtimeconfiguration release -ci /p:NativeOptimizationDataSupported=false' displayName: Build product sources - bash: | docker exec linuxclient $(containerRunTestsCommand) $(containerLibrariesRoot)/System.Net.Http/tests/EnterpriseTests/System.Net.Http.Enterprise.Tests.csproj docker exec linuxclient $(containerRunTestsCommand) $(containerLibrariesRoot)/System.Net.Security/tests/EnterpriseTests/System.Net.Security.Enterprise.Tests.csproj displayName: Build and run tests - bash: | cd $(enterpriseTestsSetup) docker-compose down displayName: Stop test network and machines env: DOTNET_RUNTIME_REPO_ROOT: $(Build.SourcesDirectory) - task: PublishTestResults@2 inputs: testRunner: 'xUnit' testResultsFiles: '**/testResults.xml' testRunTitle: 'Enterprise Tests' mergeTestResults: true failTaskOnFailedTests: true
# Disable pipeline for ordinary pushes to the branches trigger: none # To reduce load on the pipeline, enable it only for PRs that affect critical networking code pr: branches: include: - main - release/*.* paths: # If you are changing these and start including eng/common, adjust the Maestro subscriptions # so that this build can block dependency auto-updates (this build is currently ignored) include: - eng/pipelines/libraries/enterprise/* - src/libraries/Common/src/System/Net/* - src/libraries/Common/tests/System/Net/* - src/native/libs/System.Net.Security.Native/* - src/libraries/System.Net.Http/* - src/libraries/System.Net.Security/* variables: - template: ../variables.yml - name: enterpriseTestsSetup value: $(sourcesRoot)/Common/tests/System/Net/EnterpriseTests/setup - name: containerRunTestsCommand value: /repo/dotnet.sh build /t:test - name: containerLibrariesRoot value: /repo/src/libraries jobs: - job: EnterpriseLinuxTests timeoutInMinutes: 120 pool: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open steps: - bash: | cd $(enterpriseTestsSetup) docker-compose build displayName: Build test machine images env: DOTNET_RUNTIME_REPO_ROOT: $(Build.SourcesDirectory) - bash: | cd $(enterpriseTestsSetup) docker-compose up -d displayName: Start test network and machines env: DOTNET_RUNTIME_REPO_ROOT: $(Build.SourcesDirectory) - bash: | docker exec linuxclient bash /setup/test-webserver.sh displayName: Test linuxclient connection to web server - bash: | docker exec linuxclient bash -c '/repo/build.sh -subset clr+libs -runtimeconfiguration release -ci /p:NativeOptimizationDataSupported=false' docker exec linuxclient bash -c '/repo/dotnet.sh build $(containerLibrariesRoot)/System.Net.Http/tests/EnterpriseTests/System.Net.Http.Enterprise.Tests.csproj' docker exec linuxclient bash -c '/repo/dotnet.sh build $(containerLibrariesRoot)/System.Net.Security/tests/EnterpriseTests/System.Net.Security.Enterprise.Tests.csproj' displayName: Build product sources - bash: | docker exec linuxclient bash -c 'if [ -f /erc/resolv.conf.ORI ]; then cp -f /erc/resolv.conf.ORI /etc/resolv.conf; fi' docker exec linuxclient $(containerRunTestsCommand) $(containerLibrariesRoot)/System.Net.Http/tests/EnterpriseTests/System.Net.Http.Enterprise.Tests.csproj docker exec linuxclient $(containerRunTestsCommand) $(containerLibrariesRoot)/System.Net.Security/tests/EnterpriseTests/System.Net.Security.Enterprise.Tests.csproj displayName: Build and run tests - bash: | cd $(enterpriseTestsSetup) docker-compose down displayName: Stop test network and machines env: DOTNET_RUNTIME_REPO_ROOT: $(Build.SourcesDirectory) - task: PublishTestResults@2 inputs: testRunner: 'xUnit' testResultsFiles: '**/testResults.xml' testRunTitle: 'Enterprise Tests' mergeTestResults: true failTaskOnFailedTests: true
1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/Common/tests/System/Net/EnterpriseTests/setup/docker-compose.yml
version: "3.7" services: kdc: build: context: ./ dockerfile: ./kdc/Dockerfile image: kdc:latest container_name: kdc hostname: kdc domainname: linux.contoso.com dns_search: linux.contoso.com volumes: - shared-volume:/SHARED networks: - network1 apacheweb: build: context: ./ dockerfile: ./apacheweb/Dockerfile image: apacheweb:latest container_name: apacheweb hostname: apacheweb domainname: linux.contoso.com dns_search: linux.contoso.com privileged: true command: "-DNTLM" volumes: - shared-volume:/SHARED networks: network1: aliases: - apache.linux.contoso.com depends_on: - kdc altweb: image: apacheweb:latest container_name: altweb hostname: altweb domainname: linux.contoso.com dns_search: linux.contoso.com command: "-DALTPORT -DALTSPN" volumes: - shared-volume:/SHARED networks: network1: aliases: - altweb.linux.contoso.com depends_on: - kdc linuxclient: build: context: ./ dockerfile: ./linuxclient/Dockerfile image: linuxclient:latest container_name: linuxclient hostname: linuxclient domainname: linux.contoso.com dns_search: linux.contoso.com volumes: - shared-volume:/SHARED - ${DOTNET_RUNTIME_REPO_ROOT}:/repo networks: - network1 depends_on: - apacheweb - altweb - kdc networks: network1: name: linux.contoso.com volumes: shared-volume:
version: "3.7" services: kdc: build: context: ./ dockerfile: ./kdc/Dockerfile image: kdc:latest container_name: kdc hostname: kdc domainname: linux.contoso.com dns_search: linux.contoso.com volumes: - shared-volume:/SHARED networks: - network1 apacheweb: build: context: ./ dockerfile: ./apacheweb/Dockerfile image: apacheweb:latest container_name: apacheweb hostname: apacheweb domainname: linux.contoso.com dns_search: linux.contoso.com privileged: true command: "-DNTLM" volumes: - shared-volume:/SHARED networks: network1: aliases: - apache.linux.contoso.com depends_on: - kdc altweb: image: apacheweb:latest container_name: altweb hostname: altweb domainname: linux.contoso.com dns_search: linux.contoso.com command: "-DALTPORT -DALTSPN" volumes: - shared-volume:/SHARED networks: network1: aliases: - altweb.linux.contoso.com depends_on: - kdc linuxclient: build: context: ./ dockerfile: ./linuxclient/Dockerfile image: linuxclient:latest container_name: linuxclient hostname: linuxclient domainname: linux.contoso.com dns_search: linux.contoso.com privileged: true dns: - 8.8.8.8 volumes: - shared-volume:/SHARED - ${DOTNET_RUNTIME_REPO_ROOT}:/repo networks: - network1 depends_on: - apacheweb - altweb - kdc networks: network1: name: linux.contoso.com volumes: shared-volume:
1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/Common/tests/System/Net/EnterpriseTests/setup/linuxclient/test-webserver.sh
#!/usr/bin/env bash kdestroy echo password | kinit user1 curl --verbose --negotiate -u: http://apacheweb.linux.contoso.com kdestroy
#!/usr/bin/env bash kdestroy echo password | kinit user1 curl --verbose --negotiate -u: http://apacheweb.linux.contoso.com kdestroy nslookup github.com
1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/pipelines/libraries/build-job.yml
parameters: buildConfig: '' osGroup: '' osSubgroup: '' archType: '' targetRid: '' crossBuild: false crossrootfsDir: '' framework: 'net7.0' isOfficialBuild: false isOfficialAllConfigurations: false runtimeVariant: '' platform: '' # When set to a non-empty value (Debug / Release), it determines the runtime's # build configuration to use for building libraries and tests. Setting this # property implies a dependency of this job on the appropriate runtime build # and is used to construct the name of the Azure artifact representing # runtime build to use for building the libraries and library tests. liveRuntimeBuildConfig: '' runtimeFlavor: 'coreclr' timeoutInMinutes: 150 preBuildSteps: [] container: '' condition: true dependOnEvaluatePaths: false shouldContinueOnError: false variables: {} pool: '' # Run tests as part of the build job (instead of running them in a separate job) runTests: false # Package up the test builds so they can be sent to Helix useHelix: true testScope: '' jobs: - template: /eng/pipelines/libraries/base-job.yml parameters: buildConfig: ${{ parameters.buildConfig }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} archType: ${{ parameters.archType }} crossBuild: ${{ parameters.crossBuild }} crossrootfsDir: ${{ parameters.crossrootfsDir }} framework: ${{ parameters.framework }} isOfficialBuild: ${{ parameters.isOfficialBuild }} isOfficialAllConfigurations: ${{ parameters.isOfficialAllConfigurations }} liveRuntimeBuildConfig: ${{ parameters.liveRuntimeBuildConfig }} runtimeFlavor: ${{ parameters.runtimeFlavor }} runTests: ${{ parameters.runTests }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} preBuildSteps: ${{ parameters.preBuildSteps }} container: ${{ parameters.container }} condition: ${{ parameters.condition }} dependOnEvaluatePaths: ${{ parameters.dependOnEvaluatePaths }} pool: ${{ parameters.pool }} runtimeVariant: ${{ parameters.runtimeVariant }} testScope: ${{ parameters.testScope }} name: build displayName: 'Build' ${{ if and(ne(parameters.liveRuntimeBuildConfig, ''), eq(parameters.runTests, true)) }}: dependsOn: # Use full product dependency for test runs - ${{ format('{0}_{1}_product_build_{2}{3}_{4}_{5}', parameters.runtimeFlavor, parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveRuntimeBuildConfig) }} variables: - librariesTestsArtifactName: ${{ format('libraries_test_assets_{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - _subset: libs+libs.tests - ${{ if and(eq(parameters.runTests, false), eq(parameters.useHelix, false)) }}: - _subset: libs - _buildAction: '' - _additionalBuildArguments: '' - ${{ parameters.variables }} # Tests only run for 'allConfiguration' and 'net48' build-jobs # Only pass -test for when we aren't running tests using Helix. - ${{ if and(eq(parameters.runTests, true), eq(parameters.useHelix, false)) }}: - _buildAction: -restore -build -test - ${{ if eq(parameters.useHelix, true) }}: - _additionalBuildArguments: /p:ArchiveTests=true - ${{ parameters.variables }} steps: - ${{ if eq(parameters.isOfficialBuild, true) }}: - template: /eng/pipelines/common/restore-internal-tools.yml - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: $(Build.SourcesDirectory)/eng/install-native-dependencies.sh ${{ parameters.osGroup }} ${{ parameters.archType }} azDO displayName: Install Build Dependencies - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage before Build - script: $(_buildScript) -subset $(_subset) $(_buildAction) $(_buildArguments) $(_additionalBuildArguments) displayName: Restore and Build Product - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage after Build - ${{ if eq(parameters.runTests, false) }}: - template: /eng/pipelines/libraries/prepare-for-bin-publish.yml parameters: isOfficialBuild: ${{ parameters.isOfficialBuild }} - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.ArtifactStagingDirectory)/artifacts includeRootFolder: false archiveType: $(archiveType) archiveExtension: $(archiveExtension) tarCompression: $(tarCompression) artifactName: $(librariesBuildArtifactName) displayName: Build Assets # Upload test assets if we are sending tests to Helix and not running them directly in this job. - ${{ if and(eq(parameters.runTests, false), eq(parameters.useHelix, true)) }}: - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/artifacts/helix includeRootFolder: true archiveType: $(archiveType) archiveExtension: $(archiveExtension) tarCompression: $(tarCompression) artifactName: $(librariesTestsArtifactName) displayName: Test Assets # Save AllConfigurations artifacts using the prepare-signed-artifacts format. The # platform-specific jobs' nupkgs automatically flow through the matching platform-specific # Installer build, but AllConfigurations should only be uploaded once, here. - ${{ if eq(parameters.isOfficialAllConfigurations, true) }}: - template: /eng/pipelines/common/upload-intermediate-artifacts-step.yml parameters: name: Libraries_AllConfigurations publishPackagesCondition: >- or( eq(variables['_librariesBuildProducedPackages'], true), eq(variables['Build.SourceBranchName'], 'main'), eq(variables['System.PullRequest.TargetBranch'], 'main')) - ${{ if and(eq(parameters.runTests, true), eq(parameters.useHelix, true)) }}: - template: /eng/pipelines/libraries/helix.yml parameters: osGroup: ${{ parameters.osGroup }} targetRid: ${{ parameters.targetRid }} archType: ${{ parameters.archType }} buildConfig: ${{ parameters.buildConfig }} helixQueues: ${{ parameters.helixQueues }} testScope: ${{ parameters.testScope }} shouldContinueOnError: ${{ parameters.shouldContinueOnError }} creator: dotnet-bot testRunNamePrefixSuffix: $(_testRunNamePrefixSuffix) extraHelixArguments: $(_extraHelixArguments)
parameters: buildConfig: '' osGroup: '' osSubgroup: '' archType: '' targetRid: '' crossBuild: false crossrootfsDir: '' framework: 'net7.0' isOfficialBuild: false isOfficialAllConfigurations: false runtimeVariant: '' platform: '' # When set to a non-empty value (Debug / Release), it determines the runtime's # build configuration to use for building libraries and tests. Setting this # property implies a dependency of this job on the appropriate runtime build # and is used to construct the name of the Azure artifact representing # runtime build to use for building the libraries and library tests. liveRuntimeBuildConfig: '' runtimeFlavor: 'coreclr' timeoutInMinutes: 150 preBuildSteps: [] container: '' condition: true dependOnEvaluatePaths: false shouldContinueOnError: false variables: {} pool: '' # Run tests as part of the build job (instead of running them in a separate job) runTests: false # Package up the test builds so they can be sent to Helix useHelix: true testScope: '' jobs: - template: /eng/pipelines/libraries/base-job.yml parameters: buildConfig: ${{ parameters.buildConfig }} osGroup: ${{ parameters.osGroup }} osSubgroup: ${{ parameters.osSubgroup }} archType: ${{ parameters.archType }} crossBuild: ${{ parameters.crossBuild }} crossrootfsDir: ${{ parameters.crossrootfsDir }} framework: ${{ parameters.framework }} isOfficialBuild: ${{ parameters.isOfficialBuild }} isOfficialAllConfigurations: ${{ parameters.isOfficialAllConfigurations }} liveRuntimeBuildConfig: ${{ parameters.liveRuntimeBuildConfig }} runtimeFlavor: ${{ parameters.runtimeFlavor }} runTests: ${{ parameters.runTests }} timeoutInMinutes: ${{ parameters.timeoutInMinutes }} preBuildSteps: ${{ parameters.preBuildSteps }} container: ${{ parameters.container }} condition: ${{ parameters.condition }} dependOnEvaluatePaths: ${{ parameters.dependOnEvaluatePaths }} pool: ${{ parameters.pool }} runtimeVariant: ${{ parameters.runtimeVariant }} testScope: ${{ parameters.testScope }} name: build displayName: 'Build' ${{ if and(ne(parameters.liveRuntimeBuildConfig, ''), eq(parameters.runTests, true)) }}: dependsOn: # Use full product dependency for test runs - ${{ format('{0}_{1}_product_build_{2}{3}_{4}_{5}', parameters.runtimeFlavor, parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveRuntimeBuildConfig) }} variables: - librariesTestsArtifactName: ${{ format('libraries_test_assets_{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - _subset: libs+libs.tests - ${{ if and(eq(parameters.runTests, false), eq(parameters.useHelix, false)) }}: - _subset: libs - _buildAction: '' - _additionalBuildArguments: '' - ${{ parameters.variables }} # Tests only run for 'allConfiguration' and 'net48' build-jobs # Only pass -test for when we aren't running tests using Helix. - ${{ if and(eq(parameters.runTests, true), eq(parameters.useHelix, false)) }}: - _buildAction: -restore -build -test - ${{ if eq(parameters.useHelix, true) }}: - _additionalBuildArguments: /p:ArchiveTests=true - ${{ parameters.variables }} steps: - ${{ if eq(parameters.isOfficialBuild, true) }}: - template: /eng/pipelines/common/restore-internal-tools.yml - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: $(Build.SourcesDirectory)/eng/install-native-dependencies.sh ${{ parameters.osGroup }} ${{ parameters.archType }} azDO displayName: Install Build Dependencies - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage before Build - script: $(_buildScript) -subset $(_subset) $(_buildAction) $(_buildArguments) $(_additionalBuildArguments) displayName: Restore and Build Product - ${{ if in(parameters.osGroup, 'OSX', 'iOS', 'tvOS') }}: - script: | du -sh $(Build.SourcesDirectory)/* df -h displayName: Disk Usage after Build - ${{ if eq(parameters.runTests, false) }}: - template: /eng/pipelines/libraries/prepare-for-bin-publish.yml parameters: isOfficialBuild: ${{ parameters.isOfficialBuild }} - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.ArtifactStagingDirectory)/artifacts includeRootFolder: false archiveType: $(archiveType) archiveExtension: $(archiveExtension) tarCompression: $(tarCompression) artifactName: $(librariesBuildArtifactName) displayName: Build Assets # Upload test assets if we are sending tests to Helix and not running them directly in this job. - ${{ if and(eq(parameters.runTests, false), eq(parameters.useHelix, true)) }}: - template: /eng/pipelines/common/upload-artifact-step.yml parameters: rootFolder: $(Build.SourcesDirectory)/artifacts/helix includeRootFolder: true archiveType: $(archiveType) archiveExtension: $(archiveExtension) tarCompression: $(tarCompression) artifactName: $(librariesTestsArtifactName) displayName: Test Assets # Save AllConfigurations artifacts using the prepare-signed-artifacts format. The # platform-specific jobs' nupkgs automatically flow through the matching platform-specific # Installer build, but AllConfigurations should only be uploaded once, here. - ${{ if eq(parameters.isOfficialAllConfigurations, true) }}: - template: /eng/pipelines/common/upload-intermediate-artifacts-step.yml parameters: name: Libraries_AllConfigurations publishPackagesCondition: >- or( eq(variables['_librariesBuildProducedPackages'], true), eq(variables['Build.SourceBranchName'], 'main'), eq(variables['System.PullRequest.TargetBranch'], 'main')) - ${{ if and(eq(parameters.runTests, true), eq(parameters.useHelix, true)) }}: - template: /eng/pipelines/libraries/helix.yml parameters: osGroup: ${{ parameters.osGroup }} targetRid: ${{ parameters.targetRid }} archType: ${{ parameters.archType }} buildConfig: ${{ parameters.buildConfig }} helixQueues: ${{ parameters.helixQueues }} testScope: ${{ parameters.testScope }} shouldContinueOnError: ${{ parameters.shouldContinueOnError }} creator: dotnet-bot testRunNamePrefixSuffix: $(_testRunNamePrefixSuffix) extraHelixArguments: $(_extraHelixArguments)
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/common/native/install-cmake.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/tests/Common/scripts/arm32_ci_test.sh
#!/usr/bin/env bash set -x function usage { echo 'ARM Test Script' echo '$ ./tests/scripts/arm32_ci_test.sh' echo ' --abi=arm' echo ' --buildConfig=Release' echo 'Required Arguments:' echo ' --abi=<abi> : arm (default) or armel' echo ' --buildConfig=<config> : Release (default) Checked, or Debug' } # Display error message and exit function exit_with_error { set +x local errorMessage="$1" local printUsage=$2 echo "ERROR: $errorMessage" if [[ "$printUsage" == "true" ]]; then echo '' usage fi exit 1 } # Exit if the input path does not exist function exit_if_path_absent { local path="$1" local errorMessage="$2" local printUsage=$3 if [ ! -f "$path" -a ! -d "$path" ]; then exit_with_error "$errorMessage" $printUsage fi } __abi="arm" __buildConfig="Release" # Parse command line arguments for arg in "$@" do case $arg in --abi=*) __abi=${arg#*=} if [[ "$__abi" != "arm" && "$__abi" != "armel" ]]; then exit_with_error "--abi can be either arm or armel" true fi ;; --buildConfig=*) __buildConfig=${arg#*=} if [[ "$__buildConfig" != "Debug" && "$__buildConfig" != "Release" && "$__buildConfig" != "Checked" ]]; then exit_with_error "--buildConfig can be Debug, Checked or Release" true fi ;; -v|--verbose) __verboseFlag="verbose" ;; -h|--help) usage exit 0 ;; *) exit_with_error "$arg not a recognized argument" true ;; esac done __buildDirName="Linux.${__abi}.${__buildConfig}" CORECLR_DIR=/opt/code ARM_CHROOT_HOME_DIR=/home/coreclr if [ -z "${ROOTFS_DIR}" ]; then __ROOTFS_DIR=${CORECLR_DIR}/eng/common/cross/rootfs/${__abi} else __ROOTFS_DIR=${ROOTFS_DIR} fi if [[ "$__abi" == "armel" ]]; then # Prepare armel emulation environment pushd ${CORECLR_DIR}/eng/common/cross/armel/tizen apt-get update apt-get -y -qq --force-yes --reinstall install qemu binfmt-support qemu-user-static __qemuARM=$(which qemu-arm-static) cp $__qemuARM ${__ROOTFS_DIR}/usr/bin/ popd fi # Mount mkdir -p ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR} mount -t proc /proc ${__ROOTFS_DIR}/proc mount -o bind /dev ${__ROOTFS_DIR}/dev mount -o bind /dev/pts ${__ROOTFS_DIR}/dev/pts mount -o bind /sys ${__ROOTFS_DIR}/sys mount -o bind ${CORECLR_DIR} ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR} # Test environment emulation using docker and qemu has some problem to use lttng library. # We should remove libcoreclrtraceptprovider.so to avoid test hang. rm -f -v ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR}/bin/bin/coreclr/${__buildDirName}/libcoreclrtraceptprovider.so rm -f -v ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR}/bin/CoreFxBinDir/libcoreclrtraceptprovider.so chroot ${__ROOTFS_DIR} /bin/bash -x <<EOF cd ${ARM_CHROOT_HOME_DIR} ./bringup_runtest.sh --sequential\ --coreClrBinDir=${ARM_CHROOT_HOME_DIR}/artifacts/bin/coreclr/${__buildDirName} \ --mscorlibDir=${ARM_CHROOT_HOME_DIR}/artifacts/bin/coreclr/${__buildDirName} \ --testNativeBinDir=${ARM_CHROOT_HOME_DIR}/artifacts/obj/coreclr/${__buildDirName}/tests \ --coreFxBinDir=${ARM_CHROOT_HOME_DIR}/bin/CoreFxBinDir \ --testRootDir=${ARM_CHROOT_HOME_DIR}/bin/tests/windows.x64.${__buildConfig} \ --testDirFile=${ARM_CHROOT_HOME_DIR}/tests/testsRunningInsideARM.txt EOF
#!/usr/bin/env bash set -x function usage { echo 'ARM Test Script' echo '$ ./tests/scripts/arm32_ci_test.sh' echo ' --abi=arm' echo ' --buildConfig=Release' echo 'Required Arguments:' echo ' --abi=<abi> : arm (default) or armel' echo ' --buildConfig=<config> : Release (default) Checked, or Debug' } # Display error message and exit function exit_with_error { set +x local errorMessage="$1" local printUsage=$2 echo "ERROR: $errorMessage" if [[ "$printUsage" == "true" ]]; then echo '' usage fi exit 1 } # Exit if the input path does not exist function exit_if_path_absent { local path="$1" local errorMessage="$2" local printUsage=$3 if [ ! -f "$path" -a ! -d "$path" ]; then exit_with_error "$errorMessage" $printUsage fi } __abi="arm" __buildConfig="Release" # Parse command line arguments for arg in "$@" do case $arg in --abi=*) __abi=${arg#*=} if [[ "$__abi" != "arm" && "$__abi" != "armel" ]]; then exit_with_error "--abi can be either arm or armel" true fi ;; --buildConfig=*) __buildConfig=${arg#*=} if [[ "$__buildConfig" != "Debug" && "$__buildConfig" != "Release" && "$__buildConfig" != "Checked" ]]; then exit_with_error "--buildConfig can be Debug, Checked or Release" true fi ;; -v|--verbose) __verboseFlag="verbose" ;; -h|--help) usage exit 0 ;; *) exit_with_error "$arg not a recognized argument" true ;; esac done __buildDirName="Linux.${__abi}.${__buildConfig}" CORECLR_DIR=/opt/code ARM_CHROOT_HOME_DIR=/home/coreclr if [ -z "${ROOTFS_DIR}" ]; then __ROOTFS_DIR=${CORECLR_DIR}/eng/common/cross/rootfs/${__abi} else __ROOTFS_DIR=${ROOTFS_DIR} fi if [[ "$__abi" == "armel" ]]; then # Prepare armel emulation environment pushd ${CORECLR_DIR}/eng/common/cross/armel/tizen apt-get update apt-get -y -qq --force-yes --reinstall install qemu binfmt-support qemu-user-static __qemuARM=$(which qemu-arm-static) cp $__qemuARM ${__ROOTFS_DIR}/usr/bin/ popd fi # Mount mkdir -p ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR} mount -t proc /proc ${__ROOTFS_DIR}/proc mount -o bind /dev ${__ROOTFS_DIR}/dev mount -o bind /dev/pts ${__ROOTFS_DIR}/dev/pts mount -o bind /sys ${__ROOTFS_DIR}/sys mount -o bind ${CORECLR_DIR} ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR} # Test environment emulation using docker and qemu has some problem to use lttng library. # We should remove libcoreclrtraceptprovider.so to avoid test hang. rm -f -v ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR}/bin/bin/coreclr/${__buildDirName}/libcoreclrtraceptprovider.so rm -f -v ${__ROOTFS_DIR}${ARM_CHROOT_HOME_DIR}/bin/CoreFxBinDir/libcoreclrtraceptprovider.so chroot ${__ROOTFS_DIR} /bin/bash -x <<EOF cd ${ARM_CHROOT_HOME_DIR} ./bringup_runtest.sh --sequential\ --coreClrBinDir=${ARM_CHROOT_HOME_DIR}/artifacts/bin/coreclr/${__buildDirName} \ --mscorlibDir=${ARM_CHROOT_HOME_DIR}/artifacts/bin/coreclr/${__buildDirName} \ --testNativeBinDir=${ARM_CHROOT_HOME_DIR}/artifacts/obj/coreclr/${__buildDirName}/tests \ --coreFxBinDir=${ARM_CHROOT_HOME_DIR}/bin/CoreFxBinDir \ --testRootDir=${ARM_CHROOT_HOME_DIR}/bin/tests/windows.x64.${__buildConfig} \ --testDirFile=${ARM_CHROOT_HOME_DIR}/tests/testsRunningInsideARM.txt EOF
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/mono/mono/tests/verifier/make_unbox_any_test.sh
#! /bin/sh SED="sed" if [ `which gsed 2> /dev/null` ]; then SED="gsed" fi TEST_NAME=$1 TEST_VALIDITY=$2 TEST_TYPE1=$3 TEST_TYPE2=$4 TEST_POST_OP=$5 TEST_INIT=$6 TEST_FILE=`echo ${TEST_VALIDITY}_${TEST_NAME} | $SED -e 's/ /_/g' -e 's/\./_/g' -e 's/&/mp/g' -e 's/\[/_/g' -e 's/\]/_/g'`_generated.il echo $TEST_FILE $SED -e "s/INIT_OP/${TEST_INIT}/g" -e "s/TYPE1/${TEST_TYPE1}/g" -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/TYPE2/${TEST_TYPE2}/g" -e "s/POST_OP/${TEST_POST_OP}/g"> $TEST_FILE <<//EOF .assembly extern mscorlib { .ver 2:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. } .assembly 'ldobj_test' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .module ldobj.exe .class Class extends [mscorlib]System.Object { .field public int32 valid } .class public Template\`1<T> extends [mscorlib]System.Object { } .class sealed public StructTemplate\`1<T> extends [mscorlib]System.ValueType { .field public !0 t } .class sealed public StructTemplate2\`1<T> extends [mscorlib]System.ValueType { .field public !0 t } .class public auto ansi sealed MyStruct extends [mscorlib]System.ValueType { .field public int32 foo } .class public auto ansi sealed MyEnum extends [mscorlib]System.Enum { .field public specialname rtspecialname int32 value__ .field public static literal valuetype MyEnum B = int32(0x00000000) .field public static literal valuetype MyEnum C = int32(0x00000001) } .method public static int32 Main () { .entrypoint .maxstack 8 .locals init (TYPE1 V_0, TYPE2 V_1) .try { INIT_OP stloc.0 ldloc.0 unbox.any TYPE2 // VALIDITY POST_OP leave END } catch [mscorlib]System.NullReferenceException { pop leave END } END: ldc.i4.0 ret } //EOF
#! /bin/sh SED="sed" if [ `which gsed 2> /dev/null` ]; then SED="gsed" fi TEST_NAME=$1 TEST_VALIDITY=$2 TEST_TYPE1=$3 TEST_TYPE2=$4 TEST_POST_OP=$5 TEST_INIT=$6 TEST_FILE=`echo ${TEST_VALIDITY}_${TEST_NAME} | $SED -e 's/ /_/g' -e 's/\./_/g' -e 's/&/mp/g' -e 's/\[/_/g' -e 's/\]/_/g'`_generated.il echo $TEST_FILE $SED -e "s/INIT_OP/${TEST_INIT}/g" -e "s/TYPE1/${TEST_TYPE1}/g" -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/TYPE2/${TEST_TYPE2}/g" -e "s/POST_OP/${TEST_POST_OP}/g"> $TEST_FILE <<//EOF .assembly extern mscorlib { .ver 2:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. } .assembly 'ldobj_test' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .module ldobj.exe .class Class extends [mscorlib]System.Object { .field public int32 valid } .class public Template\`1<T> extends [mscorlib]System.Object { } .class sealed public StructTemplate\`1<T> extends [mscorlib]System.ValueType { .field public !0 t } .class sealed public StructTemplate2\`1<T> extends [mscorlib]System.ValueType { .field public !0 t } .class public auto ansi sealed MyStruct extends [mscorlib]System.ValueType { .field public int32 foo } .class public auto ansi sealed MyEnum extends [mscorlib]System.Enum { .field public specialname rtspecialname int32 value__ .field public static literal valuetype MyEnum B = int32(0x00000000) .field public static literal valuetype MyEnum C = int32(0x00000001) } .method public static int32 Main () { .entrypoint .maxstack 8 .locals init (TYPE1 V_0, TYPE2 V_1) .try { INIT_OP stloc.0 ldloc.0 unbox.any TYPE2 // VALIDITY POST_OP leave END } catch [mscorlib]System.NullReferenceException { pop leave END } END: ldc.i4.0 ret } //EOF
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/common/templates/job/publish-build-assets.yml
parameters: configuration: 'Debug' # Optional: condition for the job to run condition: '' # Optional: 'true' if future jobs should run even if this job fails continueOnError: false # Optional: dependencies of the job dependsOn: '' # Optional: Include PublishBuildArtifacts task enablePublishBuildArtifacts: false # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool pool: {} # Optional: should run as a public build even in the internal project # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. runAsPublic: false # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing publishUsingPipelines: false jobs: - job: Asset_Registry_Publish dependsOn: ${{ parameters.dependsOn }} displayName: Publish to Build Asset Registry pool: ${{ parameters.pool }} variables: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - name: _BuildConfig value: ${{ parameters.configuration }} - group: Publish-Build-Assets - group: AzureDevOps-Artifact-Feeds-Pats - name: runCodesignValidationInjection value: false steps: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: DownloadBuildArtifacts@0 displayName: Download artifact inputs: artifactName: AssetManifests downloadPath: '$(Build.StagingDirectory)/Download' checkDownloadedFiles: true condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: NuGetAuthenticate@0 - task: PowerShell@2 displayName: Enable cross-org NuGet feed authentication inputs: filePath: $(Build.SourcesDirectory)/eng/common/enable-cross-org-publishing.ps1 arguments: -token $(dn-bot-all-orgs-artifact-feeds-rw) - task: PowerShell@2 displayName: Publish Build Assets inputs: filePath: eng\common\sdk-task.ps1 arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' /p:BuildAssetRegistryToken=$(MaestroAccessToken) /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} /p:Configuration=$(_BuildConfig) /p:OfficialBuildId=$(Build.BuildNumber) condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - task: powershell@2 displayName: Create ReleaseConfigs Artifact inputs: targetType: inline script: | Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value $(BARBuildId) Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value "$(DefaultChannels)" Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value $(IsStableBuild) - task: PublishBuildArtifacts@1 displayName: Publish ReleaseConfigs Artifact inputs: PathtoPublish: '$(Build.StagingDirectory)/ReleaseConfigs.txt' PublishLocation: Container ArtifactName: ReleaseConfigs - task: powershell@2 displayName: Check if SymbolPublishingExclusionsFile.txt exists inputs: targetType: inline script: | $symbolExclusionfile = "$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt" if(Test-Path -Path $symbolExclusionfile) { Write-Host "SymbolExclusionFile exists" Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]true" } else{ Write-Host "Symbols Exclusion file does not exists" Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]false" } - task: PublishBuildArtifacts@1 displayName: Publish SymbolPublishingExclusionsFile Artifact condition: eq(variables['SymbolExclusionFile'], 'true') inputs: PathtoPublish: '$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' PublishLocation: Container ArtifactName: ReleaseConfigs - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: - template: /eng/common/templates/steps/publish-logs.yml parameters: JobLabel: 'Publish_Artifacts_Logs'
parameters: configuration: 'Debug' # Optional: condition for the job to run condition: '' # Optional: 'true' if future jobs should run even if this job fails continueOnError: false # Optional: dependencies of the job dependsOn: '' # Optional: Include PublishBuildArtifacts task enablePublishBuildArtifacts: false # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool pool: {} # Optional: should run as a public build even in the internal project # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. runAsPublic: false # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing publishUsingPipelines: false jobs: - job: Asset_Registry_Publish dependsOn: ${{ parameters.dependsOn }} displayName: Publish to Build Asset Registry pool: ${{ parameters.pool }} variables: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - name: _BuildConfig value: ${{ parameters.configuration }} - group: Publish-Build-Assets - group: AzureDevOps-Artifact-Feeds-Pats - name: runCodesignValidationInjection value: false steps: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: DownloadBuildArtifacts@0 displayName: Download artifact inputs: artifactName: AssetManifests downloadPath: '$(Build.StagingDirectory)/Download' checkDownloadedFiles: true condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: NuGetAuthenticate@0 - task: PowerShell@2 displayName: Enable cross-org NuGet feed authentication inputs: filePath: $(Build.SourcesDirectory)/eng/common/enable-cross-org-publishing.ps1 arguments: -token $(dn-bot-all-orgs-artifact-feeds-rw) - task: PowerShell@2 displayName: Publish Build Assets inputs: filePath: eng\common\sdk-task.ps1 arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' /p:BuildAssetRegistryToken=$(MaestroAccessToken) /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} /p:Configuration=$(_BuildConfig) /p:OfficialBuildId=$(Build.BuildNumber) condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - task: powershell@2 displayName: Create ReleaseConfigs Artifact inputs: targetType: inline script: | Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value $(BARBuildId) Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value "$(DefaultChannels)" Add-Content -Path "$(Build.StagingDirectory)/ReleaseConfigs.txt" -Value $(IsStableBuild) - task: PublishBuildArtifacts@1 displayName: Publish ReleaseConfigs Artifact inputs: PathtoPublish: '$(Build.StagingDirectory)/ReleaseConfigs.txt' PublishLocation: Container ArtifactName: ReleaseConfigs - task: powershell@2 displayName: Check if SymbolPublishingExclusionsFile.txt exists inputs: targetType: inline script: | $symbolExclusionfile = "$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt" if(Test-Path -Path $symbolExclusionfile) { Write-Host "SymbolExclusionFile exists" Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]true" } else{ Write-Host "Symbols Exclusion file does not exists" Write-Host "##vso[task.setvariable variable=SymbolExclusionFile]false" } - task: PublishBuildArtifacts@1 displayName: Publish SymbolPublishingExclusionsFile Artifact condition: eq(variables['SymbolExclusionFile'], 'true') inputs: PathtoPublish: '$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' PublishLocation: Container ArtifactName: ReleaseConfigs - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: - template: /eng/common/templates/steps/publish-logs.yml parameters: JobLabel: 'Publish_Artifacts_Logs'
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/native/external/brotli/fuzz/test_fuzzer.sh
#!/usr/bin/env bash set -e export CC=${CC:-cc} BROTLI="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )" SRC=$BROTLI/c cd $BROTLI rm -rf bin mkdir bin cd bin cmake $BROTLI -DCMAKE_C_COMPILER="$CC" \ -DBUILD_TESTING=OFF -DENABLE_SANITIZER=address make -j$(nproc) brotlidec-static ${CC} -o run_decode_fuzzer -std=c99 -fsanitize=address -I$SRC/include \ $SRC/fuzz/decode_fuzzer.c $SRC/fuzz/run_decode_fuzzer.c \ ./libbrotlidec-static.a ./libbrotlicommon-static.a mkdir decode_corpora unzip $BROTLI/java/org/brotli/integration/fuzz_data.zip -d decode_corpora for f in `ls decode_corpora` do echo "Testing $f" ./run_decode_fuzzer decode_corpora/$f done cd $BROTLI rm -rf bin
#!/usr/bin/env bash set -e export CC=${CC:-cc} BROTLI="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )" SRC=$BROTLI/c cd $BROTLI rm -rf bin mkdir bin cd bin cmake $BROTLI -DCMAKE_C_COMPILER="$CC" \ -DBUILD_TESTING=OFF -DENABLE_SANITIZER=address make -j$(nproc) brotlidec-static ${CC} -o run_decode_fuzzer -std=c99 -fsanitize=address -I$SRC/include \ $SRC/fuzz/decode_fuzzer.c $SRC/fuzz/run_decode_fuzzer.c \ ./libbrotlidec-static.a ./libbrotlicommon-static.a mkdir decode_corpora unzip $BROTLI/java/org/brotli/integration/fuzz_data.zip -d decode_corpora for f in `ls decode_corpora` do echo "Testing $f" ./run_decode_fuzzer decode_corpora/$f done cd $BROTLI rm -rf bin
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/pipelines/libraries/stress/ssl.yml
trigger: none pr: branches: include: - "*" schedules: - cron: "0 13 * * *" # 1PM UTC => 5 AM PST displayName: SslStress nightly run branches: include: - main - release/6.0 variables: - template: ../variables.yml - name: dockerfilesFolder value: $(Build.SourcesDirectory)/eng/docker - name: sslStressProject value: $(sourcesRoot)/System.Net.Security/tests/StressTests/SslStress - name: sdkBaseImage value: dotnet-sdk-libraries-current jobs: - job: linux displayName: Docker Linux timeoutInMinutes: 120 pool: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open steps: - checkout: self clean: true fetchDepth: 5 - bash: | $(dockerfilesFolder)/build-docker-sdk.sh -t $(sdkBaseImage) -c $(BUILD_CONFIGURATION) displayName: Build CLR and Libraries - bash: | $(sslStressProject)/run-docker-compose.sh -o -c $(BUILD_CONFIGURATION) -t $(sdkBaseImage) displayName: Build SslStress - bash: | cd '$(sslStressProject)' docker-compose up --abort-on-container-exit --no-color displayName: Run SslStress - job: windows displayName: Docker NanoServer timeoutInMinutes: 120 pool: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Server.Amd64.VS2019.Open steps: - checkout: self clean: true fetchDepth: 5 lfs: false - powershell: | $(dockerfilesFolder)/build-docker-sdk.ps1 -w -t $(sdkBaseImage) -c $(BUILD_CONFIGURATION) displayName: Build CLR and Libraries - powershell: | $(sslStressProject)/run-docker-compose.ps1 -w -o -c $(BUILD_CONFIGURATION) -t $(sdkBaseImage) displayName: Build SslStress - powershell: | cd '$(sslStressProject)' docker-compose up --abort-on-container-exit --no-color displayName: Run SslStress
trigger: none pr: branches: include: - "*" schedules: - cron: "0 13 * * *" # 1PM UTC => 5 AM PST displayName: SslStress nightly run branches: include: - main - release/6.0 variables: - template: ../variables.yml - name: dockerfilesFolder value: $(Build.SourcesDirectory)/eng/docker - name: sslStressProject value: $(sourcesRoot)/System.Net.Security/tests/StressTests/SslStress - name: sdkBaseImage value: dotnet-sdk-libraries-current jobs: - job: linux displayName: Docker Linux timeoutInMinutes: 120 pool: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open steps: - checkout: self clean: true fetchDepth: 5 - bash: | $(dockerfilesFolder)/build-docker-sdk.sh -t $(sdkBaseImage) -c $(BUILD_CONFIGURATION) displayName: Build CLR and Libraries - bash: | $(sslStressProject)/run-docker-compose.sh -o -c $(BUILD_CONFIGURATION) -t $(sdkBaseImage) displayName: Build SslStress - bash: | cd '$(sslStressProject)' docker-compose up --abort-on-container-exit --no-color displayName: Run SslStress - job: windows displayName: Docker NanoServer timeoutInMinutes: 120 pool: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Server.Amd64.VS2019.Open steps: - checkout: self clean: true fetchDepth: 5 lfs: false - powershell: | $(dockerfilesFolder)/build-docker-sdk.ps1 -w -t $(sdkBaseImage) -c $(BUILD_CONFIGURATION) displayName: Build CLR and Libraries - powershell: | $(sslStressProject)/run-docker-compose.ps1 -w -o -c $(BUILD_CONFIGURATION) -t $(sdkBaseImage) displayName: Build SslStress - powershell: | cd '$(sslStressProject)' docker-compose up --abort-on-container-exit --no-color displayName: Run SslStress
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/native/generateexportedsymbols.sh
#!/usr/bin/env bash saved=("$@") while test $# -gt 0; do case "$1" in --help|-h) printf "Usage:\ngenerateexportedsymbols.sh <filename>\n" exit 1;; esac shift done set -- "${saved[@]}" while read -r line; do # Skip empty lines and comment lines starting with semicolon if [[ "$line" =~ ^\;.*$|^[[:space:]]*$ ]]; then continue fi # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings line="${line//$'\r'/}" printf "_%s\n" "${line//#/}" done < "$1"
#!/usr/bin/env bash saved=("$@") while test $# -gt 0; do case "$1" in --help|-h) printf "Usage:\ngenerateexportedsymbols.sh <filename>\n" exit 1;; esac shift done set -- "${saved[@]}" while read -r line; do # Skip empty lines and comment lines starting with semicolon if [[ "$line" =~ ^\;.*$|^[[:space:]]*$ ]]; then continue fi # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings line="${line//$'\r'/}" printf "_%s\n" "${line//#/}" done < "$1"
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/pipelines/common/templates/runtimes/send-to-helix-step.yml
parameters: displayName: '' condition: true archType: '' osGroup: '' osSubgroup: '' buildConfig: '' creator: '' publishTestResults: '' helixAccessToken: '' helixBuild: '' helixSource: '' helixQueues: '' helixType: '' scenarios: '' timeoutPerTestCollectionInMinutes: '' timeoutPerTestInMinutes: '' runCrossGen: '' runCrossGen2: '' runPALTestsDir: '' compositeBuildMode: false helixProjectArguments: '' runInUnloadableContext: '' tieringTest: '' longRunningGcTests: '' gcSimulatorTests: '' runtimeFlavorDisplayName: 'CoreCLR' runtimeVariant: '' shouldContinueOnError: false steps: - template: send-to-helix-inner-step.yml parameters: osGroup: ${{ parameters.osGroup }} restoreParams: /p:DotNetPublishToBlobFeed=true -restore -projects $(Build.SourcesDirectory)$(dir)eng$(dir)empty.csproj sendParams: ${{ parameters.helixProjectArguments }} /maxcpucount /bl:$(Build.SourcesDirectory)/artifacts/log/SendToHelix.binlog /p:TargetArchitecture=${{ parameters.archType }} /p:TargetOS=${{ parameters.osGroup }} /p:TargetOSSubgroup=${{ parameters.osSubgroup }} /p:Configuration=${{ parameters.buildConfig }} condition: and(succeeded(), ${{ parameters.condition }}) shouldContinueOnError: ${{ parameters.shouldContinueOnError }} displayName: ${{ parameters.displayName }} environment: _Creator: ${{ parameters.creator }} _PublishTestResults: ${{ parameters.publishTestResults }} _HelixAccessToken: ${{ parameters.helixAccessToken }} _HelixBuild: ${{ parameters.helixBuild }} _HelixSource: ${{ parameters.helixSource }} _HelixTargetQueues: ${{ join(',', parameters.helixQueues) }} _HelixType: ${{ parameters.helixType }} _RunCrossGen: ${{ parameters.runCrossGen }} _RunCrossGen2: ${{ parameters.runCrossGen2 }} _CompositeBuildMode: ${{ parameters.compositeBuildMode }} _RunInUnloadableContext: ${{ parameters.runInUnloadableContext }} _TieringTest: ${{ parameters.tieringTest }} _LongRunningGcTests: ${{ parameters.longRunningGcTests }} _GcSimulatorTests: ${{ parameters.gcSimulatorTests }} _Scenarios: ${{ join(',', parameters.scenarios) }} _PALTestsDir: ${{ parameters.runPALTestsDir }} _TimeoutPerTestCollectionInMinutes: ${{ parameters.timeoutPerTestCollectionInMinutes }} _TimeoutPerTestInMinutes: ${{ parameters.timeoutPerTestInMinutes }} runtimeFlavorDisplayName: ${{ parameters.runtimeFlavorDisplayName }} _RuntimeVariant: ${{ parameters.runtimeVariant }} ${{ if eq(parameters.publishTestResults, 'true') }}: SYSTEM_ACCESSTOKEN: $(System.AccessToken) # TODO: remove NUGET_PACKAGES once https://github.com/dotnet/arcade/issues/1578 is fixed NUGET_PACKAGES: $(Build.SourcesDirectory)$(dir).packages
parameters: displayName: '' condition: true archType: '' osGroup: '' osSubgroup: '' buildConfig: '' creator: '' publishTestResults: '' helixAccessToken: '' helixBuild: '' helixSource: '' helixQueues: '' helixType: '' scenarios: '' timeoutPerTestCollectionInMinutes: '' timeoutPerTestInMinutes: '' runCrossGen: '' runCrossGen2: '' runPALTestsDir: '' compositeBuildMode: false helixProjectArguments: '' runInUnloadableContext: '' tieringTest: '' longRunningGcTests: '' gcSimulatorTests: '' runtimeFlavorDisplayName: 'CoreCLR' runtimeVariant: '' shouldContinueOnError: false steps: - template: send-to-helix-inner-step.yml parameters: osGroup: ${{ parameters.osGroup }} restoreParams: /p:DotNetPublishToBlobFeed=true -restore -projects $(Build.SourcesDirectory)$(dir)eng$(dir)empty.csproj sendParams: ${{ parameters.helixProjectArguments }} /maxcpucount /bl:$(Build.SourcesDirectory)/artifacts/log/SendToHelix.binlog /p:TargetArchitecture=${{ parameters.archType }} /p:TargetOS=${{ parameters.osGroup }} /p:TargetOSSubgroup=${{ parameters.osSubgroup }} /p:Configuration=${{ parameters.buildConfig }} condition: and(succeeded(), ${{ parameters.condition }}) shouldContinueOnError: ${{ parameters.shouldContinueOnError }} displayName: ${{ parameters.displayName }} environment: _Creator: ${{ parameters.creator }} _PublishTestResults: ${{ parameters.publishTestResults }} _HelixAccessToken: ${{ parameters.helixAccessToken }} _HelixBuild: ${{ parameters.helixBuild }} _HelixSource: ${{ parameters.helixSource }} _HelixTargetQueues: ${{ join(',', parameters.helixQueues) }} _HelixType: ${{ parameters.helixType }} _RunCrossGen: ${{ parameters.runCrossGen }} _RunCrossGen2: ${{ parameters.runCrossGen2 }} _CompositeBuildMode: ${{ parameters.compositeBuildMode }} _RunInUnloadableContext: ${{ parameters.runInUnloadableContext }} _TieringTest: ${{ parameters.tieringTest }} _LongRunningGcTests: ${{ parameters.longRunningGcTests }} _GcSimulatorTests: ${{ parameters.gcSimulatorTests }} _Scenarios: ${{ join(',', parameters.scenarios) }} _PALTestsDir: ${{ parameters.runPALTestsDir }} _TimeoutPerTestCollectionInMinutes: ${{ parameters.timeoutPerTestCollectionInMinutes }} _TimeoutPerTestInMinutes: ${{ parameters.timeoutPerTestInMinutes }} runtimeFlavorDisplayName: ${{ parameters.runtimeFlavorDisplayName }} _RuntimeVariant: ${{ parameters.runtimeVariant }} ${{ if eq(parameters.publishTestResults, 'true') }}: SYSTEM_ACCESSTOKEN: $(System.AccessToken) # TODO: remove NUGET_PACKAGES once https://github.com/dotnet/arcade/issues/1578 is fixed NUGET_PACKAGES: $(Build.SourcesDirectory)$(dir).packages
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/native/generateversionscript.sh
#!/usr/bin/env bash saved=("$@") while test $# -gt 0; do case "$1" in --help|-h) printf "Usage:\ngenerateversionscript.sh <filename> <prefix>\n" exit 1;; esac shift done set -- "${saved[@]}" prefix="$2" printf "V1.0 {\n global:\n" while read -r line; do # Skip empty lines and comment lines starting with semicolon if [[ "$line" =~ ^\;.*$|^[[:space:]]*$ ]]; then continue fi # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings line="${line//$'\r'/}" # Only prefix the entries that start with "#" if [[ "$line" =~ ^#.*$ ]]; then printf " %s%s;\n" "$prefix" "${line//#/}" else printf " %s;\n" "$line" fi done < "$1" printf " local: *;\n};\n"
#!/usr/bin/env bash saved=("$@") while test $# -gt 0; do case "$1" in --help|-h) printf "Usage:\ngenerateversionscript.sh <filename> <prefix>\n" exit 1;; esac shift done set -- "${saved[@]}" prefix="$2" printf "V1.0 {\n global:\n" while read -r line; do # Skip empty lines and comment lines starting with semicolon if [[ "$line" =~ ^\;.*$|^[[:space:]]*$ ]]; then continue fi # Remove the CR character in case the sources are mapped from # a Windows share and contain CRLF line endings line="${line//$'\r'/}" # Only prefix the entries that start with "#" if [[ "$line" =~ ^#.*$ ]]; then printf " %s%s;\n" "$prefix" "${line//#/}" else printf " %s;\n" "$line" fi done < "$1" printf " local: *;\n};\n"
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/pipelines/coreclr/superpmi-asmdiffs.yml
# This pipeline only runs on GitHub PRs, not on merges. trigger: none # Only run on changes to the JIT directory. Don't run if the JIT-EE GUID has changed, # since there won't be any SuperPMI collections with the new GUID until the collection # pipeline completes after this PR is merged. pr: branches: include: - main paths: # If you are changing these and start including eng/common, adjust the Maestro subscriptions # so that this build can block dependency auto-updates (this build is currently ignored) include: - src/coreclr/jit/* exclude: - src/coreclr/inc/jiteeversionguid.h jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-jit-job.yml buildConfig: checked platforms: - windows_x64 - windows_x86 jobParameters: uploadAs: 'pipelineArtifacts' - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/superpmi-asmdiffs-job.yml buildConfig: checked platforms: - windows_x64 - windows_x86 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml
# This pipeline only runs on GitHub PRs, not on merges. trigger: none # Only run on changes to the JIT directory. Don't run if the JIT-EE GUID has changed, # since there won't be any SuperPMI collections with the new GUID until the collection # pipeline completes after this PR is merged. pr: branches: include: - main paths: # If you are changing these and start including eng/common, adjust the Maestro subscriptions # so that this build can block dependency auto-updates (this build is currently ignored) include: - src/coreclr/jit/* exclude: - src/coreclr/inc/jiteeversionguid.h jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/build-jit-job.yml buildConfig: checked platforms: - windows_x64 - windows_x86 jobParameters: uploadAs: 'pipelineArtifacts' - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/coreclr/templates/superpmi-asmdiffs-job.yml buildConfig: checked platforms: - windows_x64 - windows_x86 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/Common/tests/System/Net/EnterpriseTests/setup/kdc/setup-kdc.sh
#!/usr/bin/env bash set -e # Kerbose Logging mkdir -pv /var/log/kerberos/ touch /var/log/kerberos/krb5.log touch /var/log/kerberos/kadmin.log touch /var/log/kerberos/krb5lib.log # Create Kerberos database kdb5_util create -r LINUX.CONTOSO.COM -P PLACEHOLDERadmin. -s # Start KDC service krb5kdc # Add users kadmin.local -q "add_principal -pw PLACEHOLDERcorrect20 root/[email protected]" kadmin.local -q "add_principal -pw PLACEHOLDERcorrect20 [email protected]" # Add SPNs for services kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HTTP/apacheweb.linux.contoso.com" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HTTP/altweb.linux.contoso.com:8080" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HOST/linuxclient.linux.contoso.com" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HOST/localhost" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. NEWSERVICE/localhost" # Create keytab files for other machines kadmin.local ktadd -k /SHARED/apacheweb.keytab -norandkey -glob "HTTP/*web*" kadmin.local ktadd -k /SHARED/linuxclient.keytab -norandkey HOST/linuxclient.linux.contoso.com kadmin.local ktadd -k /SHARED/linuxclient.keytab -norandkey HOST/localhost
#!/usr/bin/env bash set -e # Kerbose Logging mkdir -pv /var/log/kerberos/ touch /var/log/kerberos/krb5.log touch /var/log/kerberos/kadmin.log touch /var/log/kerberos/krb5lib.log # Create Kerberos database kdb5_util create -r LINUX.CONTOSO.COM -P PLACEHOLDERadmin. -s # Start KDC service krb5kdc # Add users kadmin.local -q "add_principal -pw PLACEHOLDERcorrect20 root/[email protected]" kadmin.local -q "add_principal -pw PLACEHOLDERcorrect20 [email protected]" # Add SPNs for services kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HTTP/apacheweb.linux.contoso.com" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HTTP/altweb.linux.contoso.com:8080" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HOST/linuxclient.linux.contoso.com" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. HOST/localhost" kadmin.local -q "add_principal -pw PLACEHOLDERadmin. NEWSERVICE/localhost" # Create keytab files for other machines kadmin.local ktadd -k /SHARED/apacheweb.keytab -norandkey -glob "HTTP/*web*" kadmin.local ktadd -k /SHARED/linuxclient.keytab -norandkey HOST/linuxclient.linux.contoso.com kadmin.local ktadd -k /SHARED/linuxclient.keytab -norandkey HOST/localhost
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/Common/src/System/Net/Http/aspnetcore/CopyToRuntime.sh
#!/usr/bin/env bash if [[ -n "$1" ]]; then remote_repo="$1" else remote_repo="$RUNTIME_REPO" fi if [[ -z "$remote_repo" ]]; then echo The 'RUNTIME_REPO' environment variable or command line parameter is not set, aborting. exit 1 fi cd "$(dirname "$0")" || exit 1 echo "RUNTIME_REPO: $remote_repo" rsync -av --delete ./ "$remote_repo"/src/libraries/Common/src/System/Net/Http/aspnetcore rsync -av --delete ./../test/Shared.Tests/runtime/ "$remote_repo"/src/libraries/Common/tests/Tests/System/Net/aspnetcore
#!/usr/bin/env bash if [[ -n "$1" ]]; then remote_repo="$1" else remote_repo="$RUNTIME_REPO" fi if [[ -z "$remote_repo" ]]; then echo The 'RUNTIME_REPO' environment variable or command line parameter is not set, aborting. exit 1 fi cd "$(dirname "$0")" || exit 1 echo "RUNTIME_REPO: $remote_repo" rsync -av --delete ./ "$remote_repo"/src/libraries/Common/src/System/Net/Http/aspnetcore rsync -av --delete ./../test/Shared.Tests/runtime/ "$remote_repo"/src/libraries/Common/tests/Tests/System/Net/aspnetcore
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/pipelines/coreclr/release-tests.yml
trigger: none schedules: - cron: "0 6 * * *" displayName: Daily at 10:00 PM (UTC-8:00) branches: include: - main always: true jobs: # # Release CoreCLR and Library builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: release platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 jobParameters: isOfficialBuild: false # # Release test builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: release platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: outerloop # # Release test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: release platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop liveLibrariesBuildConfig: Release # # Release R2R test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: release platformGroup: all helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop liveLibrariesBuildConfig: Release readyToRun: true displayNameArgs: R2R
trigger: none schedules: - cron: "0 6 * * *" displayName: Daily at 10:00 PM (UTC-8:00) branches: include: - main always: true jobs: # # Release CoreCLR and Library builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: release platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 jobParameters: isOfficialBuild: false # # Release test builds # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: release platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: outerloop # # Release test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: release platformGroup: all platforms: # It is too early to include OSX_arm64 in platform group all # Adding it here will enable it also - OSX_arm64 helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop liveLibrariesBuildConfig: Release # # Release R2R test runs # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml buildConfig: release platformGroup: all helixQueueGroup: ci helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: testGroup: outerloop liveLibrariesBuildConfig: Release readyToRun: true displayNameArgs: R2R
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/mono/mono/tests/verifier/make_generic_argument_constraints_test.sh
#! /bin/sh SED="sed" if [ `which gsed 2> /dev/null` ]; then SED="gsed" fi TEST_NAME=$1 TEST_VALIDITY=$2 TEST_SRC=$3 TEST_DEST=$4 TEST_INST_TYPE=$5 INST_TYPE="DefaultArgument"; if [ -n "$TEST_INST_TYPE" ]; then INST_TYPE="$TEST_INST_TYPE"; fi TEST_NAME=${TEST_VALIDITY}_${TEST_NAME} TEST_FILE=${TEST_NAME}_generated.il echo $TEST_FILE $SED -e "s/INIT/${TEST_INIT}/g" -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/TARGET_CONSTRAINT/${TEST_DEST}/g" -e "s/SOURCE_CONSTRAINT/${TEST_SRC}/g" > $TEST_FILE <<//EOF // VALIDITY CIL which breaks the ECMA-335 rules. // this CIL should fail verification by a conforming CLI verifier. .assembly '${TEST_NAME}_generated' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .assembly extern mscorlib { .ver 2:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. } .module bne_with_generic_type_type.exe .class interface public auto ansi abstract IfaceA { } .class interface public auto ansi abstract IfaceB { } .class public auto ansi Class extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void object::'.ctor'() ret } } .class public auto ansi DefaultArgument extends Class implements IfaceA, IfaceB { .method public hidebysig specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void Class::'.ctor'() ret } } .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void object::'.ctor'() ret } .method public static void Method< SOURCE_CONSTRAINT T> () { .locals init () ret } } .class public auto ansi beforefieldinit Test2< TARGET_CONSTRAINT T> extends [mscorlib]System.Object { .method public static void Method () { .locals init () call void class Test::Method<!T>() ret } } .method public static int32 Main () { .entrypoint .maxstack 8 call void class Test2< $INST_TYPE >::Method() ldc.i4.0 ret } //EOF
#! /bin/sh SED="sed" if [ `which gsed 2> /dev/null` ]; then SED="gsed" fi TEST_NAME=$1 TEST_VALIDITY=$2 TEST_SRC=$3 TEST_DEST=$4 TEST_INST_TYPE=$5 INST_TYPE="DefaultArgument"; if [ -n "$TEST_INST_TYPE" ]; then INST_TYPE="$TEST_INST_TYPE"; fi TEST_NAME=${TEST_VALIDITY}_${TEST_NAME} TEST_FILE=${TEST_NAME}_generated.il echo $TEST_FILE $SED -e "s/INIT/${TEST_INIT}/g" -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/TARGET_CONSTRAINT/${TEST_DEST}/g" -e "s/SOURCE_CONSTRAINT/${TEST_SRC}/g" > $TEST_FILE <<//EOF // VALIDITY CIL which breaks the ECMA-335 rules. // this CIL should fail verification by a conforming CLI verifier. .assembly '${TEST_NAME}_generated' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .assembly extern mscorlib { .ver 2:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. } .module bne_with_generic_type_type.exe .class interface public auto ansi abstract IfaceA { } .class interface public auto ansi abstract IfaceB { } .class public auto ansi Class extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void object::'.ctor'() ret } } .class public auto ansi DefaultArgument extends Class implements IfaceA, IfaceB { .method public hidebysig specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void Class::'.ctor'() ret } } .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void object::'.ctor'() ret } .method public static void Method< SOURCE_CONSTRAINT T> () { .locals init () ret } } .class public auto ansi beforefieldinit Test2< TARGET_CONSTRAINT T> extends [mscorlib]System.Object { .method public static void Method () { .locals init () call void class Test::Method<!T>() ret } } .method public static int32 Main () { .entrypoint .maxstack 8 call void class Test2< $INST_TYPE >::Method() ldc.i4.0 ret } //EOF
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/mono/mono/tests/verifier/make_il_overflow_test.sh
#! /bin/sh SED="sed" if [ `which gsed 2> /dev/null` ]; then SED="gsed" fi TEST_NAME=$1 TEST_VALIDITY=$2 TEST_BYTE_0=$3 TEST_BYTE_1=$4 TEST_BYTE_2=$5 TEST_BYTE_3=$6 TEST_BYTE_4=$7 if [ -n "$TEST_BYTE_1" ]; then EMIT_BYTE_1=".emitbyte $TEST_BYTE_1"; fi if [ -n "$TEST_BYTE_2" ]; then EMIT_BYTE_2=".emitbyte $TEST_BYTE_2"; fi if [ -n "$TEST_BYTE_3" ]; then EMIT_BYTE_3=".emitbyte $TEST_BYTE_3"; fi if [ -n "$TEST_BYTE_4" ]; then EMIT_BYTE_4=".emitbyte $TEST_BYTE_4"; fi if [ -n "$TEST_BYTE_5" ]; then EMIT_BYTE_5=".emitbyte $TEST_BYTE_5"; fi TEST_FILE=`echo ${TEST_VALIDITY}_${TEST_NAME} | $SED -e 's/ /_/g' -e 's/\./_/g' -e 's/&/mp/g' -e 's/\[/_/g' -e 's/\]/_/g'`_generated.il echo $TEST_FILE $SED -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/BYTE_0/${TEST_BYTE_0}/g" -e "s/BYTE_1/${TEST_BYTE_1}/g" > $TEST_FILE <<//EOF // VALIDITY CIL which breaks the ECMA-335 rules. // this CIL should fail verification by a conforming CLI verifier. .assembly '${TEST_NAME}_generated' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .method public static void Main() cil managed { .entrypoint .maxstack 2 .locals init () nop nop .emitbyte BYTE_0 ${EMIT_BYTE_1} ${EMIT_BYTE_2} ${EMIT_BYTE_3} ${EMIT_BYTE_4} ${EMIT_BYTE_5} } //EOF
#! /bin/sh SED="sed" if [ `which gsed 2> /dev/null` ]; then SED="gsed" fi TEST_NAME=$1 TEST_VALIDITY=$2 TEST_BYTE_0=$3 TEST_BYTE_1=$4 TEST_BYTE_2=$5 TEST_BYTE_3=$6 TEST_BYTE_4=$7 if [ -n "$TEST_BYTE_1" ]; then EMIT_BYTE_1=".emitbyte $TEST_BYTE_1"; fi if [ -n "$TEST_BYTE_2" ]; then EMIT_BYTE_2=".emitbyte $TEST_BYTE_2"; fi if [ -n "$TEST_BYTE_3" ]; then EMIT_BYTE_3=".emitbyte $TEST_BYTE_3"; fi if [ -n "$TEST_BYTE_4" ]; then EMIT_BYTE_4=".emitbyte $TEST_BYTE_4"; fi if [ -n "$TEST_BYTE_5" ]; then EMIT_BYTE_5=".emitbyte $TEST_BYTE_5"; fi TEST_FILE=`echo ${TEST_VALIDITY}_${TEST_NAME} | $SED -e 's/ /_/g' -e 's/\./_/g' -e 's/&/mp/g' -e 's/\[/_/g' -e 's/\]/_/g'`_generated.il echo $TEST_FILE $SED -e "s/VALIDITY/${TEST_VALIDITY}/g" -e "s/BYTE_0/${TEST_BYTE_0}/g" -e "s/BYTE_1/${TEST_BYTE_1}/g" > $TEST_FILE <<//EOF // VALIDITY CIL which breaks the ECMA-335 rules. // this CIL should fail verification by a conforming CLI verifier. .assembly '${TEST_NAME}_generated' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .method public static void Main() cil managed { .entrypoint .maxstack 2 .locals init () nop nop .emitbyte BYTE_0 ${EMIT_BYTE_1} ${EMIT_BYTE_2} ${EMIT_BYTE_3} ${EMIT_BYTE_4} ${EMIT_BYTE_5} } //EOF
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./eng/pipelines/coreclr/crossgen2.yml
trigger: none schedules: - cron: "0 6 * * *" displayName: Mon through Sun at 10:00 PM (UTC-8:00) branches: include: - main always: true jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: checked platforms: - Linux_x64 - Linux_arm64 - OSX_arm64 - OSX_x64 - windows_x64 - windows_arm64 - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: innerloop - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: innerloop - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml buildConfig: checked platforms: - Linux_x64 - Linux_arm64 - OSX_arm64 - OSX_x64 - windows_x64 - windows_arm64 jobParameters: testGroup: innerloop readyToRun: true crossgen2: true displayNameArgs: R2R_CG2 liveLibrariesBuildConfig: Release
trigger: none schedules: - cron: "0 6 * * *" displayName: Mon through Sun at 10:00 PM (UTC-8:00) branches: include: - main always: true jobs: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: checked platforms: - Linux_x64 - Linux_arm64 - OSX_arm64 - OSX_x64 - windows_x64 - windows_arm64 - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: innerloop - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml buildConfig: checked platforms: - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: innerloop - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml buildConfig: checked platforms: - Linux_x64 - Linux_arm64 - OSX_arm64 - OSX_x64 - windows_x64 - windows_arm64 jobParameters: testGroup: innerloop readyToRun: true crossgen2: true displayNameArgs: R2R_CG2 liveLibrariesBuildConfig: Release
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/mono/mono/arch/arm/vfpops.sh
#!/bin/sh DYADIC="ADD SUB MUL NMUL DIV" MONADIC="CPY ABS NEG SQRT CMP CMPE CMPZ CMPEZ CVT UITO SITO TOUI TOSI TOUIZ TOSIZ" # $1: opcode list # $2: template gen() { for i in $1; do sed "s/<Op>/$i/g" $2.th done } echo -e "/* Macros for VFP ops, auto-generated from template */\n" echo -e "\n/* dyadic */\n" gen "$DYADIC" vfp_macros echo -e "\n/* monadic */\n" gen "$MONADIC" vfpm_macros echo -e "\n\n" echo -e "\n/* end generated */\n"
#!/bin/sh DYADIC="ADD SUB MUL NMUL DIV" MONADIC="CPY ABS NEG SQRT CMP CMPE CMPZ CMPEZ CVT UITO SITO TOUI TOSI TOUIZ TOSIZ" # $1: opcode list # $2: template gen() { for i in $1; do sed "s/<Op>/$i/g" $2.th done } echo -e "/* Macros for VFP ops, auto-generated from template */\n" echo -e "\n/* dyadic */\n" gen "$DYADIC" vfp_macros echo -e "\n/* monadic */\n" gen "$MONADIC" vfpm_macros echo -e "\n\n" echo -e "\n/* end generated */\n"
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/mono/mono/tests/verifier/valid_iface_constant_with_parent_implementing_it.il
.assembly extern mscorlib { .ver 2:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. } .assembly 'repro' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .module repro.exe .class interface public auto ansi abstract INameable {} .class public auto ansi abstract Base implements INameable {} .class public auto ansi abstract Derived extends Base {} .class public auto ansi Nameables<(class INameable) T> { .method public specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void object::'.ctor'() ret } } .class auto ansi beforefieldinit Driver extends [mscorlib]System.Object { .method public static hidebysig default int32 Test () cil managed { .maxstack 8 .locals init () newobj instance void class Nameables<class Derived>::'.ctor'() pop ldc.i4.0 ret } .method private static hidebysig default int32 Main () cil managed { .entrypoint .maxstack 8 .locals init () call int32 class Driver::Test () ret } }
.assembly extern mscorlib { .ver 2:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. } .assembly 'repro' { .hash algorithm 0x00008004 .ver 0:0:0:0 } .module repro.exe .class interface public auto ansi abstract INameable {} .class public auto ansi abstract Base implements INameable {} .class public auto ansi abstract Derived extends Base {} .class public auto ansi Nameables<(class INameable) T> { .method public specialname rtspecialname instance default void '.ctor' () cil managed { .maxstack 8 ldarg.0 call instance void object::'.ctor'() ret } } .class auto ansi beforefieldinit Driver extends [mscorlib]System.Object { .method public static hidebysig default int32 Test () cil managed { .maxstack 8 .locals init () newobj instance void class Nameables<class Derived>::'.ctor'() pop ldc.i4.0 ret } .method private static hidebysig default int32 Main () cil managed { .entrypoint .maxstack 8 .locals init () call int32 class Driver::Test () ret } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/System.Linq/src/System/Linq/DefaultIfEmpty.SpeedOpt.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; namespace System.Linq { public static partial class Enumerable { private sealed partial class DefaultIfEmptyIterator<TSource> : IIListProvider<TSource> { public TSource[] ToArray() { TSource[] array = _source.ToArray(); return array.Length == 0 ? new[] { _default } : array; } public List<TSource> ToList() { List<TSource> list = _source.ToList(); if (list.Count == 0) { list.Add(_default); } return list; } public int GetCount(bool onlyIfCheap) { int count; if (!onlyIfCheap || _source is ICollection<TSource> || _source is ICollection) { count = _source.Count(); } else { count = _source is IIListProvider<TSource> listProv ? listProv.GetCount(onlyIfCheap: true) : -1; } return count == 0 ? 1 : count; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; namespace System.Linq { public static partial class Enumerable { private sealed partial class DefaultIfEmptyIterator<TSource> : IIListProvider<TSource> { public TSource[] ToArray() { TSource[] array = _source.ToArray(); return array.Length == 0 ? new[] { _default } : array; } public List<TSource> ToList() { List<TSource> list = _source.ToList(); if (list.Count == 0) { list.Add(_default); } return list; } public int GetCount(bool onlyIfCheap) { int count; if (!onlyIfCheap || _source is ICollection<TSource> || _source is ICollection) { count = _source.Count(); } else { count = _source is IIListProvider<TSource> listProv ? listProv.GetCount(onlyIfCheap: true) : -1; } return count == 0 ? 1 : count; } } } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/tests/JIT/Directed/nullabletypes/boxunboxenum_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="boxunboxenum.cs" /> <Compile Include="Desktop\StructDefinitions.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="boxunboxenum.cs" /> <Compile Include="Desktop\StructDefinitions.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/Average.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AverageByte() { var test = new SimpleBinaryOpTest__AverageByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AverageByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AverageByte testClass) { var result = Sse2.Average(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AverageByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AverageByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__AverageByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Average( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Average( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Average( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Average( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.Average(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Average(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Average(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AverageByte(); var result = Sse2.Average(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AverageByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Average(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Average(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Average( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((byte)((left[0] + right[0] + 1) >> 1) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)((left[i] + right[i] + 1) >> 1) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Average)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AverageByte() { var test = new SimpleBinaryOpTest__AverageByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AverageByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AverageByte testClass) { var result = Sse2.Average(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AverageByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AverageByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__AverageByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Average( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Average( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Average( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Average( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.Average(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Average(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Average(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AverageByte(); var result = Sse2.Average(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AverageByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Average(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.Average( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Average(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Average( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((byte)((left[0] + right[0] + 1) >> 1) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)((left[i] + right[i] + 1) >> 1) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Average)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/native/libs/System.Security.Cryptography.Native.Android/pal_hmac.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma once #include "pal_jni.h" PALEXPORT jobject CryptoNative_HmacCreate(uint8_t* key, int32_t keyLen, intptr_t md); PALEXPORT int32_t CryptoNative_HmacReset(jobject ctx); PALEXPORT int32_t CryptoNative_HmacUpdate(jobject ctx, uint8_t* data, int32_t len); PALEXPORT int32_t CryptoNative_HmacFinal(jobject ctx, uint8_t* md, int32_t* len); PALEXPORT int32_t CryptoNative_HmacCurrent(jobject ctx, uint8_t* md, int32_t* len); PALEXPORT void CryptoNative_HmacDestroy(jobject ctx); PALEXPORT int32_t CryptoNative_HmacOneShot(intptr_t type, uint8_t* key, int32_t keyLen, uint8_t* source, int32_t sourceLen, uint8_t* md, int32_t* mdSize);
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #pragma once #include "pal_jni.h" PALEXPORT jobject CryptoNative_HmacCreate(uint8_t* key, int32_t keyLen, intptr_t md); PALEXPORT int32_t CryptoNative_HmacReset(jobject ctx); PALEXPORT int32_t CryptoNative_HmacUpdate(jobject ctx, uint8_t* data, int32_t len); PALEXPORT int32_t CryptoNative_HmacFinal(jobject ctx, uint8_t* md, int32_t* len); PALEXPORT int32_t CryptoNative_HmacCurrent(jobject ctx, uint8_t* md, int32_t* len); PALEXPORT void CryptoNative_HmacDestroy(jobject ctx); PALEXPORT int32_t CryptoNative_HmacOneShot(intptr_t type, uint8_t* key, int32_t keyLen, uint8_t* source, int32_t sourceLen, uint8_t* md, int32_t* mdSize);
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerExtensionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Text.Encodings.Web; using System.Text.Json; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.Extensions.Logging.Test { public class ConsoleLoggerExtensionsTests { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSimpleConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddSimpleConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSystemdConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddSystemdConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddJsonConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsoleFormatter_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddConsoleFormatter<CustomFormatter, CustomOptions>(null); })); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [MemberData(nameof(FormatterNames))] public void AddConsole_ConsoleLoggerOptionsFromConfigFile_IsReadFromLoggingConfiguration(string formatterName) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterName", formatterName) }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole()) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(formatterName, logger.Options.FormatterName); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsoleFormatter_CustomFormatter_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterName", "custom"), new KeyValuePair<string, string>("Console:FormatterOptions:CustomLabel", "random"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsoleFormatter<CustomFormatter, CustomOptions>(fOptions => { fOptions.CustomLabel = "random"; }) .AddConsole(o => { o.FormatterName = "custom"; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal("custom", logger.Options.FormatterName); var formatter = Assert.IsType<CustomFormatter>(logger.Formatter); Assert.Equal("random", formatter.FormatterOptions.CustomLabel); } private class CustomFormatter : ConsoleFormatter, IDisposable { private IDisposable _optionsReloadToken; public CustomFormatter(IOptionsMonitor<CustomOptions> options) : base("custom") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = options.OnChange(ReloadLoggerOptions); } private void ReloadLoggerOptions(CustomOptions options) { FormatterOptions = options; } public CustomOptions FormatterOptions { get; set; } public string CustomLog { get; set; } public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter) { CustomLog = logEntry.Formatter(logEntry.State, logEntry.Exception); } public void Dispose() { _optionsReloadToken?.Dispose(); } } private class CustomOptions : ConsoleFormatterOptions { public string CustomLabel { get; set; } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSimpleConsole_ChangeProperties_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:ColorBehavior", "Disabled"), new KeyValuePair<string, string>("Console:FormatterOptions:SingleLine", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSimpleConsole() ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Simple, logger.Options.FormatterName); var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.Equal(LoggerColorBehavior.Disabled, formatter.FormatterOptions.ColorBehavior); Assert.True(formatter.FormatterOptions.SingleLine); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSimpleConsole_OutsideConfig_TakesProperty() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "false"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSimpleConsole(o => { o.TimestampFormat = "HH:mm:ss "; o.IncludeScopes = false; o.UseUtcTimestamp = true; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Simple, logger.Options.FormatterName); var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); Assert.False(formatter.FormatterOptions.IncludeScopes); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSystemdConsole_ChangeProperties_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSystemdConsole() ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Systemd, logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSystemdConsole_OutsideConfig_TakesProperty() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSystemdConsole(o => { o.TimestampFormat = "HH:mm:ss "; o.IncludeScopes = false; o.UseUtcTimestamp = false; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Systemd, logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); Assert.False(formatter.FormatterOptions.UseUtcTimestamp); Assert.False(formatter.FormatterOptions.IncludeScopes); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_ChangeProperties_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:JsonWriterOptions:Indented", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddJsonConsole() ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Json, logger.Options.FormatterName); var formatter = Assert.IsType<JsonConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); Assert.True(formatter.FormatterOptions.JsonWriterOptions.Indented); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_OutsideConfig_TakesProperty() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddJsonConsole(o => { o.JsonWriterOptions = new JsonWriterOptions() { Indented = false, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Json, logger.Options.FormatterName); var formatter = Assert.IsType<JsonConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); Assert.False(formatter.FormatterOptions.JsonWriterOptions.Indented); Assert.Equal(JavaScriptEncoder.UnsafeRelaxedJsonEscaping, formatter.FormatterOptions.JsonWriterOptions.Encoder); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullFormatterNameUsingSystemdFormat_AnyDeprecatedPropertiesOverwriteFormatterOptions() { var configs = new[] { new KeyValuePair<string, string>("Console:Format", "Systemd"), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }; var configuration = new ConfigurationBuilder().AddInMemoryCollection(configs).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Null(logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullFormatterName_UsingSystemdFormat_IgnoreFormatterOptionsAndUseDeprecatedInstead() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Systemd"), new KeyValuePair<string, string>("Console:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Null(logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); // ignore FormatterOptions, using deprecated one Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // not set anywhere, defaulted to false Assert.False(formatter.FormatterOptions.IncludeScopes); // setup using lambda wins over config } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullFormatterName_UsingDefaultFormat_IgnoreFormatterOptionsAndUseDeprecatedInstead() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Default"), new KeyValuePair<string, string>("Console:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:SingleLine", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.DisableColors = true; o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Null(logger.Options.FormatterName); #pragma warning disable CS0618 Assert.True(logger.Options.DisableColors); #pragma warning restore CS0618 var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.False(formatter.FormatterOptions.SingleLine); // ignored Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); // ignore FormatterOptions, using deprecated one Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // not set anywhere, defaulted to false Assert.False(formatter.FormatterOptions.IncludeScopes); // setup using lambda wins over config Assert.Equal(LoggerColorBehavior.Disabled, formatter.FormatterOptions.ColorBehavior); // setup using lambda } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData("missingFormatter")] [InlineData("simple")] [InlineData("Simple")] public void AddConsole_FormatterNameIsSet_UsingDefaultFormat_IgnoreDeprecatedAndUseFormatterOptionsInstead(string formatterName) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Default"), new KeyValuePair<string, string>("Console:FormatterName", formatterName), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:SingleLine", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.DisableColors = true; o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(formatterName, logger.Options.FormatterName); #pragma warning disable CS0618 Assert.True(logger.Options.DisableColors); #pragma warning restore CS0618 var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.True(formatter.FormatterOptions.SingleLine); // picked from FormatterOptions Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); // ignore deprecated, using FormatterOptions instead Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // not set anywhere, defaulted to false Assert.True(formatter.FormatterOptions.IncludeScopes); // ignore deprecated set in lambda use FormatterOptions instead Assert.Equal(LoggerColorBehavior.Default, formatter.FormatterOptions.ColorBehavior); // ignore deprecated set in lambda, defaulted to false } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData("missingFormatter")] [InlineData("systemd")] [InlineData("Systemd")] public void AddConsole_FormatterNameIsSet_UsingSystemdFormat_IgnoreDeprecatedAndUseFormatterOptionsInstead(string formatterName) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Systemd"), new KeyValuePair<string, string>("Console:FormatterName", formatterName), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.UseUtcTimestamp = true; o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(formatterName, logger.Options.FormatterName); #pragma warning disable CS0618 Assert.True(logger.Options.UseUtcTimestamp); #pragma warning restore CS0618 var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); // ignore deprecated, using FormatterOptions instead Assert.True(formatter.FormatterOptions.IncludeScopes); // ignore deprecated set in lambda use FormatterOptions instead Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // ignore deprecated set in lambda, defaulted to false } public static TheoryData<string> FormatterNames { get { var data = new TheoryData<string>(); data.Add(ConsoleFormatterNames.Simple); data.Add(ConsoleFormatterNames.Systemd); data.Add(ConsoleFormatterNames.Json); return data; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Text.Encodings.Web; using System.Text.Json; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.Extensions.Logging.Test { public class ConsoleLoggerExtensionsTests { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSimpleConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddSimpleConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSystemdConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddSystemdConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddJsonConsole(null); })); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsoleFormatter_NullConfigure_Throws() { Assert.Throws<ArgumentNullException>(() => new ServiceCollection() .AddLogging(builder => { builder.AddConsoleFormatter<CustomFormatter, CustomOptions>(null); })); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [MemberData(nameof(FormatterNames))] public void AddConsole_ConsoleLoggerOptionsFromConfigFile_IsReadFromLoggingConfiguration(string formatterName) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterName", formatterName) }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole()) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(formatterName, logger.Options.FormatterName); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsoleFormatter_CustomFormatter_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterName", "custom"), new KeyValuePair<string, string>("Console:FormatterOptions:CustomLabel", "random"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsoleFormatter<CustomFormatter, CustomOptions>(fOptions => { fOptions.CustomLabel = "random"; }) .AddConsole(o => { o.FormatterName = "custom"; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal("custom", logger.Options.FormatterName); var formatter = Assert.IsType<CustomFormatter>(logger.Formatter); Assert.Equal("random", formatter.FormatterOptions.CustomLabel); } private class CustomFormatter : ConsoleFormatter, IDisposable { private IDisposable _optionsReloadToken; public CustomFormatter(IOptionsMonitor<CustomOptions> options) : base("custom") { ReloadLoggerOptions(options.CurrentValue); _optionsReloadToken = options.OnChange(ReloadLoggerOptions); } private void ReloadLoggerOptions(CustomOptions options) { FormatterOptions = options; } public CustomOptions FormatterOptions { get; set; } public string CustomLog { get; set; } public override void Write<TState>(in LogEntry<TState> logEntry, IExternalScopeProvider scopeProvider, TextWriter textWriter) { CustomLog = logEntry.Formatter(logEntry.State, logEntry.Exception); } public void Dispose() { _optionsReloadToken?.Dispose(); } } private class CustomOptions : ConsoleFormatterOptions { public string CustomLabel { get; set; } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSimpleConsole_ChangeProperties_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:ColorBehavior", "Disabled"), new KeyValuePair<string, string>("Console:FormatterOptions:SingleLine", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSimpleConsole() ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Simple, logger.Options.FormatterName); var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.Equal(LoggerColorBehavior.Disabled, formatter.FormatterOptions.ColorBehavior); Assert.True(formatter.FormatterOptions.SingleLine); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSimpleConsole_OutsideConfig_TakesProperty() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "false"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSimpleConsole(o => { o.TimestampFormat = "HH:mm:ss "; o.IncludeScopes = false; o.UseUtcTimestamp = true; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Simple, logger.Options.FormatterName); var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); Assert.False(formatter.FormatterOptions.IncludeScopes); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSystemdConsole_ChangeProperties_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSystemdConsole() ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Systemd, logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddSystemdConsole_OutsideConfig_TakesProperty() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddSystemdConsole(o => { o.TimestampFormat = "HH:mm:ss "; o.IncludeScopes = false; o.UseUtcTimestamp = false; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Systemd, logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); Assert.False(formatter.FormatterOptions.UseUtcTimestamp); Assert.False(formatter.FormatterOptions.IncludeScopes); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_ChangeProperties_IsReadFromLoggingConfiguration() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:JsonWriterOptions:Indented", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddJsonConsole() ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Json, logger.Options.FormatterName); var formatter = Assert.IsType<JsonConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); Assert.True(formatter.FormatterOptions.JsonWriterOptions.Indented); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddJsonConsole_OutsideConfig_TakesProperty() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), new KeyValuePair<string, string>("Console:FormatterOptions:UseUtcTimestamp", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddJsonConsole(o => { o.JsonWriterOptions = new JsonWriterOptions() { Indented = false, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(ConsoleFormatterNames.Json, logger.Options.FormatterName); var formatter = Assert.IsType<JsonConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); Assert.True(formatter.FormatterOptions.UseUtcTimestamp); Assert.True(formatter.FormatterOptions.IncludeScopes); Assert.False(formatter.FormatterOptions.JsonWriterOptions.Indented); Assert.Equal(JavaScriptEncoder.UnsafeRelaxedJsonEscaping, formatter.FormatterOptions.JsonWriterOptions.Encoder); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullFormatterNameUsingSystemdFormat_AnyDeprecatedPropertiesOverwriteFormatterOptions() { var configs = new[] { new KeyValuePair<string, string>("Console:Format", "Systemd"), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }; var configuration = new ConfigurationBuilder().AddInMemoryCollection(configs).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Null(logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullFormatterName_UsingSystemdFormat_IgnoreFormatterOptionsAndUseDeprecatedInstead() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Systemd"), new KeyValuePair<string, string>("Console:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Null(logger.Options.FormatterName); var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); // ignore FormatterOptions, using deprecated one Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // not set anywhere, defaulted to false Assert.False(formatter.FormatterOptions.IncludeScopes); // setup using lambda wins over config } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void AddConsole_NullFormatterName_UsingDefaultFormat_IgnoreFormatterOptionsAndUseDeprecatedInstead() { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Default"), new KeyValuePair<string, string>("Console:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:SingleLine", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.DisableColors = true; o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Null(logger.Options.FormatterName); #pragma warning disable CS0618 Assert.True(logger.Options.DisableColors); #pragma warning restore CS0618 var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.False(formatter.FormatterOptions.SingleLine); // ignored Assert.Equal("HH:mm:ss ", formatter.FormatterOptions.TimestampFormat); // ignore FormatterOptions, using deprecated one Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // not set anywhere, defaulted to false Assert.False(formatter.FormatterOptions.IncludeScopes); // setup using lambda wins over config Assert.Equal(LoggerColorBehavior.Disabled, formatter.FormatterOptions.ColorBehavior); // setup using lambda } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData("missingFormatter")] [InlineData("simple")] [InlineData("Simple")] public void AddConsole_FormatterNameIsSet_UsingDefaultFormat_IgnoreDeprecatedAndUseFormatterOptionsInstead(string formatterName) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Default"), new KeyValuePair<string, string>("Console:FormatterName", formatterName), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:SingleLine", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.DisableColors = true; o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(formatterName, logger.Options.FormatterName); #pragma warning disable CS0618 Assert.True(logger.Options.DisableColors); #pragma warning restore CS0618 var formatter = Assert.IsType<SimpleConsoleFormatter>(logger.Formatter); Assert.True(formatter.FormatterOptions.SingleLine); // picked from FormatterOptions Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); // ignore deprecated, using FormatterOptions instead Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // not set anywhere, defaulted to false Assert.True(formatter.FormatterOptions.IncludeScopes); // ignore deprecated set in lambda use FormatterOptions instead Assert.Equal(LoggerColorBehavior.Default, formatter.FormatterOptions.ColorBehavior); // ignore deprecated set in lambda, defaulted to false } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [InlineData("missingFormatter")] [InlineData("systemd")] [InlineData("Systemd")] public void AddConsole_FormatterNameIsSet_UsingSystemdFormat_IgnoreDeprecatedAndUseFormatterOptionsInstead(string formatterName) { var configuration = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("Console:Format", "Systemd"), new KeyValuePair<string, string>("Console:FormatterName", formatterName), new KeyValuePair<string, string>("Console:TimestampFormat", "HH:mm:ss "), new KeyValuePair<string, string>("Console:FormatterOptions:IncludeScopes", "true"), new KeyValuePair<string, string>("Console:FormatterOptions:TimestampFormat", "HH:mm "), }).Build(); var loggerProvider = new ServiceCollection() .AddLogging(builder => builder .AddConfiguration(configuration) .AddConsole(o => { #pragma warning disable CS0618 o.UseUtcTimestamp = true; o.IncludeScopes = false; #pragma warning restore CS0618 }) ) .BuildServiceProvider() .GetRequiredService<ILoggerProvider>(); var consoleLoggerProvider = Assert.IsType<ConsoleLoggerProvider>(loggerProvider); var logger = (ConsoleLogger)consoleLoggerProvider.CreateLogger("Category"); Assert.Equal(formatterName, logger.Options.FormatterName); #pragma warning disable CS0618 Assert.True(logger.Options.UseUtcTimestamp); #pragma warning restore CS0618 var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter); Assert.Equal("HH:mm ", formatter.FormatterOptions.TimestampFormat); // ignore deprecated, using FormatterOptions instead Assert.True(formatter.FormatterOptions.IncludeScopes); // ignore deprecated set in lambda use FormatterOptions instead Assert.False(formatter.FormatterOptions.UseUtcTimestamp); // ignore deprecated set in lambda, defaulted to false } public static TheoryData<string> FormatterNames { get { var data = new TheoryData<string>(); data.Add(ConsoleFormatterNames.Simple); data.Add(ConsoleFormatterNames.Systemd); data.Add(ConsoleFormatterNames.Json); return data; } } } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/ceq_i.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ceq_i.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <RestorePackages>true</RestorePackages> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ceq_i.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/System.IO.FileSystem/tests/RandomAccess/ReadScatterAsync.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using Xunit; namespace System.IO.Tests { [ActiveIssue("https://github.com/dotnet/runtime/issues/34582", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [SkipOnPlatform(TestPlatforms.Browser, "async file IO is not supported on browser")] public class RandomAccess_ReadScatterAsync : RandomAccess_Base<ValueTask<long>> { protected override ValueTask<long> MethodUnderTest(SafeFileHandle handle, byte[] bytes, long fileOffset) => RandomAccess.ReadAsync(handle, new Memory<byte>[] { bytes }, fileOffset); [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public void ThrowsArgumentNullExceptionForNullBuffers(FileOptions options) { using (SafeFileHandle handle = File.OpenHandle(GetTestFilePath(), FileMode.CreateNew, FileAccess.Write, options: options)) { AssertExtensions.Throws<ArgumentNullException>("buffers", () => RandomAccess.ReadAsync(handle, buffers: null, 0)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task TaskAlreadyCanceledAsync(FileOptions options) { using (SafeFileHandle handle = File.OpenHandle(GetTestFilePath(), FileMode.CreateNew, FileAccess.ReadWrite, options: options)) { CancellationTokenSource cts = GetCancelledTokenSource(); CancellationToken token = cts.Token; Assert.True(RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, 0, token).IsCanceled); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, 0, token).AsTask()); Assert.Equal(token, ex.CancellationToken); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ThrowsOnWriteAccess(FileOptions options) { using (SafeFileHandle handle = GetHandleToExistingFile(FileAccess.Write, options)) { await Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, 0)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadToAnEmptyBufferReturnsZeroAsync(FileOptions options) { string filePath = GetTestFilePath(); File.WriteAllBytes(filePath, new byte[1]); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { Assert.Equal(0, await RandomAccess.ReadAsync(handle, new Memory<byte>[] { Array.Empty<byte>() }, fileOffset: 0)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadFromBeyondEndOfFileReturnsZeroAsync(FileOptions options) { string filePath = GetTestFilePath(); File.WriteAllBytes(filePath, new byte[100]); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { long eof = RandomAccess.GetLength(handle); Assert.Equal(0, await RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, fileOffset: eof + 1)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadsBytesFromGivenFileAtGivenOffsetAsync(FileOptions options) { const int fileSize = 4_001; string filePath = GetTestFilePath(); byte[] expected = RandomNumberGenerator.GetBytes(fileSize); File.WriteAllBytes(filePath, expected); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { byte[] actual = new byte[fileSize + 1]; long current = 0; long total = 0; do { int firstBufferLength = (int)Math.Min(actual.Length - total, fileSize / 4); Memory<byte> buffer_1 = actual.AsMemory((int)total, firstBufferLength); Memory<byte> buffer_2 = actual.AsMemory((int)total + firstBufferLength); current = await RandomAccess.ReadAsync( handle, new Memory<byte>[] { buffer_1, Array.Empty<byte>(), buffer_2 }, fileOffset: total); Assert.InRange(current, 0, buffer_1.Length + buffer_2.Length); total += current; } while (current != 0); Assert.Equal(fileSize, total); Assert.Equal(expected, actual.Take((int)total).ToArray()); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadToTheSameBufferOverwritesContent(FileOptions options) { string filePath = GetTestFilePath(); File.WriteAllBytes(filePath, new byte[3] { 1, 2, 3 }); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { byte[] buffer = new byte[1]; Assert.Equal(buffer.Length + buffer.Length, await RandomAccess.ReadAsync(handle, Enumerable.Repeat(buffer.AsMemory(), 2).ToList(), fileOffset: 0)); Assert.Equal(2, buffer[0]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using Xunit; namespace System.IO.Tests { [ActiveIssue("https://github.com/dotnet/runtime/issues/34582", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [SkipOnPlatform(TestPlatforms.Browser, "async file IO is not supported on browser")] public class RandomAccess_ReadScatterAsync : RandomAccess_Base<ValueTask<long>> { protected override ValueTask<long> MethodUnderTest(SafeFileHandle handle, byte[] bytes, long fileOffset) => RandomAccess.ReadAsync(handle, new Memory<byte>[] { bytes }, fileOffset); [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public void ThrowsArgumentNullExceptionForNullBuffers(FileOptions options) { using (SafeFileHandle handle = File.OpenHandle(GetTestFilePath(), FileMode.CreateNew, FileAccess.Write, options: options)) { AssertExtensions.Throws<ArgumentNullException>("buffers", () => RandomAccess.ReadAsync(handle, buffers: null, 0)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task TaskAlreadyCanceledAsync(FileOptions options) { using (SafeFileHandle handle = File.OpenHandle(GetTestFilePath(), FileMode.CreateNew, FileAccess.ReadWrite, options: options)) { CancellationTokenSource cts = GetCancelledTokenSource(); CancellationToken token = cts.Token; Assert.True(RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, 0, token).IsCanceled); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, 0, token).AsTask()); Assert.Equal(token, ex.CancellationToken); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ThrowsOnWriteAccess(FileOptions options) { using (SafeFileHandle handle = GetHandleToExistingFile(FileAccess.Write, options)) { await Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, 0)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadToAnEmptyBufferReturnsZeroAsync(FileOptions options) { string filePath = GetTestFilePath(); File.WriteAllBytes(filePath, new byte[1]); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { Assert.Equal(0, await RandomAccess.ReadAsync(handle, new Memory<byte>[] { Array.Empty<byte>() }, fileOffset: 0)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadFromBeyondEndOfFileReturnsZeroAsync(FileOptions options) { string filePath = GetTestFilePath(); File.WriteAllBytes(filePath, new byte[100]); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { long eof = RandomAccess.GetLength(handle); Assert.Equal(0, await RandomAccess.ReadAsync(handle, new Memory<byte>[] { new byte[1] }, fileOffset: eof + 1)); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadsBytesFromGivenFileAtGivenOffsetAsync(FileOptions options) { const int fileSize = 4_001; string filePath = GetTestFilePath(); byte[] expected = RandomNumberGenerator.GetBytes(fileSize); File.WriteAllBytes(filePath, expected); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { byte[] actual = new byte[fileSize + 1]; long current = 0; long total = 0; do { int firstBufferLength = (int)Math.Min(actual.Length - total, fileSize / 4); Memory<byte> buffer_1 = actual.AsMemory((int)total, firstBufferLength); Memory<byte> buffer_2 = actual.AsMemory((int)total + firstBufferLength); current = await RandomAccess.ReadAsync( handle, new Memory<byte>[] { buffer_1, Array.Empty<byte>(), buffer_2 }, fileOffset: total); Assert.InRange(current, 0, buffer_1.Length + buffer_2.Length); total += current; } while (current != 0); Assert.Equal(fileSize, total); Assert.Equal(expected, actual.Take((int)total).ToArray()); } } [Theory] [MemberData(nameof(GetSyncAsyncOptions))] public async Task ReadToTheSameBufferOverwritesContent(FileOptions options) { string filePath = GetTestFilePath(); File.WriteAllBytes(filePath, new byte[3] { 1, 2, 3 }); using (SafeFileHandle handle = File.OpenHandle(filePath, FileMode.Open, options: options)) { byte[] buffer = new byte[1]; Assert.Equal(buffer.Length + buffer.Length, await RandomAccess.ReadAsync(handle, Enumerable.Repeat(buffer.AsMemory(), 2).ToList(), fileOffset: 0)); Assert.Equal(2, buffer[0]); } } } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EmfPlusFlags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Drawing.Imaging { /** * EMF+ Flags */ internal enum EmfPlusFlags { Display = 0x00000001, NonDualGdi = 0x00000002 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Drawing.Imaging { /** * EMF+ Flags */ internal enum EmfPlusFlags { Display = 0x00000001, NonDualGdi = 0x00000002 } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/coreclr/tools/dotnet-pgo/R2RSignatureTypeProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using ILCompiler.Reflection.ReadyToRun; using Internal.ReadyToRunConstants; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace Microsoft.Diagnostics.Tools.Pgo { struct R2RSigProviderContext { } class R2RSignatureTypeProvider : IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProvider(TraceTypeSystemContext tsc) { _tsc = tsc; } TraceTypeSystemContext _tsc; TypeDesc IConstructedTypeProvider<TypeDesc>.GetArrayType(TypeDesc elementType, ArrayShape shape) { if (elementType == null) return null; return elementType.MakeArrayType(shape.Rank); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetByReferenceType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeByRefType(); } TypeDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetCanonType() { return _tsc.CanonType; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetConstrainedMethod(MethodDesc method, TypeDesc constraint) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetFunctionPointerType(MethodSignature<TypeDesc> signature) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetGenericInstantiation(TypeDesc genericType, ImmutableArray<TypeDesc> typeArguments) { if (genericType == null) return null; foreach (var type in typeArguments) { if (type == null) return null; } return _tsc.GetInstantiatedType((MetadataType)genericType, new Instantiation(typeArguments.ToArray())); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericMethodParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericTypeParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetInstantiatedMethod(MethodDesc uninstantiatedMethod, ImmutableArray<TypeDesc> instantiation) { if (uninstantiatedMethod == null) return null; foreach (var type in instantiation) { if (type == null) return null; } return uninstantiatedMethod.MakeInstantiatedMethod(instantiation.ToArray()); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } return method; } protected MethodDesc GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { if (owningTypeOverride != method.OwningType) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } } return method; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodWithFlags(ReadyToRunMethodSigFlags flags, MethodDesc method) { return method; } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetModifiedType(TypeDesc modifier, TypeDesc unmodifiedType, bool isRequired) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetPinnedType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetPointerType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetPrimitiveType(PrimitiveTypeCode typeCode) { WellKnownType wkt = 0; switch (typeCode) { case PrimitiveTypeCode.Void: wkt = WellKnownType.Void; break; case PrimitiveTypeCode.Boolean: wkt = WellKnownType.Boolean; break; case PrimitiveTypeCode.Char: wkt = WellKnownType.Char; break; case PrimitiveTypeCode.SByte: wkt = WellKnownType.SByte; break; case PrimitiveTypeCode.Byte: wkt = WellKnownType.Byte; break; case PrimitiveTypeCode.Int16: wkt = WellKnownType.Int16; break; case PrimitiveTypeCode.UInt16: wkt = WellKnownType.UInt16; break; case PrimitiveTypeCode.Int32: wkt = WellKnownType.Int32; break; case PrimitiveTypeCode.UInt32: wkt = WellKnownType.UInt32; break; case PrimitiveTypeCode.Int64: wkt = WellKnownType.Int64; break; case PrimitiveTypeCode.UInt64: wkt = WellKnownType.UInt64; break; case PrimitiveTypeCode.Single: wkt = WellKnownType.Single; break; case PrimitiveTypeCode.Double: wkt = WellKnownType.Double; break; case PrimitiveTypeCode.String: wkt = WellKnownType.String; break; case PrimitiveTypeCode.TypedReference: wkt = WellKnownType.TypedReference; break; case PrimitiveTypeCode.IntPtr: wkt = WellKnownType.IntPtr; break; case PrimitiveTypeCode.UIntPtr: wkt = WellKnownType.UIntPtr; break; case PrimitiveTypeCode.Object: wkt = WellKnownType.Object; break; } return _tsc.GetWellKnownType(wkt); } TypeDesc ISZArrayTypeProvider<TypeDesc>.GetSZArrayType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeArrayType(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetTypeFromSpecification(MetadataReader reader, R2RSigProviderContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } } class R2RSignatureTypeProviderForGlobalTables : R2RSignatureTypeProvider, IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProviderForGlobalTables(TraceTypeSystemContext tsc) : base(tsc) { } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { if (owningTypeOverride != null) { reader = ((EcmaModule)((MetadataType)owningTypeOverride.GetTypeDefinition()).Module).MetadataReader; } Debug.Assert(reader != null); return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { // Global signature cannot have MemberRef entries in them as such things aren't uniquely identifiable throw new NotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using ILCompiler.Reflection.ReadyToRun; using Internal.ReadyToRunConstants; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace Microsoft.Diagnostics.Tools.Pgo { struct R2RSigProviderContext { } class R2RSignatureTypeProvider : IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProvider(TraceTypeSystemContext tsc) { _tsc = tsc; } TraceTypeSystemContext _tsc; TypeDesc IConstructedTypeProvider<TypeDesc>.GetArrayType(TypeDesc elementType, ArrayShape shape) { if (elementType == null) return null; return elementType.MakeArrayType(shape.Rank); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetByReferenceType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeByRefType(); } TypeDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetCanonType() { return _tsc.CanonType; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetConstrainedMethod(MethodDesc method, TypeDesc constraint) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetFunctionPointerType(MethodSignature<TypeDesc> signature) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetGenericInstantiation(TypeDesc genericType, ImmutableArray<TypeDesc> typeArguments) { if (genericType == null) return null; foreach (var type in typeArguments) { if (type == null) return null; } return _tsc.GetInstantiatedType((MetadataType)genericType, new Instantiation(typeArguments.ToArray())); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericMethodParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericTypeParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetInstantiatedMethod(MethodDesc uninstantiatedMethod, ImmutableArray<TypeDesc> instantiation) { if (uninstantiatedMethod == null) return null; foreach (var type in instantiation) { if (type == null) return null; } return uninstantiatedMethod.MakeInstantiatedMethod(instantiation.ToArray()); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } return method; } protected MethodDesc GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { if (owningTypeOverride != method.OwningType) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } } return method; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodWithFlags(ReadyToRunMethodSigFlags flags, MethodDesc method) { return method; } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetModifiedType(TypeDesc modifier, TypeDesc unmodifiedType, bool isRequired) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetPinnedType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetPointerType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetPrimitiveType(PrimitiveTypeCode typeCode) { WellKnownType wkt = 0; switch (typeCode) { case PrimitiveTypeCode.Void: wkt = WellKnownType.Void; break; case PrimitiveTypeCode.Boolean: wkt = WellKnownType.Boolean; break; case PrimitiveTypeCode.Char: wkt = WellKnownType.Char; break; case PrimitiveTypeCode.SByte: wkt = WellKnownType.SByte; break; case PrimitiveTypeCode.Byte: wkt = WellKnownType.Byte; break; case PrimitiveTypeCode.Int16: wkt = WellKnownType.Int16; break; case PrimitiveTypeCode.UInt16: wkt = WellKnownType.UInt16; break; case PrimitiveTypeCode.Int32: wkt = WellKnownType.Int32; break; case PrimitiveTypeCode.UInt32: wkt = WellKnownType.UInt32; break; case PrimitiveTypeCode.Int64: wkt = WellKnownType.Int64; break; case PrimitiveTypeCode.UInt64: wkt = WellKnownType.UInt64; break; case PrimitiveTypeCode.Single: wkt = WellKnownType.Single; break; case PrimitiveTypeCode.Double: wkt = WellKnownType.Double; break; case PrimitiveTypeCode.String: wkt = WellKnownType.String; break; case PrimitiveTypeCode.TypedReference: wkt = WellKnownType.TypedReference; break; case PrimitiveTypeCode.IntPtr: wkt = WellKnownType.IntPtr; break; case PrimitiveTypeCode.UIntPtr: wkt = WellKnownType.UIntPtr; break; case PrimitiveTypeCode.Object: wkt = WellKnownType.Object; break; } return _tsc.GetWellKnownType(wkt); } TypeDesc ISZArrayTypeProvider<TypeDesc>.GetSZArrayType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeArrayType(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetTypeFromSpecification(MetadataReader reader, R2RSigProviderContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } } class R2RSignatureTypeProviderForGlobalTables : R2RSignatureTypeProvider, IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProviderForGlobalTables(TraceTypeSystemContext tsc) : base(tsc) { } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { if (owningTypeOverride != null) { reader = ((EcmaModule)((MetadataType)owningTypeOverride.GetTypeDefinition()).Module).MetadataReader; } Debug.Assert(reader != null); return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { // Global signature cannot have MemberRef entries in them as such things aren't uniquely identifiable throw new NotSupportedException(); } } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/tests/JIT/HardwareIntrinsics/General/Vector256/BitwiseAnd.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void BitwiseAndSingle() { var test = new VectorBinaryOpTest__BitwiseAndSingle(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__BitwiseAndSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__BitwiseAndSingle testClass) { var result = Vector256.BitwiseAnd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__BitwiseAndSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorBinaryOpTest__BitwiseAndSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.BitwiseAnd( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.BitwiseAnd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.BitwiseAnd), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.BitwiseAnd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = Vector256.BitwiseAnd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__BitwiseAndSingle(); var result = Vector256.BitwiseAnd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.BitwiseAnd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.BitwiseAnd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != (BitConverter.SingleToInt32Bits(left[0]) & BitConverter.SingleToInt32Bits(right[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != (BitConverter.SingleToInt32Bits(left[i]) & BitConverter.SingleToInt32Bits(right[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.BitwiseAnd)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void BitwiseAndSingle() { var test = new VectorBinaryOpTest__BitwiseAndSingle(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__BitwiseAndSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__BitwiseAndSingle testClass) { var result = Vector256.BitwiseAnd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__BitwiseAndSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorBinaryOpTest__BitwiseAndSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.BitwiseAnd( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.BitwiseAnd), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.BitwiseAnd), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Single)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.BitwiseAnd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = Vector256.BitwiseAnd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__BitwiseAndSingle(); var result = Vector256.BitwiseAnd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.BitwiseAnd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.BitwiseAnd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != (BitConverter.SingleToInt32Bits(left[0]) & BitConverter.SingleToInt32Bits(right[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != (BitConverter.SingleToInt32Bits(left[i]) & BitConverter.SingleToInt32Bits(right[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.BitwiseAnd)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,981
attempt to fix up EnterpriseTests
contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
wfurt
2022-03-01T01:09:41Z
2022-03-03T22:16:04Z
35c518b61bb5220d28ecca6812f2f1443140d61e
9174037cc6b58de847c9c88b7dcceef2b4fda440
attempt to fix up EnterpriseTests. contributes to https://github.com/dotnet/core-eng/issues/15594. It seems like te container cannot resolve outside addresses, There may be cleaner ways how to fix this But as stop-gap, tis seems to work e.g. there is already test script so if the lookup fails it would add public server.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b59478/b59478.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Runtime.Loader/tests/ApplyUpdateTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using Xunit; namespace System.Reflection.Metadata { /// /// The general setup for ApplyUpdate tests is: /// /// Each test Foo has a corresponding assembly under /// System.Reflection.Metadata.ApplyUpate.Test.Foo The Foo.csproj has a delta /// script that applies one or more updates to Foo.dll The ApplyUpdateTest /// testsuite runs each test in sequence, loading the corresponding /// assembly, applying an update to it and observing the results. [Collection(nameof(DisableParallelization))] public class ApplyUpdateTest { [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void StaticMethodBodyUpdate() { ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.MethodBody1).Assembly; var r = ApplyUpdate.Test.MethodBody1.StaticMethod1(); Assert.Equal("OLD STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = ApplyUpdate.Test.MethodBody1.StaticMethod1(); Assert.Equal("NEW STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = ApplyUpdate.Test.MethodBody1.StaticMethod1 (); Assert.Equal ("NEWEST STRING", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void LambdaBodyChange() { ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.LambdaBodyChange).Assembly; var o = new ApplyUpdate.Test.LambdaBodyChange (); var r = o.MethodWithLambda(); Assert.Equal("OLD STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEW STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEWEST STRING!", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void LambdaCapturesThis() { // Tests that changes to the body of a lambda that captures 'this' is supported. ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.LambdaCapturesThis).Assembly; var o = new ApplyUpdate.Test.LambdaCapturesThis (); var r = o.MethodWithLambda(); Assert.Equal("OLD STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEW STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEWEST STRING!", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void FirstCallAfterUpdate() { /* Tests that updating a method that has not been called before works correctly and that * the JIT/interpreter doesn't have to rely on cached baseline data. */ ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.FirstCallAfterUpdate).Assembly; var o = new ApplyUpdate.Test.FirstCallAfterUpdate (); ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ApplyUpdate(assm); string r = o.Method1("NEW"); Assert.Equal("NEWEST STRING", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/52993", TestRuntimes.Mono)] void ClassWithCustomAttributes() { ApplyUpdateUtil.TestCase(static () => { // Get the custom attribtues from a newly-added type and method // and check that they are the expected ones. var assm = typeof(ApplyUpdate.Test.ClassWithCustomAttributesHelper).Assembly; // returns ClassWithCustomAttributes var ty = ApplyUpdate.Test.ClassWithCustomAttributesHelper.GetAttributedClass(); Assert.NotNull (ty); ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ClearAllReflectionCaches(); // returns ClassWithCustomAttributes2 ty = ApplyUpdate.Test.ClassWithCustomAttributesHelper.GetAttributedClass(); Assert.NotNull (ty); var attrType = typeof(ObsoleteAttribute); var cattrs = Attribute.GetCustomAttributes(ty, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); Assert.NotNull(cattrs[0]); Assert.Equal(attrType, cattrs[0].GetType()); var methodName = "Method2"; var mi = ty.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); Assert.NotNull (mi); cattrs = Attribute.GetCustomAttributes(mi, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); Assert.NotNull(cattrs[0]); Assert.Equal(attrType, cattrs[0].GetType()); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] public void CustomAttributeUpdates() { // Test that _modifying_ custom attribute constructor/property argumments works as expected. // For this test, we don't change which constructor is called, or how many custom attributes there are. ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeUpdates).Assembly; ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ClearAllReflectionCaches(); // Just check the updated value on one method Type attrType = typeof(System.Reflection.Metadata.ApplyUpdate.Test.MyAttribute); Type ty = assm.GetType("System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeUpdates"); Assert.NotNull(ty); MethodInfo mi = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeUpdates.Method1), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi); var cattrs = Attribute.GetCustomAttributes(mi, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); Assert.NotNull(cattrs[0]); Assert.Equal(attrType, cattrs[0].GetType()); string p = (cattrs[0] as System.Reflection.Metadata.ApplyUpdate.Test.MyAttribute).StringValue; Assert.Equal("rstuv", p); }); } [ActiveIssue("https://github.com/dotnet/runtime/issues/52993", TestRuntimes.Mono)] [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] public void CustomAttributeDelete() { // Test that deleting custom attribute on constructor/property works as expected. ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete).Assembly; ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ClearAllReflectionCaches(); // Just check the updated value on one method Type attrType = typeof(System.Reflection.Metadata.ApplyUpdate.Test.MyDeleteAttribute); Type ty = assm.GetType("System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete"); Assert.NotNull(ty); MethodInfo mi1 = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete.Method1), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi1); Attribute[] cattrs = Attribute.GetCustomAttributes(mi1, attrType); Assert.NotNull(cattrs); Assert.Equal(0, cattrs.Length); MethodInfo mi2 = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete.Method2), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi2); cattrs = Attribute.GetCustomAttributes(mi2, attrType); Assert.NotNull(cattrs); Assert.Equal(0, cattrs.Length); MethodInfo mi3 = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete.Method3), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi3); cattrs = Attribute.GetCustomAttributes(mi3, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); string p = (cattrs[0] as System.Reflection.Metadata.ApplyUpdate.Test.MyDeleteAttribute).StringValue; Assert.Equal("Not Deleted", p); }); } [ActiveIssue("https://github.com/dotnet/runtime/issues/52993", TestRuntimes.Mono)] [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] public void AsyncMethodChanges() { // Test that changing an async method doesn't cause any type load exceptions ApplyUpdateUtil.TestCase(static () => { Assembly assembly = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange).Assembly; ApplyUpdateUtil.ApplyUpdate(assembly); ApplyUpdateUtil.ClearAllReflectionCaches(); Type ty = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange); Assert.NotNull(ty); MethodInfo mi = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange.TestTaskMethod), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi); string result = ApplyUpdate.Test.AsyncMethodChange.TestTaskMethod().GetAwaiter().GetResult(); Assert.Equal("TestTaskMethod v1", result); object[] attributes = mi.GetCustomAttributes(true); Assert.NotNull(attributes); Assert.True(attributes.Length > 0); foreach (var attribute in attributes) { if (attribute is AsyncStateMachineAttribute asm) { Assert.Contains("<TestTaskMethod>", asm.StateMachineType.Name); } } }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddLambdaCapturingThis() { // Test that adding a lambda that captures 'this' (to a method that already has a lambda that captures 'this') is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis(); Assert.Equal("123", x.TestMethod()); ApplyUpdateUtil.ApplyUpdate(assm); string result = x.TestMethod(); Assert.Equal("42123abcd", result); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddStaticField() { // Test that adding a new static field to an existing class is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField(); x.TestMethod(); Assert.Equal ("abcd", x.GetField); ApplyUpdateUtil.ApplyUpdate(assm); x.TestMethod(); string result = x.GetField; Assert.Equal("4567", result); }); } [ActiveIssue("https://github.com/dotnet/runtime/issues/63643", TestRuntimes.Mono)] [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddNestedClass() { // Test that adding a new nested class to an existing class is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass(); var r = x.TestMethod(); Assert.Equal ("123", r); ApplyUpdateUtil.ApplyUpdate(assm); r = x.TestMethod(); Assert.Equal("123456", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddStaticLambda() { // Test that adding a new static lambda to an existing method body is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda(); var r = x.TestMethod(); Assert.Equal ("abcd", r); ApplyUpdateUtil.ApplyUpdate(assm); r = x.TestMethod(); Assert.Equal("abcd1abcd", r); }); } class NonRuntimeAssembly : Assembly { } [Fact] public static void ApplyUpdateInvalidParameters() { // Dummy delta arrays var metadataDelta = new byte[20]; var ilDelta = new byte[20]; // Assembly can't be null Assert.Throws<ArgumentNullException>("assembly", () => MetadataUpdater.ApplyUpdate(null, new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty)); // Tests fail on non-runtime assemblies Assert.Throws<ArgumentException>(() => MetadataUpdater.ApplyUpdate(new NonRuntimeAssembly(), new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty)); // Tests that this assembly isn't not editable Assert.Throws<InvalidOperationException>(() => MetadataUpdater.ApplyUpdate(typeof(AssemblyExtensions).Assembly, new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty)); } [Fact] public static void GetCapabilities() { var ty = typeof(System.Reflection.Metadata.MetadataUpdater); var mi = ty.GetMethod("GetCapabilities", BindingFlags.NonPublic | BindingFlags.Static, Array.Empty<Type>()); Assert.NotNull(mi); var result = mi.Invoke(null, null); Assert.NotNull(result); Assert.Equal(typeof(string), result.GetType()); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.TestUsingRemoteExecutor))] public static void IsSupported() { bool result = MetadataUpdater.IsSupported; Assert.False(result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using Xunit; namespace System.Reflection.Metadata { /// /// The general setup for ApplyUpdate tests is: /// /// Each test Foo has a corresponding assembly under /// System.Reflection.Metadata.ApplyUpate.Test.Foo The Foo.csproj has a delta /// script that applies one or more updates to Foo.dll The ApplyUpdateTest /// testsuite runs each test in sequence, loading the corresponding /// assembly, applying an update to it and observing the results. [Collection(nameof(DisableParallelization))] public class ApplyUpdateTest { [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void StaticMethodBodyUpdate() { ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.MethodBody1).Assembly; var r = ApplyUpdate.Test.MethodBody1.StaticMethod1(); Assert.Equal("OLD STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = ApplyUpdate.Test.MethodBody1.StaticMethod1(); Assert.Equal("NEW STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = ApplyUpdate.Test.MethodBody1.StaticMethod1 (); Assert.Equal ("NEWEST STRING", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void LambdaBodyChange() { ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.LambdaBodyChange).Assembly; var o = new ApplyUpdate.Test.LambdaBodyChange (); var r = o.MethodWithLambda(); Assert.Equal("OLD STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEW STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEWEST STRING!", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void LambdaCapturesThis() { // Tests that changes to the body of a lambda that captures 'this' is supported. ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.LambdaCapturesThis).Assembly; var o = new ApplyUpdate.Test.LambdaCapturesThis (); var r = o.MethodWithLambda(); Assert.Equal("OLD STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEW STRING", r); ApplyUpdateUtil.ApplyUpdate(assm); r = o.MethodWithLambda(); Assert.Equal("NEWEST STRING!", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void FirstCallAfterUpdate() { /* Tests that updating a method that has not been called before works correctly and that * the JIT/interpreter doesn't have to rely on cached baseline data. */ ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.FirstCallAfterUpdate).Assembly; var o = new ApplyUpdate.Test.FirstCallAfterUpdate (); ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ApplyUpdate(assm); string r = o.Method1("NEW"); Assert.Equal("NEWEST STRING", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/52993", TestRuntimes.Mono)] void ClassWithCustomAttributes() { ApplyUpdateUtil.TestCase(static () => { // Get the custom attribtues from a newly-added type and method // and check that they are the expected ones. var assm = typeof(ApplyUpdate.Test.ClassWithCustomAttributesHelper).Assembly; // returns ClassWithCustomAttributes var ty = ApplyUpdate.Test.ClassWithCustomAttributesHelper.GetAttributedClass(); Assert.NotNull (ty); ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ClearAllReflectionCaches(); // returns ClassWithCustomAttributes2 ty = ApplyUpdate.Test.ClassWithCustomAttributesHelper.GetAttributedClass(); Assert.NotNull (ty); var attrType = typeof(ObsoleteAttribute); var cattrs = Attribute.GetCustomAttributes(ty, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); Assert.NotNull(cattrs[0]); Assert.Equal(attrType, cattrs[0].GetType()); var methodName = "Method2"; var mi = ty.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); Assert.NotNull (mi); cattrs = Attribute.GetCustomAttributes(mi, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); Assert.NotNull(cattrs[0]); Assert.Equal(attrType, cattrs[0].GetType()); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] public void CustomAttributeUpdates() { // Test that _modifying_ custom attribute constructor/property argumments works as expected. // For this test, we don't change which constructor is called, or how many custom attributes there are. ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeUpdates).Assembly; ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ClearAllReflectionCaches(); // Just check the updated value on one method Type attrType = typeof(System.Reflection.Metadata.ApplyUpdate.Test.MyAttribute); Type ty = assm.GetType("System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeUpdates"); Assert.NotNull(ty); MethodInfo mi = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeUpdates.Method1), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi); var cattrs = Attribute.GetCustomAttributes(mi, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); Assert.NotNull(cattrs[0]); Assert.Equal(attrType, cattrs[0].GetType()); string p = (cattrs[0] as System.Reflection.Metadata.ApplyUpdate.Test.MyAttribute).StringValue; Assert.Equal("rstuv", p); }); } [ActiveIssue("https://github.com/dotnet/runtime/issues/52993", TestRuntimes.Mono)] [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] public void CustomAttributeDelete() { // Test that deleting custom attribute on constructor/property works as expected. ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete).Assembly; ApplyUpdateUtil.ApplyUpdate(assm); ApplyUpdateUtil.ClearAllReflectionCaches(); // Just check the updated value on one method Type attrType = typeof(System.Reflection.Metadata.ApplyUpdate.Test.MyDeleteAttribute); Type ty = assm.GetType("System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete"); Assert.NotNull(ty); MethodInfo mi1 = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete.Method1), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi1); Attribute[] cattrs = Attribute.GetCustomAttributes(mi1, attrType); Assert.NotNull(cattrs); Assert.Equal(0, cattrs.Length); MethodInfo mi2 = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete.Method2), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi2); cattrs = Attribute.GetCustomAttributes(mi2, attrType); Assert.NotNull(cattrs); Assert.Equal(0, cattrs.Length); MethodInfo mi3 = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributeDelete.Method3), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi3); cattrs = Attribute.GetCustomAttributes(mi3, attrType); Assert.NotNull(cattrs); Assert.Equal(1, cattrs.Length); string p = (cattrs[0] as System.Reflection.Metadata.ApplyUpdate.Test.MyDeleteAttribute).StringValue; Assert.Equal("Not Deleted", p); }); } [ActiveIssue("https://github.com/dotnet/runtime/issues/52993", TestRuntimes.Mono)] [ConditionalFact(typeof(ApplyUpdateUtil), nameof (ApplyUpdateUtil.IsSupported))] public void AsyncMethodChanges() { // Test that changing an async method doesn't cause any type load exceptions ApplyUpdateUtil.TestCase(static () => { Assembly assembly = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange).Assembly; ApplyUpdateUtil.ApplyUpdate(assembly); ApplyUpdateUtil.ClearAllReflectionCaches(); Type ty = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange); Assert.NotNull(ty); MethodInfo mi = ty.GetMethod(nameof(System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange.TestTaskMethod), BindingFlags.Public | BindingFlags.Static); Assert.NotNull(mi); string result = ApplyUpdate.Test.AsyncMethodChange.TestTaskMethod().GetAwaiter().GetResult(); Assert.Equal("TestTaskMethod v1", result); object[] attributes = mi.GetCustomAttributes(true); Assert.NotNull(attributes); Assert.True(attributes.Length > 0); foreach (var attribute in attributes) { if (attribute is AsyncStateMachineAttribute asm) { Assert.Contains("<TestTaskMethod>", asm.StateMachineType.Name); } } }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddLambdaCapturingThis() { // Test that adding a lambda that captures 'this' (to a method that already has a lambda that captures 'this') is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis(); Assert.Equal("123", x.TestMethod()); ApplyUpdateUtil.ApplyUpdate(assm); string result = x.TestMethod(); Assert.Equal("42123abcd", result); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddStaticField() { // Test that adding a new static field to an existing class is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField(); x.TestMethod(); Assert.Equal ("abcd", x.GetField); ApplyUpdateUtil.ApplyUpdate(assm); x.TestMethod(); string result = x.GetField; Assert.Equal("4567", result); }); } [ActiveIssue("https://github.com/dotnet/runtime/issues/63643", TestRuntimes.Mono)] [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddNestedClass() { // Test that adding a new nested class to an existing class is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass(); var r = x.TestMethod(); Assert.Equal ("123", r); ApplyUpdateUtil.ApplyUpdate(assm); r = x.TestMethod(); Assert.Equal("123456", r); }); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestAddStaticLambda() { // Test that adding a new static lambda to an existing method body is supported ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda(); var r = x.TestMethod(); Assert.Equal ("abcd", r); ApplyUpdateUtil.ApplyUpdate(assm); r = x.TestMethod(); Assert.Equal("abcd1abcd", r); }); } class NonRuntimeAssembly : Assembly { } [Fact] public static void ApplyUpdateInvalidParameters() { // Dummy delta arrays var metadataDelta = new byte[20]; var ilDelta = new byte[20]; // Assembly can't be null Assert.Throws<ArgumentNullException>("assembly", () => MetadataUpdater.ApplyUpdate(null, new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty)); // Tests fail on non-runtime assemblies Assert.Throws<ArgumentException>(() => MetadataUpdater.ApplyUpdate(new NonRuntimeAssembly(), new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty)); // Tests that this assembly isn't not editable Assert.Throws<InvalidOperationException>(() => MetadataUpdater.ApplyUpdate(typeof(AssemblyExtensions).Assembly, new ReadOnlySpan<byte>(metadataDelta), new ReadOnlySpan<byte>(ilDelta), ReadOnlySpan<byte>.Empty)); } [Fact] public static void GetCapabilities() { var ty = typeof(System.Reflection.Metadata.MetadataUpdater); var mi = ty.GetMethod("GetCapabilities", BindingFlags.NonPublic | BindingFlags.Static, Array.Empty<Type>()); Assert.NotNull(mi); var result = mi.Invoke(null, null); Assert.NotNull(result); Assert.Equal(typeof(string), result.GetType()); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.TestUsingRemoteExecutor))] public static void IsSupported() { bool result = MetadataUpdater.IsSupported; Assert.False(result); } [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] public static void TestStaticLambdaRegression() { ApplyUpdateUtil.TestCase(static () => { var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.StaticLambdaRegression).Assembly; var x = new System.Reflection.Metadata.ApplyUpdate.Test.StaticLambdaRegression(); Assert.Equal (0, x.count); x.TestMethod(); x.TestMethod(); Assert.Equal (2, x.count); ApplyUpdateUtil.ApplyUpdate(assm, usePDB: false); x.TestMethod(); x.TestMethod(); Assert.Equal (4, x.count); ApplyUpdateUtil.ApplyUpdate(assm, usePDB: false); x.TestMethod(); x.TestMethod(); Assert.Equal (6, x.count); }); } } }
1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Runtime.Loader/tests/ApplyUpdateUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; using Microsoft.DotNet.RemoteExecutor; namespace System.Reflection.Metadata { public class ApplyUpdateUtil { internal const string DotNetModifiableAssembliesSwitch = "DOTNET_MODIFIABLE_ASSEMBLIES"; internal const string DotNetModifiableAssembliesValue = "debug"; /// Whether ApplyUpdate is supported by the environment, test configuration, and runtime. /// /// We need: /// 1. Either DOTNET_MODIFIABLE_ASSEMBLIES=debug is set, or we can use the RemoteExecutor to run a child process with that environment; and, /// 2. Either Mono in a supported configuration (interpreter as the execution engine, and the hot reload component enabled), or CoreCLR; and, /// 3. The test assemblies are compiled with Debug information (this is configured by setting EmitDebugInformation in ApplyUpdate\Directory.Build.props) public static bool IsSupported => (IsModifiableAssembliesSet || IsRemoteExecutorSupported) && (!IsMonoRuntime || IsSupportedMonoConfiguration); /// true if the current runtime was not launched with the apropriate settings for applying /// updates (DOTNET_MODIFIABLE_ASSEMBLIES unset), but we can use the remote executor to /// launch a child process that has the right setting. public static bool TestUsingRemoteExecutor => IsRemoteExecutorSupported && !IsModifiableAssembliesSet; /// true if the current runtime was launched with the appropriate settings for applying /// updates (DOTNET_MODIFIABLE_ASSEMBLIES set, and if Mono, the interpreter is enabled). public static bool TestUsingLaunchEnvironment => (!IsMonoRuntime || IsSupportedMonoConfiguration) && IsModifiableAssembliesSet; public static bool IsModifiableAssembliesSet => String.Equals(DotNetModifiableAssembliesValue, Environment.GetEnvironmentVariable(DotNetModifiableAssembliesSwitch), StringComparison.InvariantCultureIgnoreCase); // static cctor for RemoteExecutor throws on wasm. public static bool IsRemoteExecutorSupported => !RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")) && RemoteExecutor.IsSupported; public static bool IsMonoRuntime => PlatformDetection.IsMonoRuntime; private static readonly Lazy<bool> s_isSupportedMonoConfiguration = new Lazy<bool>(CheckSupportedMonoConfiguration); public static bool IsSupportedMonoConfiguration => s_isSupportedMonoConfiguration.Value; // Not every build of Mono supports ApplyUpdate internal static bool CheckSupportedMonoConfiguration() { // check that interpreter is enabled, and the build has hot reload capabilities enabled. var isInterp = RuntimeFeature.IsDynamicCodeSupported && !RuntimeFeature.IsDynamicCodeCompiled; return isInterp && !PlatformDetection.IsMonoAOT && HasApplyUpdateCapabilities(); } internal static bool HasApplyUpdateCapabilities() { var ty = typeof(MetadataUpdater); var mi = ty.GetMethod("GetCapabilities", BindingFlags.NonPublic | BindingFlags.Static, Array.Empty<Type>()); if (mi == null) return false; var caps = mi.Invoke(null, null); // any non-empty string, assumed to be at least "baseline" return caps is string {Length: > 0}; } private static System.Collections.Generic.Dictionary<Assembly, int> assembly_count = new(); internal static void ApplyUpdate (System.Reflection.Assembly assm) { int count; if (!assembly_count.TryGetValue(assm, out count)) count = 1; else count++; assembly_count [assm] = count; /* FIXME WASM: Location is empty on wasm. Make up a name based on Name */ string basename = assm.Location; if (basename == "") basename = assm.GetName().Name + ".dll"; Console.Error.WriteLine($"Applying metadata update for {basename}, revision {count}"); string dmeta_name = $"{basename}.{count}.dmeta"; string dil_name = $"{basename}.{count}.dil"; string dpdb_name = $"{basename}.{count}.dpdb"; byte[] dmeta_data = System.IO.File.ReadAllBytes(dmeta_name); byte[] dil_data = System.IO.File.ReadAllBytes(dil_name); byte[] dpdb_data = System.IO.File.ReadAllBytes(dpdb_name); MetadataUpdater.ApplyUpdate(assm, dmeta_data, dil_data, dpdb_data); } internal static void AddRemoteInvokeOptions (ref RemoteInvokeOptions options) { options = options ?? new RemoteInvokeOptions(); options.StartInfo.EnvironmentVariables.Add(DotNetModifiableAssembliesSwitch, DotNetModifiableAssembliesValue); /* Ask mono to use .dpdb data to generate sequence points even without a debugger attached */ if (IsMonoRuntime) AppendEnvironmentVariable(options.StartInfo.EnvironmentVariables, "MONO_DEBUG", "gen-seq-points"); } private static void AppendEnvironmentVariable(System.Collections.Specialized.StringDictionary env, string key, string addedValue) { if (!env.ContainsKey(key)) env.Add(key, addedValue); else { string oldValue = env[key]; env[key] = oldValue + "," + addedValue; } } /// Run the given test case, which applies updates to the given assembly. /// /// Note that the testBody should be a static delegate or a static /// lambda - it must not use state from the enclosing method. public static void TestCase(Action testBody, RemoteInvokeOptions options = null) { if (TestUsingRemoteExecutor) { Console.Error.WriteLine ($"Running test using RemoteExecutor"); AddRemoteInvokeOptions(ref options); RemoteExecutor.Invoke(testBody, options).Dispose(); } else { Console.Error.WriteLine($"Running test using direct invoke"); testBody(); } } /// Run the given test case, which applies updates to the given /// assembly, and has 1 additional argument. /// /// Note that the testBody should be a static delegate or a static /// lambda - it must not use state from the enclosing method. public static void TestCase(Action<string> testBody, string arg1, RemoteInvokeOptions options = null) { if (TestUsingRemoteExecutor) { AddRemoteInvokeOptions(ref options); RemoteExecutor.Invoke(testBody, arg1, options).Dispose(); } else { testBody(arg1); } } public static void ClearAllReflectionCaches() { // TODO: Implement for Mono, see https://github.com/dotnet/runtime/issues/50978 if (IsMonoRuntime) return; var clearCacheMethod = GetClearCacheMethod(); clearCacheMethod (null); } // CoreCLR only private static Action<Type[]> GetClearCacheMethod() { // TODO: Unify with src/libraries/System.Runtime/tests/System/Reflection/ReflectionCacheTests.cs Type updateHandler = typeof(Type).Assembly.GetType("System.Reflection.Metadata.RuntimeTypeMetadataUpdateHandler", throwOnError: true, ignoreCase: false); MethodInfo clearCache = updateHandler.GetMethod("ClearCache", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, new[] { typeof(Type[]) }); Assert.NotNull(clearCache); return clearCache.CreateDelegate<Action<Type[]>>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; using Microsoft.DotNet.RemoteExecutor; namespace System.Reflection.Metadata { public class ApplyUpdateUtil { internal const string DotNetModifiableAssembliesSwitch = "DOTNET_MODIFIABLE_ASSEMBLIES"; internal const string DotNetModifiableAssembliesValue = "debug"; /// Whether ApplyUpdate is supported by the environment, test configuration, and runtime. /// /// We need: /// 1. Either DOTNET_MODIFIABLE_ASSEMBLIES=debug is set, or we can use the RemoteExecutor to run a child process with that environment; and, /// 2. Either Mono in a supported configuration (interpreter as the execution engine, and the hot reload component enabled), or CoreCLR; and, /// 3. The test assemblies are compiled with Debug information (this is configured by setting EmitDebugInformation in ApplyUpdate\Directory.Build.props) public static bool IsSupported => (IsModifiableAssembliesSet || IsRemoteExecutorSupported) && (!IsMonoRuntime || IsSupportedMonoConfiguration); /// true if the current runtime was not launched with the apropriate settings for applying /// updates (DOTNET_MODIFIABLE_ASSEMBLIES unset), but we can use the remote executor to /// launch a child process that has the right setting. public static bool TestUsingRemoteExecutor => IsRemoteExecutorSupported && !IsModifiableAssembliesSet; /// true if the current runtime was launched with the appropriate settings for applying /// updates (DOTNET_MODIFIABLE_ASSEMBLIES set, and if Mono, the interpreter is enabled). public static bool TestUsingLaunchEnvironment => (!IsMonoRuntime || IsSupportedMonoConfiguration) && IsModifiableAssembliesSet; public static bool IsModifiableAssembliesSet => String.Equals(DotNetModifiableAssembliesValue, Environment.GetEnvironmentVariable(DotNetModifiableAssembliesSwitch), StringComparison.InvariantCultureIgnoreCase); // static cctor for RemoteExecutor throws on wasm. public static bool IsRemoteExecutorSupported => !RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")) && RemoteExecutor.IsSupported; public static bool IsMonoRuntime => PlatformDetection.IsMonoRuntime; private static readonly Lazy<bool> s_isSupportedMonoConfiguration = new Lazy<bool>(CheckSupportedMonoConfiguration); public static bool IsSupportedMonoConfiguration => s_isSupportedMonoConfiguration.Value; // Not every build of Mono supports ApplyUpdate internal static bool CheckSupportedMonoConfiguration() { // check that interpreter is enabled, and the build has hot reload capabilities enabled. var isInterp = RuntimeFeature.IsDynamicCodeSupported && !RuntimeFeature.IsDynamicCodeCompiled; return isInterp && !PlatformDetection.IsMonoAOT && HasApplyUpdateCapabilities(); } internal static bool HasApplyUpdateCapabilities() { var ty = typeof(MetadataUpdater); var mi = ty.GetMethod("GetCapabilities", BindingFlags.NonPublic | BindingFlags.Static, Array.Empty<Type>()); if (mi == null) return false; var caps = mi.Invoke(null, null); // any non-empty string, assumed to be at least "baseline" return caps is string {Length: > 0}; } private static System.Collections.Generic.Dictionary<Assembly, int> assembly_count = new(); internal static void ApplyUpdate (System.Reflection.Assembly assm, bool usePDB = true) { int count; if (!assembly_count.TryGetValue(assm, out count)) count = 1; else count++; assembly_count [assm] = count; /* FIXME WASM: Location is empty on wasm. Make up a name based on Name */ string basename = assm.Location; if (basename == "") basename = assm.GetName().Name + ".dll"; Console.Error.WriteLine($"Applying metadata update for {basename}, revision {count}"); string dmeta_name = $"{basename}.{count}.dmeta"; string dil_name = $"{basename}.{count}.dil"; string dpdb_name = $"{basename}.{count}.dpdb"; byte[] dmeta_data = System.IO.File.ReadAllBytes(dmeta_name); byte[] dil_data = System.IO.File.ReadAllBytes(dil_name); byte[] dpdb_data = null; if (usePDB) dpdb_data = System.IO.File.ReadAllBytes(dpdb_name); MetadataUpdater.ApplyUpdate(assm, dmeta_data, dil_data, dpdb_data); } internal static void AddRemoteInvokeOptions (ref RemoteInvokeOptions options) { options = options ?? new RemoteInvokeOptions(); options.StartInfo.EnvironmentVariables.Add(DotNetModifiableAssembliesSwitch, DotNetModifiableAssembliesValue); /* Ask mono to use .dpdb data to generate sequence points even without a debugger attached */ if (IsMonoRuntime) AppendEnvironmentVariable(options.StartInfo.EnvironmentVariables, "MONO_DEBUG", "gen-seq-points"); } private static void AppendEnvironmentVariable(System.Collections.Specialized.StringDictionary env, string key, string addedValue) { if (!env.ContainsKey(key)) env.Add(key, addedValue); else { string oldValue = env[key]; env[key] = oldValue + "," + addedValue; } } /// Run the given test case, which applies updates to the given assembly. /// /// Note that the testBody should be a static delegate or a static /// lambda - it must not use state from the enclosing method. public static void TestCase(Action testBody, RemoteInvokeOptions options = null) { if (TestUsingRemoteExecutor) { Console.Error.WriteLine ($"Running test using RemoteExecutor"); AddRemoteInvokeOptions(ref options); RemoteExecutor.Invoke(testBody, options).Dispose(); } else { Console.Error.WriteLine($"Running test using direct invoke"); testBody(); } } /// Run the given test case, which applies updates to the given /// assembly, and has 1 additional argument. /// /// Note that the testBody should be a static delegate or a static /// lambda - it must not use state from the enclosing method. public static void TestCase(Action<string> testBody, string arg1, RemoteInvokeOptions options = null) { if (TestUsingRemoteExecutor) { AddRemoteInvokeOptions(ref options); RemoteExecutor.Invoke(testBody, arg1, options).Dispose(); } else { testBody(arg1); } } public static void ClearAllReflectionCaches() { // TODO: Implement for Mono, see https://github.com/dotnet/runtime/issues/50978 if (IsMonoRuntime) return; var clearCacheMethod = GetClearCacheMethod(); clearCacheMethod (null); } // CoreCLR only private static Action<Type[]> GetClearCacheMethod() { // TODO: Unify with src/libraries/System.Runtime/tests/System/Reflection/ReflectionCacheTests.cs Type updateHandler = typeof(Type).Assembly.GetType("System.Reflection.Metadata.RuntimeTypeMetadataUpdateHandler", throwOnError: true, ignoreCase: false); MethodInfo clearCache = updateHandler.GetMethod("ClearCache", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, new[] { typeof(Type[]) }); Assert.NotNull(clearCache); return clearCache.CreateDelegate<Action<Type[]>>(); } } }
1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Runtime.Loader/tests/System.Runtime.Loader.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <RootNamespace>System.Runtime.Loader.Tests</RootNamespace> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <TestRuntime>true</TestRuntime> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <!-- Some tests rely on no deps.json file being present. --> <GenerateDependencyFile>false</GenerateDependencyFile> <!-- EnC tests on targets without a remote executor need the environment variable set before launching the test --> <!-- Also ask Mono to use make sequence points even without a debugger attached to match "dotnet watch" behavior --> <WasmXHarnessMonoArgs>--setenv=DOTNET_MODIFIABLE_ASSEMBLIES=debug --setenv=MONO_DEBUG=gen-seq-points</WasmXHarnessMonoArgs> <!-- disabled due to https://github.com/dotnet/runtime/issues/65672 --> <XUnitUseRandomizedTestOrderer>false</XUnitUseRandomizedTestOrderer> </PropertyGroup> <ItemGroup> <Compile Include="ApplyUpdateTest.cs" /> <Compile Include="ApplyUpdateUtil.cs" /> <Compile Include="AssemblyLoadContextTest.cs" /> <Compile Include="CollectibleAssemblyLoadContextTest.cs" /> <Compile Include="ContextualReflection.cs" /> <Compile Include="CustomTPALoadContext.cs" /> <Compile Include="MetadataUpdateHandlerAttributeTest.cs" /> <Compile Include="ResourceAssemblyLoadContext.cs" /> <Compile Include="SatelliteAssemblies.cs" /> <Compile Include="LoaderLinkTest.cs" /> <Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs" Link="Common\TestUtilities\System\DisableParallelization.cs" /> <EmbeddedResource Include="MainStrings*.resx" /> </ItemGroup> <PropertyGroup> <!-- used to figure out which project references are ApplyUpdate tests --> <ApplyUpdateTestPrefix>System.Reflection.Metadata.ApplyUpdate.Test.</ApplyUpdateTestPrefix> </PropertyGroup> <ItemGroup> <!-- iOS & tvOS are aot workloads and loading an embedded assembly results in some dynamic codegen, which is not allowed --> <ProjectReference Condition="'$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'tvOS'" Include="System.Runtime.Loader.Test.Assembly\System.Runtime.Loader.Test.Assembly.csproj" ReferenceOutputAssembly="false" OutputItemType="EmbeddedResource" /> <ProjectReference Condition="'$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'tvOS'" Include="System.Runtime.Loader.Test.Assembly2\System.Runtime.Loader.Test.Assembly2.csproj" ReferenceOutputAssembly="false" OutputItemType="EmbeddedResource" /> <ProjectReference Condition="'$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'tvOS'" Include="System.Runtime.Loader.Test.AssemblyNotSupported\System.Runtime.Loader.Test.AssemblyNotSupported.csproj" ReferenceOutputAssembly="false" OutputItemType="EmbeddedResource" /> <ProjectReference Condition="'$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'tvOS'" Include="System.Runtime.Loader.Test.Assembly\System.Runtime.Loader.Test.Assembly.csproj" /> <ProjectReference Condition="'$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'tvOS'" Include="System.Runtime.Loader.Test.Assembly2\System.Runtime.Loader.Test.Assembly2.csproj" /> <ProjectReference Condition="'$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'tvOS'" Include="System.Runtime.Loader.Test.AssemblyNotSupported\System.Runtime.Loader.Test.AssemblyNotSupported.csproj" /> <ProjectReference Include="ContextualReflectionDependency\System.Runtime.Loader.Test.ContextualReflectionDependency.csproj" /> <ProjectReference Include="ReferencedClassLib\ReferencedClassLib.csproj" /> <ProjectReference Include="ReferencedClassLibNeutralIsSatellite\ReferencedClassLibNeutralIsSatellite.csproj" /> <ProjectReference Include="LoaderLinkTest.Shared\LoaderLinkTest.Shared.csproj" /> <ProjectReference Include="LoaderLinkTest.Dynamic\LoaderLinkTest.Dynamic.csproj" /> <!-- ApplyUpdate tests --> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange\System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeDelete\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeDelete.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.MethodBody1\System.Reflection.Metadata.ApplyUpdate.Test.MethodBody1.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributes\System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributes.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeUpdate\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeUpdate.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.LambdaBodyChange\System.Reflection.Metadata.ApplyUpdate.Test.LambdaBodyChange.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.LambdaCapturesThis\System.Reflection.Metadata.ApplyUpdate.Test.LambdaCapturesThis.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.FirstCallAfterUpdate\System.Reflection.Metadata.ApplyUpdate.Test.FirstCallAfterUpdate.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis\System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass\System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetOS)' == 'Browser'"> <WasmFilesToIncludeFromPublishDir Include="$(AssemblyName).dll" /> <TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" /> </ItemGroup> <Target Name="PreserveEnCAssembliesFromLinking" Condition="'$(TargetOS)' == 'Browser' and '$(EnableAggressiveTrimming)' == 'true'" BeforeTargets="ConfigureTrimming"> <ItemGroup> <!-- want to compute the intersection: apply update test assemblies that are also resolved to publish. --> <ApplyUpdateTestProjectReference Include="@(ProjectReference)" Condition="$([System.String]::new('%(FileName)').StartsWith('$(ApplyUpdateTestPrefix)'))" /> <ApplyUpdateTestAssemblyName Include="@(ApplyUpdateTestProjectReference->'%(FileName).dll')" /> <ResolvedFileToPublishNoDirName Include="%(ResolvedFileToPublish.FileName)%(ResolvedFileToPublish.Extension)"> <ResolvedFileToPublish>%(ResolvedFileToPublish.FullPath)</ResolvedFileToPublish> </ResolvedFileToPublishNoDirName> <ResolvedApplyUpdateAssembly Include="@(ResolvedFileToPublishNoDirName)" Condition="'@(ResolvedFileToPublishNoDirName)' == '@(ApplyUpdateTestAssemblyName)' and %(Identity) != ''" /> <!-- Don't let the IL linker modify EnC test assemblies --> <TrimmerRootAssembly Include="%(ResolvedApplyUpdateAssembly.ResolvedFileToPublish)" /> </ItemGroup> </Target> <Target Name="IncludeDeltasInWasmBundle" BeforeTargets="PrepareForWasmBuildApp" Condition="'$(TargetOS)' == 'Browser'"> <ItemGroup> <!-- FIXME: this belongs in eng/testing/tests.wasm.targets --> <!-- FIXME: Can we do something on the Content items in the referenced projects themselves to get this for free? --> <WasmFilesToIncludeInFileSystem Include="@(PublishItemsOutputGroupOutputs)" Condition="$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.dmeta'))" /> <WasmFilesToIncludeInFileSystem Include="@(PublishItemsOutputGroupOutputs)" Condition="$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.dil'))" /> <WasmFilesToIncludeInFileSystem Include="@(PublishItemsOutputGroupOutputs)" Condition="$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.dpdb'))" /> </ItemGroup> </Target> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <RootNamespace>System.Runtime.Loader.Tests</RootNamespace> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <TestRuntime>true</TestRuntime> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <!-- Some tests rely on no deps.json file being present. --> <GenerateDependencyFile>false</GenerateDependencyFile> <!-- EnC tests on targets without a remote executor need the environment variable set before launching the test --> <!-- Also ask Mono to use make sequence points even without a debugger attached to match "dotnet watch" behavior --> <WasmXHarnessMonoArgs>--setenv=DOTNET_MODIFIABLE_ASSEMBLIES=debug --setenv=MONO_DEBUG=gen-seq-points</WasmXHarnessMonoArgs> <!-- disabled due to https://github.com/dotnet/runtime/issues/65672 --> <XUnitUseRandomizedTestOrderer>false</XUnitUseRandomizedTestOrderer> </PropertyGroup> <ItemGroup> <Compile Include="ApplyUpdateTest.cs" /> <Compile Include="ApplyUpdateUtil.cs" /> <Compile Include="AssemblyLoadContextTest.cs" /> <Compile Include="CollectibleAssemblyLoadContextTest.cs" /> <Compile Include="ContextualReflection.cs" /> <Compile Include="CustomTPALoadContext.cs" /> <Compile Include="MetadataUpdateHandlerAttributeTest.cs" /> <Compile Include="ResourceAssemblyLoadContext.cs" /> <Compile Include="SatelliteAssemblies.cs" /> <Compile Include="LoaderLinkTest.cs" /> <Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs" Link="Common\TestUtilities\System\DisableParallelization.cs" /> <EmbeddedResource Include="MainStrings*.resx" /> </ItemGroup> <PropertyGroup> <!-- used to figure out which project references are ApplyUpdate tests --> <ApplyUpdateTestPrefix>System.Reflection.Metadata.ApplyUpdate.Test.</ApplyUpdateTestPrefix> </PropertyGroup> <ItemGroup> <!-- iOS & tvOS are aot workloads and loading an embedded assembly results in some dynamic codegen, which is not allowed --> <ProjectReference Condition="'$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'tvOS'" Include="System.Runtime.Loader.Test.Assembly\System.Runtime.Loader.Test.Assembly.csproj" ReferenceOutputAssembly="false" OutputItemType="EmbeddedResource" /> <ProjectReference Condition="'$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'tvOS'" Include="System.Runtime.Loader.Test.Assembly2\System.Runtime.Loader.Test.Assembly2.csproj" ReferenceOutputAssembly="false" OutputItemType="EmbeddedResource" /> <ProjectReference Condition="'$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'tvOS'" Include="System.Runtime.Loader.Test.AssemblyNotSupported\System.Runtime.Loader.Test.AssemblyNotSupported.csproj" ReferenceOutputAssembly="false" OutputItemType="EmbeddedResource" /> <ProjectReference Condition="'$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'tvOS'" Include="System.Runtime.Loader.Test.Assembly\System.Runtime.Loader.Test.Assembly.csproj" /> <ProjectReference Condition="'$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'tvOS'" Include="System.Runtime.Loader.Test.Assembly2\System.Runtime.Loader.Test.Assembly2.csproj" /> <ProjectReference Condition="'$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'tvOS'" Include="System.Runtime.Loader.Test.AssemblyNotSupported\System.Runtime.Loader.Test.AssemblyNotSupported.csproj" /> <ProjectReference Include="ContextualReflectionDependency\System.Runtime.Loader.Test.ContextualReflectionDependency.csproj" /> <ProjectReference Include="ReferencedClassLib\ReferencedClassLib.csproj" /> <ProjectReference Include="ReferencedClassLibNeutralIsSatellite\ReferencedClassLibNeutralIsSatellite.csproj" /> <ProjectReference Include="LoaderLinkTest.Shared\LoaderLinkTest.Shared.csproj" /> <ProjectReference Include="LoaderLinkTest.Dynamic\LoaderLinkTest.Dynamic.csproj" /> <!-- ApplyUpdate tests --> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange\System.Reflection.Metadata.ApplyUpdate.Test.AsyncMethodChange.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeDelete\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeDelete.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.MethodBody1\System.Reflection.Metadata.ApplyUpdate.Test.MethodBody1.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributes\System.Reflection.Metadata.ApplyUpdate.Test.ClassWithCustomAttributes.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeUpdate\System.Reflection.Metadata.ApplyUpdate.Test.CustomAttributeUpdate.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.LambdaBodyChange\System.Reflection.Metadata.ApplyUpdate.Test.LambdaBodyChange.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.LambdaCapturesThis\System.Reflection.Metadata.ApplyUpdate.Test.LambdaCapturesThis.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.FirstCallAfterUpdate\System.Reflection.Metadata.ApplyUpdate.Test.FirstCallAfterUpdate.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis\System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass\System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda\System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda.csproj" /> <ProjectReference Include="ApplyUpdate\System.Reflection.Metadata.ApplyUpdate.Test.StaticLambdaRegression\System.Reflection.Metadata.ApplyUpdate.Test.StaticLambdaRegression.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetOS)' == 'Browser'"> <WasmFilesToIncludeFromPublishDir Include="$(AssemblyName).dll" /> <TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" /> </ItemGroup> <Target Name="PreserveEnCAssembliesFromLinking" Condition="'$(TargetOS)' == 'Browser' and '$(EnableAggressiveTrimming)' == 'true'" BeforeTargets="ConfigureTrimming"> <ItemGroup> <!-- want to compute the intersection: apply update test assemblies that are also resolved to publish. --> <ApplyUpdateTestProjectReference Include="@(ProjectReference)" Condition="$([System.String]::new('%(FileName)').StartsWith('$(ApplyUpdateTestPrefix)'))" /> <ApplyUpdateTestAssemblyName Include="@(ApplyUpdateTestProjectReference->'%(FileName).dll')" /> <ResolvedFileToPublishNoDirName Include="%(ResolvedFileToPublish.FileName)%(ResolvedFileToPublish.Extension)"> <ResolvedFileToPublish>%(ResolvedFileToPublish.FullPath)</ResolvedFileToPublish> </ResolvedFileToPublishNoDirName> <ResolvedApplyUpdateAssembly Include="@(ResolvedFileToPublishNoDirName)" Condition="'@(ResolvedFileToPublishNoDirName)' == '@(ApplyUpdateTestAssemblyName)' and %(Identity) != ''" /> <!-- Don't let the IL linker modify EnC test assemblies --> <TrimmerRootAssembly Include="%(ResolvedApplyUpdateAssembly.ResolvedFileToPublish)" /> </ItemGroup> </Target> <Target Name="IncludeDeltasInWasmBundle" BeforeTargets="PrepareForWasmBuildApp" Condition="'$(TargetOS)' == 'Browser'"> <ItemGroup> <!-- FIXME: this belongs in eng/testing/tests.wasm.targets --> <!-- FIXME: Can we do something on the Content items in the referenced projects themselves to get this for free? --> <WasmFilesToIncludeInFileSystem Include="@(PublishItemsOutputGroupOutputs)" Condition="$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.dmeta'))" /> <WasmFilesToIncludeInFileSystem Include="@(PublishItemsOutputGroupOutputs)" Condition="$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.dil'))" /> <WasmFilesToIncludeInFileSystem Include="@(PublishItemsOutputGroupOutputs)" Condition="$([System.String]::new('%(PublishItemsOutputGroupOutputs.Identity)').EndsWith('.dpdb'))" /> </ItemGroup> </Target> </Project>
1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/mono/mono/component/hot_reload.c
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #include <config.h> #include <glib.h> #include <config.h> #include "mono/utils/mono-compiler.h" #include "mono/component/hot_reload-internals.h" #include <glib.h> #include "mono/metadata/assembly-internals.h" #include "mono/metadata/mono-hash-internals.h" #include "mono/metadata/metadata-internals.h" #include "mono/metadata/metadata-update.h" #include "mono/metadata/object-internals.h" #include "mono/metadata/tokentype.h" #include "mono/utils/mono-coop-mutex.h" #include "mono/utils/mono-error-internals.h" #include "mono/utils/mono-lazy-init.h" #include "mono/utils/mono-logger-internals.h" #include "mono/utils/mono-path.h" #include "mono/metadata/debug-internals.h" #include "mono/metadata/mono-debug.h" #include "mono/metadata/debug-mono-ppdb.h" #include "mono/utils/bsearch.h" #include <mono/component/hot_reload.h> #include <mono/utils/mono-compiler.h> #define ALLOW_CLASS_ADD #define ALLOW_METHOD_ADD #define ALLOW_FIELD_ADD typedef struct _BaselineInfo BaselineInfo; typedef struct _DeltaInfo DeltaInfo; static void hot_reload_init (void); static bool hot_reload_available (void); static void hot_reload_set_fastpath_data (MonoMetadataUpdateData *data); static gboolean hot_reload_update_enabled (int *modifiable_assemblies_out); static gboolean hot_reload_no_inline (MonoMethod *caller, MonoMethod *callee); static uint32_t hot_reload_thread_expose_published (void); static uint32_t hot_reload_get_thread_generation (void); static void hot_reload_cleanup_on_close (MonoImage *image); static void hot_reload_effective_table_slow (const MonoTableInfo **t, int idx); static void hot_reload_apply_changes (int origin, MonoImage *base_image, gconstpointer dmeta, uint32_t dmeta_len, gconstpointer dil, uint32_t dil_len, gconstpointer dpdb_bytes_orig, uint32_t dpdb_length, MonoError *error); static int hot_reload_relative_delta_index (MonoImage *image_dmeta, DeltaInfo *delta_info, int token); static void hot_reload_close_except_pools_all (MonoImage *base_image); static void hot_reload_close_all (MonoImage *base_image); static gpointer hot_reload_get_updated_method_rva (MonoImage *base_image, uint32_t idx); static gboolean hot_reload_table_bounds_check (MonoImage *base_image, int table_index, int token_index); static gboolean hot_reload_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, uint32_t orig_index, MonoImage **image_out, uint32_t *index_out); static gpointer hot_reload_get_updated_method_ppdb (MonoImage *base_image, uint32_t idx); static gboolean hot_reload_has_modified_rows (const MonoTableInfo *table); static int hot_reload_table_num_rows_slow (MonoImage *image, int table_index); static GSList* hot_reload_get_added_members (MonoClass *klass); static uint32_t hot_reload_method_parent (MonoImage *base, uint32_t method_token); static void* hot_reload_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer); static uint32_t hot_reload_field_parent (MonoImage *base, uint32_t field_token); static uint32_t hot_reload_get_field_idx (MonoClassField *field); static MonoClassField * hot_reload_get_field (MonoClass *klass, uint32_t fielddef_token); static gpointer hot_reload_get_static_field_addr (MonoClassField *field); static MonoMethod * hot_reload_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error); static MonoClassMetadataUpdateField * metadata_update_field_setup_basic_info_and_resolve (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, DeltaInfo *delta_info, MonoClass *parent_klass, uint32_t fielddef_token, MonoError *error); static MonoComponentHotReload fn_table = { { MONO_COMPONENT_ITF_VERSION, &hot_reload_available }, &hot_reload_set_fastpath_data, &hot_reload_update_enabled, &hot_reload_no_inline, &hot_reload_thread_expose_published, &hot_reload_get_thread_generation, &hot_reload_cleanup_on_close, &hot_reload_effective_table_slow, &hot_reload_apply_changes, &hot_reload_close_except_pools_all, &hot_reload_close_all, &hot_reload_get_updated_method_rva, &hot_reload_table_bounds_check, &hot_reload_delta_heap_lookup, &hot_reload_get_updated_method_ppdb, &hot_reload_has_modified_rows, &hot_reload_table_num_rows_slow, &hot_reload_method_parent, &hot_reload_metadata_linear_search, &hot_reload_field_parent, &hot_reload_get_field_idx, &hot_reload_get_field, &hot_reload_get_static_field_addr, &hot_reload_find_method_by_name, }; MonoComponentHotReload * mono_component_hot_reload_init (void) { hot_reload_init (); return &fn_table; } static bool hot_reload_available (void) { return true; } static MonoMetadataUpdateData* metadata_update_data_ptr; static void hot_reload_set_fastpath_data (MonoMetadataUpdateData *ptr) { metadata_update_data_ptr = ptr; } /* TLS value is a uint32_t of the latest published generation that the thread can see */ static MonoNativeTlsKey exposed_generation_id; #if 1 #define UPDATE_DEBUG(stmt) do { stmt; } while (0) #else #define UPDATE_DEBUG(stmt) /*empty */ #endif /* For each delta image, for each table: * - the total logical number of rows for the previous generation * - the number of modified rows in the current generation * - the number of inserted rows in the current generation * * In each delta, the physical tables contain the rows that modify existing rows of a prior generation, * followed by inserted rows. * https://github.com/dotnet/runtime/blob/6072e4d3a7a2a1493f514cdf4be75a3d56580e84/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs#L324 * * The total logical number of rows in a table for a particular generation is * prev_gen_rows + inserted_rows. */ typedef struct _delta_row_count { guint32 prev_gen_rows; guint32 modified_rows; guint32 inserted_rows; } delta_row_count; /* Additional informaiton for MonoImages representing deltas */ struct _DeltaInfo { uint32_t generation; /* global update ID that added this delta image */ MonoImage *delta_image; /* DeltaInfo doesn't own the image, the base MonoImage owns the reference */ /* Maps MethodDef token indices to a pointer into the RVA of the delta IL */ GHashTable *method_table_update; /* Maps MethodDef token indices to a pointer into the RVA of the delta PPDB */ GHashTable *method_ppdb_table_update; // for each table, the row in the EncMap table that has the first token for remapping it? uint32_t enc_recs [MONO_TABLE_NUM]; delta_row_count count [MONO_TABLE_NUM]; MonoPPDBFile *ppdb_file; MonoMemPool *pool; /* mutated tables are allocated here */ MonoTableInfo mutants[MONO_TABLE_NUM]; }; /* Additional informaiton for baseline MonoImages */ struct _BaselineInfo { /* List of DeltaInfos of deltas*/ GList *delta_info; /* Tail of delta_info for fast appends */ GList *delta_info_last; /* Maps MethodDef token indices to a boolean flag that there's an update for the method */ GHashTable *method_table_update; /* TRUE if any published update modified an existing row */ gboolean any_modified_rows [MONO_TABLE_NUM]; /* A list of MonoClassMetadataUpdateInfo* that need to be cleaned up */ GSList *klass_info; /* Parents for added methods, fields, etc */ GHashTable *member_parent; /* maps added methoddef or fielddef tokens to typedef tokens */ }; #define DOTNET_MODIFIABLE_ASSEMBLIES "DOTNET_MODIFIABLE_ASSEMBLIES" /* See Note: Suppressed Columns */ static guint16 m_SuppressedDeltaColumns [MONO_TABLE_NUM]; /** * mono_metadata_update_enable: * \param modifiable_assemblies_out: set to MonoModifiableAssemblies value * * Returns \c TRUE if metadata updates are enabled at runtime. False otherwise. * * If \p modifiable_assemblies_out is not \c NULL, it's set on return. * * The result depends on the value of the DOTNET_MODIFIABLE_ASSEMBLIES * environment variable. "debug" means debuggable assemblies are modifiable, * all other values are ignored and metadata updates are disabled. */ gboolean hot_reload_update_enabled (int *modifiable_assemblies_out) { static gboolean inited = FALSE; static int modifiable = MONO_MODIFIABLE_ASSM_NONE; if (!inited) { char *val = g_getenv (DOTNET_MODIFIABLE_ASSEMBLIES); if (val && !g_strcasecmp (val, "debug")) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Metadata update enabled for debuggable assemblies"); modifiable = MONO_MODIFIABLE_ASSM_DEBUG; } g_free (val); inited = TRUE; } if (modifiable_assemblies_out) *modifiable_assemblies_out = modifiable; return modifiable != MONO_MODIFIABLE_ASSM_NONE; } static gboolean assembly_update_supported (MonoAssembly *assm) { int modifiable = 0; if (!hot_reload_update_enabled (&modifiable)) return FALSE; if (modifiable == MONO_MODIFIABLE_ASSM_DEBUG && mono_assembly_is_jit_optimizer_disabled (assm)) return TRUE; return FALSE; } /** * hot_reload_update_no_inline: * \param caller: the calling method * \param callee: the method being called * * Returns \c TRUE if \p callee should not be inlined into \p caller. * * If metadata updates are enabled either for the caller or callee's module, * the callee should not be inlined. * */ gboolean hot_reload_no_inline (MonoMethod *caller, MonoMethod *callee) { if (!hot_reload_update_enabled (NULL)) return FALSE; MonoAssembly *caller_assm = m_class_get_image(caller->klass)->assembly; MonoAssembly *callee_assm = m_class_get_image(callee->klass)->assembly; return mono_assembly_is_jit_optimizer_disabled (caller_assm) || mono_assembly_is_jit_optimizer_disabled (callee_assm); } /* Maps each MonoTableInfo* to the MonoImage that it belongs to. This is * mapping the base image MonoTableInfos to the base MonoImage. We don't need * this for deltas. */ static GHashTable *table_to_image; /* Maps each delta MonoImage to its DeltaInfo. Doesn't own the DeltaInfo or the images */ static GHashTable *delta_image_to_info; /* Maps each baseline MonoImage to its BaselineInfo */ static GHashTable *baseline_image_to_info; /* Low-level lock to protects table_to_image and delta_image_to_info */ /* FIXME: use concurrent hash tables so that readers don't have to lock. */ static MonoCoopMutex table_to_image_mutex; static void table_to_image_lock (void) { mono_coop_mutex_lock (&table_to_image_mutex); } static void table_to_image_unlock (void) { mono_coop_mutex_unlock (&table_to_image_mutex); } static BaselineInfo * baseline_info_init (MonoImage *image_base) { BaselineInfo *baseline_info = g_malloc0 (sizeof (BaselineInfo)); return baseline_info; } static void klass_info_destroy (gpointer value, gpointer user_data G_GNUC_UNUSED) { MonoClassMetadataUpdateInfo *info = (MonoClassMetadataUpdateInfo *)value; /* added_members is allocated from the class mempool, don't free it here */ /* The MonoClassMetadataUpdateField is allocated from the class mempool, don't free it here */ g_ptr_array_free (info->added_fields, TRUE); if (info->runtime.static_fields) { mono_g_hash_table_destroy (info->runtime.static_fields); info->runtime.static_fields = NULL; } mono_coop_mutex_destroy (&info->runtime.static_fields_lock); /* The MonoClassMetadataUpdateInfo itself is allocated from the class mempool, don't free it here */ } static void baseline_info_destroy (BaselineInfo *info) { if (info->method_table_update) g_hash_table_destroy (info->method_table_update); if (info->klass_info) { g_slist_foreach (info->klass_info, klass_info_destroy, NULL); g_slist_free (info->klass_info); } g_free (info); } static BaselineInfo * baseline_info_lookup_or_add (MonoImage *base_image) { BaselineInfo *info; table_to_image_lock (); info = g_hash_table_lookup (baseline_image_to_info, base_image); if (!info) { info = baseline_info_init (base_image); g_hash_table_insert (baseline_image_to_info, base_image, info); } table_to_image_unlock (); return info; } static void baseline_info_remove (MonoImage *base_image) { table_to_image_lock (); g_hash_table_remove (baseline_image_to_info, base_image); table_to_image_unlock (); } static BaselineInfo * baseline_info_lookup (MonoImage *base_image) { BaselineInfo *info; table_to_image_lock (); info = g_hash_table_lookup (baseline_image_to_info, base_image); table_to_image_unlock (); return info; } static DeltaInfo* delta_info_init (MonoImage *image_dmeta, MonoImage *image_base, MonoPPDBFile *ppdb_file, BaselineInfo *base_info, uint32_t generation, DeltaInfo **prev_last_delta); static void free_ppdb_entry (gpointer key, gpointer val, gpointer user_data) { g_free (val); } static void delta_info_destroy (DeltaInfo *dinfo) { if (dinfo->method_table_update) g_hash_table_destroy (dinfo->method_table_update); if (dinfo->method_ppdb_table_update) { g_hash_table_foreach (dinfo->method_ppdb_table_update, free_ppdb_entry, NULL); g_hash_table_destroy (dinfo->method_ppdb_table_update); } mono_ppdb_close (dinfo->ppdb_file); if (dinfo->pool) mono_mempool_destroy (dinfo->pool); g_free (dinfo); } static DeltaInfo * delta_info_lookup_locked (MonoImage *delta_image) { return (DeltaInfo*)g_hash_table_lookup (delta_image_to_info, delta_image); } static DeltaInfo * delta_info_lookup (MonoImage *delta_image) { DeltaInfo *result; table_to_image_lock (); result = delta_info_lookup_locked (delta_image); g_assert (!result || result->delta_image == delta_image); table_to_image_unlock (); return result; } static void table_to_image_init (void) { mono_coop_mutex_init (&table_to_image_mutex); table_to_image = g_hash_table_new (NULL, NULL); delta_image_to_info = g_hash_table_new (NULL, NULL); baseline_image_to_info = g_hash_table_new (NULL, NULL); } static gboolean remove_base_image (gpointer key, gpointer value, gpointer user_data) { MonoImage *base_image = (MonoImage*)user_data; MonoImage *value_image = (MonoImage*)value; return (value_image == base_image); } void hot_reload_cleanup_on_close (MonoImage *image) { table_to_image_lock (); /* remove all keys (delta images) that map to the given image (base image) */ g_hash_table_foreach_remove (table_to_image, remove_base_image, (gpointer)image); table_to_image_unlock (); } void hot_reload_close_except_pools_all (MonoImage *base_image) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return; for (GList *ptr = info->delta_info; ptr; ptr = ptr->next) { DeltaInfo *info = (DeltaInfo *)ptr->data; MonoImage *image = info->delta_image; if (image) { table_to_image_lock (); g_hash_table_remove (delta_image_to_info, image); table_to_image_unlock (); /* if for some reason the image has other references, break the link to this delta_info that is going away */ if (!mono_image_close_except_pools (image)) info->delta_image = NULL; } } } void hot_reload_close_all (MonoImage *base_image) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return; for (GList *ptr = info->delta_info; ptr; ptr = ptr->next) { DeltaInfo *info = (DeltaInfo *)ptr->data; if (!info) continue; MonoImage *image = info->delta_image; if (image) { mono_image_close_finish (image); } delta_info_destroy (info); ptr->data = NULL; } g_list_free (info->delta_info); baseline_info_remove (base_image); baseline_info_destroy (info); } static void table_to_image_add (MonoImage *base_image) { /* If at least one table from this image is already here, they all are */ if (g_hash_table_contains (table_to_image, &base_image->tables[MONO_TABLE_MODULE])) return; table_to_image_lock (); if (g_hash_table_contains (table_to_image, &base_image->tables[MONO_TABLE_MODULE])) { table_to_image_unlock (); return; } for (int idx = 0; idx < MONO_TABLE_NUM; ++idx) { MonoTableInfo *table = &base_image->tables[idx]; g_hash_table_insert (table_to_image, table, base_image); } table_to_image_unlock (); } static MonoImage * table_info_get_base_image (const MonoTableInfo *t) { MonoImage *image = (MonoImage *) g_hash_table_lookup (table_to_image, t); return image; } /* Given a table, find the base image that it came from and its table index */ static gboolean table_info_find_in_base (const MonoTableInfo *table, MonoImage **base_out, int *tbl_index) { g_assert (base_out); *base_out = NULL; MonoImage *base = table_info_get_base_image (table); if (!base) return FALSE; *base_out = base; /* Invariant: `table` must be a `MonoTableInfo` of the base image. */ g_assert (base->tables < table && table < &base->tables [MONO_TABLE_LAST]); if (tbl_index) { size_t s = ALIGN_TO (sizeof (MonoTableInfo), sizeof (gpointer)); *tbl_index = ((intptr_t) table - (intptr_t) base->tables) / s; } return TRUE; } static MonoImage* image_open_dmeta_from_data (MonoImage *base_image, uint32_t generation, gconstpointer dmeta_bytes, uint32_t dmeta_length); static DeltaInfo* image_append_delta (MonoImage *base, BaselineInfo *base_info, MonoImage *delta, DeltaInfo *delta_info); /* common method, don't use directly, use add_method_to_baseline, add_field_to_baseline, etc */ static void add_member_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t member_token); static void add_method_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t method_token, MonoDebugInformationEnc* pdb_address); static void add_field_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t field_token); void hot_reload_init (void) { table_to_image_init (); mono_native_tls_alloc (&exposed_generation_id, NULL); /* See CMiniMdRW::ApplyDelta in metamodelenc.cpp in CoreCLR */ m_SuppressedDeltaColumns[MONO_TABLE_EVENTMAP] = (1 << MONO_EVENT_MAP_EVENTLIST); m_SuppressedDeltaColumns[MONO_TABLE_PROPERTYMAP] = (1 << MONO_PROPERTY_MAP_PROPERTY_LIST); m_SuppressedDeltaColumns[MONO_TABLE_METHOD] = (1 << MONO_METHOD_PARAMLIST); m_SuppressedDeltaColumns[MONO_TABLE_TYPEDEF] = (1 << MONO_TYPEDEF_FIELD_LIST)|(1<<MONO_TYPEDEF_METHOD_LIST); } static void hot_reload_update_published_invoke_hook (MonoAssemblyLoadContext *alc, uint32_t generation) { if (mono_get_runtime_callbacks ()->metadata_update_published) mono_get_runtime_callbacks ()->metadata_update_published (alc, generation); } static uint32_t update_published, update_alloc_frontier; static MonoCoopMutex publish_mutex; static void publish_lock (void) { mono_coop_mutex_lock (&publish_mutex); } static void publish_unlock (void) { mono_coop_mutex_unlock (&publish_mutex); } static mono_lazy_init_t metadata_update_lazy_init; static void initialize (void) { mono_coop_mutex_init (&publish_mutex); } static void thread_set_exposed_generation (uint32_t value) { mono_native_tls_set_value (exposed_generation_id, GUINT_TO_POINTER((guint)value)); } /** * LOCKING: assumes the publish_lock is held */ static void hot_reload_set_has_updates (void) { g_assert (metadata_update_data_ptr != NULL); metadata_update_data_ptr->has_updates = 1; } static uint32_t hot_reload_update_prepare (void) { mono_lazy_initialize (&metadata_update_lazy_init, initialize); /* * TODO: assert that the updater isn't depending on current metadata, else publishing might block. */ publish_lock (); uint32_t alloc_gen = ++update_alloc_frontier; /* Have to set this here so the updater starts using the slow path of metadata lookups */ hot_reload_set_has_updates (); /* Expose the alloc frontier to the updater thread */ thread_set_exposed_generation (alloc_gen); return alloc_gen; } static gboolean G_GNUC_UNUSED hot_reload_update_available (void) { return update_published < update_alloc_frontier; } /** * hot_reaload_thread_expose_published: * * Allow the current thread to see the latest published deltas. * * Returns the current published generation that the thread will see. */ uint32_t hot_reload_thread_expose_published (void) { mono_memory_read_barrier (); uint32_t thread_current_gen = update_published; thread_set_exposed_generation (thread_current_gen); return thread_current_gen; } /** * hot_reload_get_thread_generation: * * Return the published generation that the current thread is allowed to see. * May be behind the latest published generation if the thread hasn't called * \c mono_metadata_update_thread_expose_published in a while. */ uint32_t hot_reload_get_thread_generation (void) { return (uint32_t)GPOINTER_TO_UINT(mono_native_tls_get_value(exposed_generation_id)); } static gboolean G_GNUC_UNUSED hot_reload_wait_for_update (uint32_t timeout_ms) { /* TODO: give threads a way to voluntarily wait for an update to be published. */ g_assert_not_reached (); } static void hot_reload_update_publish (MonoAssemblyLoadContext *alc, uint32_t generation) { g_assert (update_published < generation && generation <= update_alloc_frontier); /* TODO: wait for all threads that are using old metadata to update. */ hot_reload_update_published_invoke_hook (alc, generation); update_published = update_alloc_frontier; mono_memory_write_barrier (); publish_unlock (); } static void hot_reload_update_cancel (uint32_t generation) { g_assert (update_alloc_frontier == generation); g_assert (update_alloc_frontier > 0); g_assert (update_alloc_frontier - 1 >= update_published); --update_alloc_frontier; /* Roll back exposed generation to the last published one */ thread_set_exposed_generation (update_published); publish_unlock (); } static void add_class_info_to_baseline (MonoClass *klass, MonoClassMetadataUpdateInfo *klass_info) { MonoImage *image = m_class_get_image (klass); BaselineInfo *baseline_info = baseline_info_lookup (image); baseline_info->klass_info = g_slist_prepend (baseline_info->klass_info, klass_info); } static MonoClassMetadataUpdateInfo * mono_class_get_or_add_metadata_update_info (MonoClass *klass) { MonoClassMetadataUpdateInfo *info = NULL; info = mono_class_get_metadata_update_info (klass); if (info) return info; mono_loader_lock (); info = mono_class_get_metadata_update_info (klass); if (!info) { info = mono_class_alloc0 (klass, sizeof (MonoClassMetadataUpdateInfo)); add_class_info_to_baseline (klass, info); mono_class_set_metadata_update_info (klass, info); } mono_loader_unlock (); g_assert (info); return info; } /* * Given a baseline and an (optional) previous delta, allocate space for new tables for the current delta. * * Assumes the DeltaInfo:count info has already been calculated and initialized. */ static void delta_info_initialize_mutants (const MonoImage *base, const BaselineInfo *base_info, const DeltaInfo *prev_delta, DeltaInfo *delta) { g_assert (delta->pool); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Initializing mutant tables for image %p (generation %d)", base, delta->generation); for (int i = 0; i < MONO_TABLE_NUM; ++i) { gboolean need_copy = FALSE; /* if any generation modified any row of this table, make a copy for the current generation. */ if (base_info->any_modified_rows [i]) need_copy = TRUE; delta_row_count *count = &delta->count [i]; guint32 base_rows = table_info_get_rows (&base->tables [i]); /* if some previous generation added rows, or we're adding rows, make a copy */ if (base_rows != count->prev_gen_rows || count->inserted_rows) need_copy = TRUE; if (!need_copy) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, " Table 0x%02x unchanged (rows: base %d, prev %d, inserted %d), not copied", i, base_rows, count->prev_gen_rows, count->inserted_rows); continue; } else { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, " Table 0x%02x changed (rows: base %d, prev %d, inserted %d), IS copied", i, base_rows, count->prev_gen_rows, count->inserted_rows); } /* The invariant is that once we made a copy in any previous generation, we'll make * a copy in this generation. So subsequent generations can copy either from the * immediately preceeding generation or from the baseline if the preceeding * generation didn't make a copy. */ guint32 rows = count->prev_gen_rows + count->inserted_rows; const MonoTableInfo *prev_table; if (!prev_delta || prev_delta->mutants [i].base == NULL) prev_table = &base->tables [i]; else prev_table = &prev_delta->mutants [i]; g_assert (prev_table != NULL); MonoTableInfo *tbl = &delta->mutants [i]; if (prev_table->rows_ == 0) { /* table was empty in the baseline and it was empty in the prior generation, but now we have some rows. Use the format of the mutant table. */ g_assert (prev_table->row_size == 0); tbl->row_size = delta->delta_image->tables [i].row_size; tbl->size_bitfield = delta->delta_image->tables [i].size_bitfield; } else { tbl->row_size = prev_table->row_size; tbl->size_bitfield = prev_table->size_bitfield; } tbl->rows_ = rows; g_assert (tbl->rows_ > 0 && tbl->row_size != 0); tbl->base = mono_mempool_alloc (delta->pool, tbl->row_size * rows); g_assert (table_info_get_rows (prev_table) == count->prev_gen_rows); /* copy the old rows and zero out the new ones */ memcpy ((char*)tbl->base, prev_table->base, count->prev_gen_rows * tbl->row_size); memset (((char*)tbl->base) + count->prev_gen_rows * tbl->row_size, 0, count->inserted_rows * tbl->row_size); } } /** * LOCKING: Assumes the publish_lock is held * Returns: The previous latest delta, or NULL if this is the first delta */ DeltaInfo * image_append_delta (MonoImage *base, BaselineInfo *base_info, MonoImage *delta, DeltaInfo *delta_info) { if (!base_info->delta_info) { base_info->delta_info = base_info->delta_info_last = g_list_alloc (); base_info->delta_info->data = (gpointer)delta_info; mono_memory_write_barrier (); /* Have to set this here so that passes over the metadata in the updater thread start using the slow path */ base->has_updates = TRUE; return NULL; } DeltaInfo *prev_last_delta = (DeltaInfo*)base_info->delta_info_last->data; g_assert (prev_last_delta->generation < delta_info->generation); /* g_list_append returns the given list, not the newly appended */ GList *l = g_list_append (base_info->delta_info_last, delta_info); g_assert (l != NULL && l->next != NULL && l->next->next == NULL); base_info->delta_info_last = l->next; mono_memory_write_barrier (); /* Have to set this here so that passes over the metadata in the updater thread start using the slow path */ base->has_updates = TRUE; return prev_last_delta; } /** * LOCKING: assumes the publish_lock is held */ MonoImage* image_open_dmeta_from_data (MonoImage *base_image, uint32_t generation, gconstpointer dmeta_bytes, uint32_t dmeta_length) { MonoImageOpenStatus status; MonoAssemblyLoadContext *alc = mono_image_get_alc (base_image); MonoImage *dmeta_image = mono_image_open_from_data_internal (alc, (char*)dmeta_bytes, dmeta_length, TRUE, &status, TRUE, NULL, NULL); g_assert (dmeta_image != NULL); g_assert (status == MONO_IMAGE_OK); return dmeta_image; } static gpointer open_dil_data (MonoImage *base_image G_GNUC_UNUSED, gconstpointer dil_src, uint32_t dil_length) { /* TODO: find a better memory manager. But this way we at least won't lose the IL data. */ MonoMemoryManager *mem_manager = (MonoMemoryManager *)mono_alc_get_default ()->memory_manager; gpointer dil_copy = mono_mem_manager_alloc (mem_manager, dil_length); memcpy (dil_copy, dil_src, dil_length); return dil_copy; } static const char * scope_to_string (uint32_t tok) { const char *scope; switch (tok & MONO_RESOLUTION_SCOPE_MASK) { case MONO_RESOLUTION_SCOPE_MODULE: scope = "."; break; case MONO_RESOLUTION_SCOPE_MODULEREF: scope = "M"; break; case MONO_RESOLUTION_SCOPE_TYPEREF: scope = "T"; break; case MONO_RESOLUTION_SCOPE_ASSEMBLYREF: scope = "A"; break; default: g_assert_not_reached (); } return scope; } static void dump_update_summary (MonoImage *image_base, MonoImage *image_dmeta) { int rows; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta tables:"); for (int idx = 0; idx < MONO_TABLE_NUM; ++idx) { if (image_dmeta->tables [idx].base) mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "\t0x%02x \"%s\"", idx, mono_meta_table_name (idx)); } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); rows = mono_image_get_table_rows (image_base, MONO_TABLE_TYPEREF); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_TYPEREF_SIZE]; mono_metadata_decode_row (&image_base->tables [MONO_TABLE_TYPEREF], i - 1, cols, MONO_TYPEREF_SIZE); const char *scope = scope_to_string (cols [MONO_TYPEREF_SCOPE]); const char *name = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAME]); const char *nspace = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAMESPACE]); if (!name) name = "<N/A>"; if (!nspace) nspace = "<N/A>"; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base typeref i=%d (token=0x%08x) -> scope=%s, namespace=%s, name=%s", i, MONO_TOKEN_TYPE_REF | i, scope, nspace, name); } if (!image_dmeta->minimal_delta) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "--------------------------------"); rows = mono_image_get_table_rows (image_dmeta, MONO_TABLE_TYPEREF); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_TYPEREF_SIZE]; mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_TYPEREF], i - 1, cols, MONO_TYPEREF_SIZE); const char *scope = scope_to_string (cols [MONO_TYPEREF_SCOPE]); const char *name = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAME]); const char *nspace = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAMESPACE]); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta typeref i=%d (token=0x%08x) -> scope=%s, nspace=%s, name=%s", i, MONO_TOKEN_TYPE_REF | i, scope, nspace, name); } } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); rows = mono_image_get_table_rows (image_base, MONO_TABLE_METHOD); for (int i = 1; i <= rows ; ++i) { guint32 cols [MONO_METHOD_SIZE]; mono_metadata_decode_row_raw (&image_base->tables [MONO_TABLE_METHOD], i - 1, cols, MONO_METHOD_SIZE); const char *name = mono_metadata_string_heap (image_base, cols [MONO_METHOD_NAME]); guint32 rva = cols [MONO_METHOD_RVA]; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base method i=%d (token=0x%08x), rva=%d/0x%04x, name=%s", i, MONO_TOKEN_METHOD_DEF | i, rva, rva, name); } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "--------------------------------"); rows = mono_image_get_table_rows (image_dmeta, MONO_TABLE_METHOD); for (int i = 1; i <= rows ; ++i) { guint32 cols [MONO_METHOD_SIZE]; mono_metadata_decode_row_raw (&image_dmeta->tables [MONO_TABLE_METHOD], i - 1, cols, MONO_METHOD_SIZE); const char *name = mono_metadata_string_heap (image_base, cols [MONO_METHOD_NAME]); guint32 rva = cols [MONO_METHOD_RVA]; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta method i=%d (token=0x%08x), rva=%d/0x%04x, name=%s", i, MONO_TOKEN_METHOD_DEF | i, rva, rva, name); } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); rows = mono_image_get_table_rows (image_base, MONO_TABLE_STANDALONESIG); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE]; mono_metadata_decode_row (&image_base->tables [MONO_TABLE_STANDALONESIG], i - 1, cols, MONO_STAND_ALONE_SIGNATURE_SIZE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base standalonesig i=%d (token=0x%08x) -> 0x%08x", i, MONO_TOKEN_SIGNATURE | i, cols [MONO_STAND_ALONE_SIGNATURE]); } if (!image_dmeta->minimal_delta) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "--------------------------------"); rows = mono_image_get_table_rows (image_dmeta, MONO_TABLE_STANDALONESIG); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE]; mono_metadata_decode_row_raw (&image_dmeta->tables [MONO_TABLE_STANDALONESIG], i - 1, cols, MONO_STAND_ALONE_SIGNATURE_SIZE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta standalonesig i=%d (token=0x%08x) -> 0x%08x", i, MONO_TOKEN_SIGNATURE | i, cols [MONO_STAND_ALONE_SIGNATURE]); } } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); } /* * Finds the latest mutated version of the table given by tbl_index * * On success returns TRUE, modifies *t and optionally updates *delta_out */ static gboolean effective_table_mutant (MonoImage *base, BaselineInfo *info, int tbl_index, const MonoTableInfo **t, DeltaInfo **delta_out) { GList *ptr =info->delta_info_last; uint32_t exposed_gen = hot_reload_get_thread_generation (); MonoImage *dmeta = NULL; DeltaInfo *delta_info = NULL; /* walk backward from the latest image until we find one that matches the current thread's exposed generation */ do { delta_info = (DeltaInfo*)ptr->data; dmeta = delta_info->delta_image; if (delta_info->generation <= exposed_gen) break; ptr = ptr->prev; } while (ptr); if (!ptr) return FALSE; g_assert (dmeta != NULL); g_assert (delta_info != NULL); *t = &delta_info->mutants [tbl_index]; if (delta_out) *delta_out = delta_info; return TRUE; } void hot_reload_effective_table_slow (const MonoTableInfo **t, int idx) { /* FIXME: don't let any thread other than the updater thread see values from a delta image * with a generation past update_published */ MonoImage *base; int tbl_index; if (!table_info_find_in_base (*t, &base, &tbl_index)) return; BaselineInfo *info = baseline_info_lookup (base); if (!info) return; gboolean success = effective_table_mutant (base, info, tbl_index, t, NULL); g_assert (success); } /* * The ENCMAP table contains the base of the relative offset. * * Returns -1 if the token does not resolve in this generation's ENCMAP. * * Example: * Say you have a base image with a METHOD table having 5 entries. The minimal * delta image adds another one, so it would be indexed with token * `MONO_TOKEN_METHOD_DEF | 6`. However, the minimal delta image only has this * single entry, and thus this would be an out-of-bounds access. That's where * the ENCMAP table comes into play: It will have an entry * `MONO_TOKEN_METHOD_DEF | 5`, so before accessing the new entry in the * minimal delta image, it has to be substracted. Thus the new relative index * is `1`, and no out-of-bounds acccess anymore. * * One can assume that ENCMAP is sorted (todo: verify this claim). * * BTW, `enc_recs` is just a pre-computed map to make the lookup for the * relative index faster. */ int hot_reload_relative_delta_index (MonoImage *image_dmeta, DeltaInfo *delta_info, int token) { MonoTableInfo *encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; int table = mono_metadata_token_table (token); int index = mono_metadata_token_index (token); int index_map = delta_info->enc_recs [table]; int encmap_rows = table_info_get_rows (encmap); if (!table_info_get_rows (encmap) || !image_dmeta->minimal_delta) return mono_metadata_token_index (token); /* if the table didn't have any updates in this generation and the * table index is bigger than the last table that got updates, * enc_recs will point past the last row */ if (index_map - 1 == encmap_rows) return -1; guint32 cols[MONO_ENCMAP_SIZE]; mono_metadata_decode_row (encmap, index_map - 1, cols, MONO_ENCMAP_SIZE); int map_entry = cols [MONO_ENCMAP_TOKEN]; /* we're looking at the beginning of a sequence of encmap rows that are all the * modifications+additions for the table we are looking for (or we're looking at an entry * for the next table after the one we wanted). the map entries will have tokens in * increasing order. skip over the rows where the tokens are not the one we want, until we * hit the rows for the next table or we hit the end of the encmap */ while (mono_metadata_token_table (map_entry) == table && mono_metadata_token_index (map_entry) < index && index_map < encmap_rows) { mono_metadata_decode_row (encmap, ++index_map - 1, cols, MONO_ENCMAP_SIZE); map_entry = cols [MONO_ENCMAP_TOKEN]; } if (mono_metadata_token_table (map_entry) == table) { if (mono_metadata_token_index (map_entry) == index) { /* token resolves to this generation */ int return_val = index_map - delta_info->enc_recs [table] + 1; g_assert (return_val > 0 && return_val <= table_info_get_rows (&image_dmeta->tables[table])); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "relative index for token 0x%08x -> table 0x%02x row 0x%08x", token, table, return_val); return return_val; } else { /* Otherwise we stopped either: because we saw an an entry for a row after * the one we wanted - we were looking for a modification, but the encmap * has an addition; or, because we saw the last entry in the encmap and it * still wasn't for a row as high as the one we wanted. either way, the * update we want is not in the delta we're looking at. */ g_assert ((mono_metadata_token_index (map_entry) > index) || (mono_metadata_token_index (map_entry) < index && index_map == encmap_rows)); return -1; } } else { /* otherwise there are no more encmap entries for this table, and we didn't see the * index, so there was no modification/addition for that index in this delta. */ g_assert (mono_metadata_token_table (map_entry) > table); return -1; } } /* LOCKING: assumes publish_lock is held */ static DeltaInfo* delta_info_init (MonoImage *image_dmeta, MonoImage *image_base, MonoPPDBFile *ppdb_file, BaselineInfo *base_info, uint32_t generation, DeltaInfo **prev_delta_info) { MonoTableInfo *encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; g_assert (!delta_info_lookup (image_dmeta)); if (!table_info_get_rows (encmap)) return NULL; DeltaInfo *delta_info = g_malloc0 (sizeof (DeltaInfo)); delta_info->generation = generation; delta_info->ppdb_file = ppdb_file; delta_info->delta_image = image_dmeta; table_to_image_lock (); g_hash_table_insert (delta_image_to_info, image_dmeta, delta_info); table_to_image_unlock (); delta_info->pool = mono_mempool_new (); g_assert (prev_delta_info); /* base_image takes ownership of 1 refcount ref of dmeta_image */ *prev_delta_info = image_append_delta (image_base, base_info, image_dmeta, delta_info); return delta_info; } /* LOCKING: assumes publish_lock is held */ static gboolean delta_info_compute_table_records (MonoImage *image_dmeta, MonoImage *image_base, BaselineInfo *base_info, DeltaInfo *delta_info) { MonoTableInfo *encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; int table, prev_table = -1, idx; /*** Compute logical table sizes ***/ if (base_info->delta_info == base_info->delta_info_last) { /* this is the first update. */ for (int i = 0; i < MONO_TABLE_NUM; ++i) { delta_info->count[i].prev_gen_rows = table_info_get_rows (&image_base->tables[i]); } } else { g_assert (delta_info == (DeltaInfo*)base_info->delta_info_last->data); g_assert (base_info->delta_info_last->prev != NULL); DeltaInfo *prev_gen_info = (DeltaInfo*)base_info->delta_info_last->prev->data; for (int i = 0; i < MONO_TABLE_NUM; ++i) { delta_info->count[i].prev_gen_rows = prev_gen_info->count[i].prev_gen_rows + prev_gen_info->count[i].inserted_rows; } } /* TODO: while going through the tables, update delta_info->count[tbl].{modified,inserted}_rows */ int encmap_rows = table_info_get_rows (encmap); for (idx = 1; idx <= encmap_rows; ++idx) { guint32 cols[MONO_ENCMAP_SIZE]; mono_metadata_decode_row (encmap, idx - 1, cols, MONO_ENCMAP_SIZE); uint32_t tok = cols [MONO_ENCMAP_TOKEN]; table = mono_metadata_token_table (tok); uint32_t rid = mono_metadata_token_index (tok); g_assert (table >= 0 && table < MONO_TABLE_NUM); g_assert (table != MONO_TABLE_ENCLOG); g_assert (table != MONO_TABLE_ENCMAP); g_assert (table >= prev_table); /* FIXME: check bounds - is it < or <=. */ if (rid < delta_info->count[table].prev_gen_rows) { base_info->any_modified_rows[table] = TRUE; delta_info->count[table].modified_rows++; } else delta_info->count[table].inserted_rows++; if (table == prev_table) continue; while (prev_table < table) { prev_table++; delta_info->enc_recs [prev_table] = idx; } } g_assert (prev_table < MONO_TABLE_NUM - 1); while (prev_table < MONO_TABLE_NUM - 1) { prev_table++; delta_info->enc_recs [prev_table] = idx; } if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) { for (int i = 0 ; i < MONO_TABLE_NUM; ++i) { if (!image_dmeta->tables [i].base) continue; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "enc_recs [%02x] / %s = 0x%02x\t(inserted: %03d, modified: %03d)", i, mono_meta_table_name (i), delta_info->enc_recs[i], delta_info->count[i].inserted_rows, delta_info->count[i].modified_rows); } } return TRUE; } enum MonoEnCFuncCode { ENC_FUNC_DEFAULT = 0, ENC_FUNC_ADD_METHOD = 1, ENC_FUNC_ADD_FIELD = 2, ENC_FUNC_ADD_PARAM = 3, ENC_FUNC_ADD_PROPERTY = 4, ENC_FUNC_ADD_EVENT = 5, }; static const char* funccode_to_str (int func_code) { switch (func_code) { case 0: return "Func default"; case 1: return "Method Create"; case 2: return "Field Create"; case 3: return "Param Create"; case 4: return "Property Create"; case 5: return "Event Create"; default: g_assert_not_reached (); } return NULL; } /* * Apply the row from the delta image given by log_token to the cur_delta mutated table. * */ static void delta_info_mutate_row (MonoImage *image_dmeta, DeltaInfo *cur_delta, guint32 log_token) { int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); /* 1-based */ gboolean modified = token_index <= cur_delta->count [token_table].prev_gen_rows; int delta_index = hot_reload_relative_delta_index (image_dmeta, cur_delta, log_token); /* The complication here is that we want the mutant table to look like the table in * the baseline image with respect to column widths, but the delta tables are generally coming in * uncompressed (4-byte columns). So we have to copy one column at a time and adjust the * widths as we go. */ guint32 dst_bitfield = cur_delta->mutants [token_table].size_bitfield; guint32 src_bitfield = image_dmeta->tables [token_table].size_bitfield; const char *src_base = image_dmeta->tables [token_table].base + (delta_index - 1) * image_dmeta->tables [token_table].row_size; char *dst_base = (char*)cur_delta->mutants [token_table].base + (token_index - 1) * cur_delta->mutants [token_table].row_size; guint32 src_offset = 0, dst_offset = 0; for (int col = 0; col < mono_metadata_table_count (dst_bitfield); ++col) { guint32 dst_col_size = mono_metadata_table_size (dst_bitfield, col); guint32 src_col_size = mono_metadata_table_size (src_bitfield, col); if ((m_SuppressedDeltaColumns [token_table] & (1 << col)) == 0) { const char *src = src_base + src_offset; char *dst = dst_base + dst_offset; /* copy src to dst, via a temporary to adjust for size differences */ /* FIXME: unaligned access, endianness */ guint32 tmp; switch (src_col_size) { case 1: tmp = *(guint8*)src; break; case 2: tmp = *(guint16*)src; break; case 4: tmp = *(guint32*)src; break; default: g_assert_not_reached (); } /* FIXME: unaligned access, endianness */ switch (dst_col_size) { case 1: *(guint8*)dst = (guint8)tmp; break; case 2: *(guint16*)dst = (guint16)tmp; break; case 4: *(guint32*)dst = tmp; break; default: g_assert_not_reached (); } } src_offset += src_col_size; dst_offset += dst_col_size; } g_assert (dst_offset == cur_delta->mutants [token_table].row_size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "mutate: table=0x%02x row=0x%04x delta row=0x%04x %s", token_table, token_index, delta_index, modified ? "Mod" : "Add"); } static void prepare_mutated_rows (const MonoTableInfo *table_enclog, MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *delta_info) { int rows = table_info_get_rows (table_enclog); /* Prepare the mutated metadata tables */ for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; if (func_code != ENC_FUNC_DEFAULT) continue; delta_info_mutate_row (image_dmeta, delta_info, log_token); } } /* Run some sanity checks first. If we detect unsupported scenarios, this * function will fail and the metadata update should be aborted. This should * run before anything in the metadata world is updated. */ static gboolean apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *delta_info, gconstpointer dil_data, uint32_t dil_length, MonoError *error) { MonoTableInfo *table_enclog = &image_dmeta->tables [MONO_TABLE_ENCLOG]; int rows = table_info_get_rows (table_enclog); gboolean unsupported_edits = FALSE; /* hack: make a pass over it, looking only for table method updates, in * order to give more meaningful error messages first */ for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); // FIXME: the top bit 0x8000000 of log_token is some kind of // indicator see IsRecId in metamodelrw.cpp and // MDInternalRW::EnumDeltaTokensInit which skips over those // records when EditAndContinueModule::ApplyEditAndContinue is // iterating. int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x (%s idx=0x%02x) (base table has 0x%04x rows; prev gen had 0x%04x rows)\t%s\tfunc=0x%02x (\"%s\")\n", i, log_token, mono_meta_table_name (token_table), token_index, table_info_get_rows (&image_base->tables [token_table]), delta_info->count[token_table].prev_gen_rows, (is_addition ? "ADD" : "UPDATE"), func_code, funccode_to_str (func_code)); if (token_table != MONO_TABLE_METHOD) continue; #ifndef ALLOW_METHOD_ADD if (is_addition) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "\tcannot add new method with token 0x%08x", log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: cannot add new method with token 0x%08x", log_token); unsupported_edits = TRUE; } #endif #ifdef ALLOW_METHOD_ADD /* adding a new parameter to a new method is ok */ if (func_code == ENC_FUNC_ADD_PARAM && is_addition) continue; #endif g_assert (func_code == 0); /* anything else doesn't make sense here */ } for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; switch (token_table) { case MONO_TABLE_ASSEMBLYREF: /* okay, supported */ break; case MONO_TABLE_METHOD: #ifdef ALLOW_METHOD_ADD if (func_code == ENC_FUNC_ADD_PARAM) continue; /* ok, allowed */ #endif /* handled above */ break; case MONO_TABLE_FIELD: #ifdef ALLOW_FIELD_ADD if (func_code == ENC_FUNC_DEFAULT) continue; /* ok, allowed */ #else /* adding or modifying a field */ mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support adding or modifying fields.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding or modifying fields. token=0x%08x", log_token); unsupported_edits = TRUE; break; #endif case MONO_TABLE_PROPERTY: { /* modifying a property, ok */ if (!is_addition) break; /* adding a property */ mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support adding new properties.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding new properties. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } case MONO_TABLE_METHODSEMANTICS: { if (is_addition) { /* new rows are fine, as long as they point at existing methods */ guint32 sema_cols [MONO_METHOD_SEMA_SIZE]; int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); g_assert (mapped_token != -1); mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_METHODSEMANTICS], mapped_token - 1, sema_cols, MONO_METHOD_SEMA_SIZE); switch (sema_cols [MONO_METHOD_SEMA_SEMANTICS]) { case METHOD_SEMANTIC_GETTER: case METHOD_SEMANTIC_SETTER: { int prop_method_index = sema_cols [MONO_METHOD_SEMA_METHOD]; /* ok, if it's pointing to an existing getter/setter */ gboolean is_prop_method_add = prop_method_index-1 >= delta_info->count[MONO_TABLE_METHOD].prev_gen_rows; if (!is_prop_method_add) break; mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x adding new getter/setter method 0x%08x to a property is not supported", i, log_token, prop_method_index); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding a new getter or setter to a property, token=0x%08x", log_token); unsupported_edits = TRUE; continue; } default: mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x adding new non-getter/setter property or event methods is not supported.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding new non-getter/setter property or event methods. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } } else { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support patching of existing table cols.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing table cols. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } } case MONO_TABLE_CUSTOMATTRIBUTE: { if (!is_addition) { /* modifying existing rows is ok, as long as the parent and ctor are the same */ guint32 ca_upd_cols [MONO_CUSTOM_ATTR_SIZE]; guint32 ca_base_cols [MONO_CUSTOM_ATTR_SIZE]; int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); g_assert (mapped_token != -1); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x CUSTOM_ATTR update. mapped index = 0x%08x\n", i, log_token, mapped_token); mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_CUSTOMATTRIBUTE], mapped_token - 1, ca_upd_cols, MONO_CUSTOM_ATTR_SIZE); mono_metadata_decode_row (&image_base->tables [MONO_TABLE_CUSTOMATTRIBUTE], token_index - 1, ca_base_cols, MONO_CUSTOM_ATTR_SIZE); /* compare the ca_upd_cols [MONO_CUSTOM_ATTR_PARENT] to ca_base_cols [MONO_CUSTOM_ATTR_PARENT]. */ mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x CUSTOM_ATTR update. Old Parent 0x%08x New Parent 0x%08x\n", i, log_token, ca_base_cols [MONO_CUSTOM_ATTR_PARENT], ca_upd_cols [MONO_CUSTOM_ATTR_PARENT]); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x CUSTOM_ATTR update. Old ctor 0x%08x New ctor 0x%08x\n", i, log_token, ca_base_cols [MONO_CUSTOM_ATTR_TYPE], ca_upd_cols [MONO_CUSTOM_ATTR_TYPE]); /* TODO: when we support the ChangeCustomAttribute capability, the * parent might become 0 to delete attributes. It may also be the * case that the MONO_CUSTOM_ATTR_TYPE will change. Without that * capability, we trust that if the TYPE is not the same token, it * still resolves to the same MonoMethod* (but we can't check it in * pass1 because we haven't added the new AssemblyRefs yet. */ if (ca_base_cols [MONO_CUSTOM_ATTR_PARENT] != ca_upd_cols [MONO_CUSTOM_ATTR_PARENT]) { mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing CA table cols with a different Parent. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } break; } else { /* Added a row. ok */ break; } } case MONO_TABLE_PARAM: { if (!is_addition) { /* We only allow modifications where the parameter name doesn't change. */ uint32_t base_param [MONO_PARAM_SIZE]; uint32_t upd_param [MONO_PARAM_SIZE]; int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); g_assert (mapped_token != -1); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x PARAM update. mapped index = 0x%08x\n", i, log_token, mapped_token); mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_PARAM], mapped_token - 1, upd_param, MONO_PARAM_SIZE); mono_metadata_decode_row (&image_base->tables [MONO_TABLE_PARAM], token_index - 1, base_param, MONO_PARAM_SIZE); const char *base_name = mono_metadata_string_heap (image_base, base_param [MONO_PARAM_NAME]); const char *upd_name = mono_metadata_string_heap (image_base, upd_param [MONO_PARAM_NAME]); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x: 0x%08x PARAM update: seq = %d (base = %d), name = '%s' (base = '%s')\n", i, log_token, upd_param [MONO_PARAM_SEQUENCE], base_param [MONO_PARAM_SEQUENCE], upd_name, base_name); if (strcmp (base_name, upd_name) != 0 || base_param [MONO_PARAM_SEQUENCE] != upd_param [MONO_PARAM_SEQUENCE]) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support patching of existing PARAM table cols.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing PARAM table cols. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } break; } else break; /* added a row. ok */ } case MONO_TABLE_TYPEDEF: { gboolean new_class G_GNUC_UNUSED = is_addition; #ifdef ALLOW_METHOD_ADD /* only allow adding methods to existing classes for now */ if ( #ifndef ALLOW_CLASS_ADD !new_class && #endif func_code == ENC_FUNC_ADD_METHOD) { /* next record should be a MONO_TABLE_METHOD addition (func == default) */ g_assert (i + 1 < rows); guint32 next_cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i + 1, next_cols, MONO_ENCLOG_SIZE); g_assert (next_cols [MONO_ENCLOG_FUNC_CODE] == ENC_FUNC_DEFAULT); int next_token = next_cols [MONO_ENCLOG_TOKEN]; int next_table = mono_metadata_token_table (next_token); int next_index = mono_metadata_token_index (next_token); g_assert (next_table == MONO_TABLE_METHOD); /* expecting an added method */ g_assert (next_index-1 >= delta_info->count[next_table].prev_gen_rows); i++; /* skip the next record */ continue; } #endif #ifdef ALLOW_FIELD_ADD if ( #ifndef ALLOW_CLASS_ADD !new_class && #endif func_code == ENC_FUNC_ADD_FIELD) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x AddField to klass 0x%08x, skipping next EnClog record", i, log_token, token_index); g_assert (i + 1 < rows); guint32 next_cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i + 1, next_cols, MONO_ENCLOG_SIZE); g_assert (next_cols [MONO_ENCLOG_FUNC_CODE] == ENC_FUNC_DEFAULT); int next_token = next_cols [MONO_ENCLOG_TOKEN]; int next_table = mono_metadata_token_table (next_token); int next_index = mono_metadata_token_index (next_token); g_assert (next_table == MONO_TABLE_FIELD); /* expecting an added field */ g_assert (next_index-1 >= delta_info->count[next_table].prev_gen_rows); i++; /* skip the next record */ continue; } #endif /* fallthru */ } default: if (!is_addition) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support patching of existing table cols.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing table cols. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } } /* * So the way a non-default func_code works is that it's attached to the EnCLog * record preceeding the new member defintion (so e.g. an addMethod code will be on * the preceeding MONO_TABLE_TYPEDEF enc record that identifies the parent type). */ switch (func_code) { case ENC_FUNC_DEFAULT: /* default */ break; default: mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x FunCode %d (%s) not supported (token=0x%08x)", i, log_token, func_code, funccode_to_str (func_code), log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: FuncCode %d (%s) not supported (token=0x%08x)", func_code, funccode_to_str (func_code), log_token); unsupported_edits = TRUE; continue; } } return !unsupported_edits; } static void set_delta_method_debug_info (DeltaInfo *delta_info, uint32_t token_index, MonoDebugInformationEnc *pdb_address) { g_hash_table_insert (delta_info->method_ppdb_table_update, GUINT_TO_POINTER (token_index), (gpointer) pdb_address); } static void set_update_method (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, MonoImage *image_dmeta, DeltaInfo *delta_info, uint32_t token_index, const char* il_address, MonoDebugInformationEnc* pdb_address) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "setting method 0x%08x in g=%d IL=%p", token_index, generation, (void*)il_address); /* FIXME: this is a race if other threads are doing a lookup. */ g_hash_table_insert (base_info->method_table_update, GUINT_TO_POINTER (token_index), GUINT_TO_POINTER (generation)); g_hash_table_insert (delta_info->method_table_update, GUINT_TO_POINTER (token_index), (gpointer) il_address); set_delta_method_debug_info (delta_info, token_index, pdb_address); } static MonoDebugInformationEnc * hot_reload_get_method_debug_information (MonoPPDBFile *ppdb_file, int idx) { if (!ppdb_file) return NULL; MonoImage *image_dppdb = ppdb_file->image; MonoTableInfo *table_encmap = &image_dppdb->tables [MONO_TABLE_ENCMAP]; int rows = table_info_get_rows (table_encmap); for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCMAP_SIZE]; mono_metadata_decode_row (table_encmap, i, cols, MONO_ENCMAP_SIZE); int map_token = cols [MONO_ENCMAP_TOKEN]; int token_table = mono_metadata_token_table (map_token); if (token_table == MONO_TABLE_METHODBODY) { int token_index = mono_metadata_token_index (map_token); if (token_index == idx) { MonoDebugInformationEnc *encDebugInfo = g_new0 (MonoDebugInformationEnc, 1); encDebugInfo->idx = i + 1; encDebugInfo->ppdb_file = ppdb_file; return encDebugInfo; } } } return NULL; } static void G_GNUC_UNUSED dump_assembly_ref_names (MonoImage *image) { if (!mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) return; for (int i = 0; i < image->nreferences; ++i) { ERROR_DECL(local_error); MonoAssemblyName aname; mono_assembly_get_assemblyref_checked (image, i, &aname, local_error); if (is_ok (local_error)) mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Reference[%02d] = '%s'", i, aname.name); else { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Reference[%02d] error '%s'", i, mono_error_get_message (local_error)); mono_error_cleanup (local_error); } } } /* do actuall enclog application */ static gboolean apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, MonoImage *image_dmeta, DeltaInfo *delta_info, gconstpointer dil_data, uint32_t dil_length, MonoError *error) { MonoTableInfo *table_enclog = &image_dmeta->tables [MONO_TABLE_ENCLOG]; int rows = table_info_get_rows (table_enclog); /* NOTE: Suppressed colums * * Certain column values in some tables in the deltas are not meant to be applied over the * previous generation. See CMiniMdRW::m_SuppressedDeltaColumns in CoreCLR. For example the * MONO_METHOD_PARAMLIST column in MONO_TABLE_METHOD is always 0 in an update - for modified * rows the previous value must be carried over. For added rows, it is supposed to be * initialized to the end of the param table and updated with the "Param create" func code * in subsequent EnCLog records. * * For mono's immutable model (where we don't change the baseline image data), we will need * to mutate the delta image tables to incorporate the suppressed column values from the * previous generation. * * For Baseline capabilities, the only suppressed column is MONO_METHOD_PARAMLIST - which we * can ignore because we don't do anything with param updates and the only column we care * about is MONO_METHOD_RVA which gets special case treatment with set_update_method(). * * But when we implement additional capabilities (for example UpdateParameters), we will * need to start mutating the delta image tables to pick up the suppressed column values. * Fortunately whether we get the delta from the debugger or from the runtime API, we always * have it in writable memory (and not mmap-ed pages), so we can rewrite the table values. */ mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Pass 2 begin: base '%s' delta image=%p", image_base->name, image_dmeta); #if defined(ALLOW_METHOD_ADD) || defined(ALLOW_FIELD_ADD) MonoClass *add_member_klass = NULL; #endif gboolean assemblyref_updated = FALSE; for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "enclog i=%d: token=0x%08x (table=%s): %d:\t%s", i, log_token, mono_meta_table_name (token_table), func_code, (is_addition ? "ADD" : "UPDATE")); /* TODO: See CMiniMdRW::ApplyDelta for how to drive this. */ switch (func_code) { case ENC_FUNC_DEFAULT: /* default */ break; #ifdef ALLOW_METHOD_ADD case ENC_FUNC_ADD_METHOD: { g_assert (token_table == MONO_TABLE_TYPEDEF); MonoClass *klass = mono_class_get_checked (image_base, log_token, error); if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Can't get class with token 0x%08x due to: %s", log_token, mono_error_get_message (error)); return FALSE; } add_member_klass = klass; break; } case ENC_FUNC_ADD_PARAM: { g_assert (token_table == MONO_TABLE_METHOD); break; } #endif #ifdef ALLOW_FIELD_ADD case ENC_FUNC_ADD_FIELD: { g_assert (token_table == MONO_TABLE_TYPEDEF); MonoClass *klass = mono_class_get_checked (image_base, log_token, error); if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Can't get class with token 0x%08x due to: %s", log_token, mono_error_get_message (error)); return FALSE; } add_member_klass = klass; break; } #endif default: g_error ("EnC: unsupported FuncCode, should be caught by pass1"); break; } switch (token_table) { case MONO_TABLE_ASSEMBLYREF: { g_assert (token_index > table_info_get_rows (&image_base->tables [token_table])); if (assemblyref_updated) continue; assemblyref_updated = TRUE; /* FIXME: use DeltaInfo:prev_gen_rows instead of looping */ /* TODO: do we know that there will never be modified rows in ASSEMBLYREF? */ int old_rows = table_info_get_rows (&image_base->tables [MONO_TABLE_ASSEMBLYREF]); for (GList *l = base_info->delta_info; l; l = l->next) { MonoImage *delta_child = ((DeltaInfo*)l->data)->delta_image; old_rows += table_info_get_rows (&delta_child->tables [MONO_TABLE_ASSEMBLYREF]); } int new_rows = table_info_get_rows (&image_dmeta->tables [MONO_TABLE_ASSEMBLYREF]); old_rows -= new_rows; g_assert (new_rows > 0); g_assert (old_rows > 0); /* TODO: this can end bad with code around assembly.c:mono_assembly_load_reference */ mono_image_lock (image_base); MonoAssembly **old_array = image_base->references; g_assert (image_base->nreferences == old_rows); image_base->references = g_new0 (MonoAssembly *, old_rows + new_rows + 1); memcpy (image_base->references, old_array, sizeof (gpointer) * (old_rows + 1)); image_base->nreferences = old_rows + new_rows; mono_image_unlock (image_base); #if 0 dump_assembly_ref_names (image_base); #endif g_free (old_array); break; } case MONO_TABLE_METHOD: { #ifdef ALLOW_METHOD_ADD /* if adding a param, handle it with the next record */ if (func_code == ENC_FUNC_ADD_PARAM) break; if (is_addition) { if (!add_member_klass) g_error ("EnC: new method added but I don't know the class, should be caught by pass1"); g_assert (add_member_klass); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Adding new method 0x%08x to class %s.%s", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); MonoDebugInformationEnc *method_debug_information = hot_reload_get_method_debug_information (delta_info->ppdb_file, token_index); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Debug info for method 0x%08x has ppdb idx 0x%08x", log_token, method_debug_information ? method_debug_information->idx : 0); add_method_to_baseline (base_info, delta_info, add_member_klass, log_token, method_debug_information); add_member_klass = NULL; } #endif if (!base_info->method_table_update) base_info->method_table_update = g_hash_table_new (g_direct_hash, g_direct_equal); if (!delta_info->method_table_update) delta_info->method_table_update = g_hash_table_new (g_direct_hash, g_direct_equal); if (!delta_info->method_ppdb_table_update) delta_info->method_ppdb_table_update = g_hash_table_new (g_direct_hash, g_direct_equal); int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); int rva = mono_metadata_decode_row_col (&image_dmeta->tables [MONO_TABLE_METHOD], mapped_token - 1, MONO_METHOD_RVA); if (rva < dil_length) { char *il_address = ((char *) dil_data) + rva; MonoDebugInformationEnc *method_debug_information = hot_reload_get_method_debug_information (delta_info->ppdb_file, token_index); set_update_method (image_base, base_info, generation, image_dmeta, delta_info, token_index, il_address, method_debug_information); } else { /* rva points probably into image_base IL stream. can this ever happen? */ g_print ("TODO: this case is still a bit contrived. token=0x%08x with rva=0x%04x\n", log_token, rva); } #if defined(ALLOW_METHOD_ADD) || defined(ALLOW_FIELD_ADD) add_member_klass = NULL; #endif break; } case MONO_TABLE_FIELD: { #ifdef ALLOW_FIELD_ADD g_assert (is_addition); g_assert (add_member_klass); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Adding new field 0x%08x to class %s.%s", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); uint32_t mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, log_token); uint32_t field_flags = mono_metadata_decode_row_col (&image_dmeta->tables [MONO_TABLE_FIELD], mapped_token - 1, MONO_FIELD_FLAGS); if ((field_flags & FIELD_ATTRIBUTE_STATIC) == 0) { /* TODO: implement instance (and literal?) fields */ mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_METADATA_UPDATE, "Adding non-static fields isn't implemented yet (token 0x%08x, class %s.%s)", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); mono_error_set_not_implemented (error, "Adding non-static fields isn't implemented yet (token 0x%08x, class %s.%s)", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); return FALSE; } add_field_to_baseline (base_info, delta_info, add_member_klass, log_token); /* This actually does more than mono_class_setup_basic_field_info and * resolves MonoClassField:type and sets MonoClassField:offset to -1 to make * it easier to spot that the field is special. */ metadata_update_field_setup_basic_info_and_resolve (image_base, base_info, generation, delta_info, add_member_klass, log_token, error); if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_METADATA_UPDATE, "Could not setup field (token 0x%08x) due to: %s", log_token, mono_error_get_message (error)); return FALSE; } add_member_klass = NULL; #else g_assert_not_reached (); #endif break; } case MONO_TABLE_TYPEDEF: { #ifdef ALLOW_CLASS_ADD if (is_addition) { /* Adding a new class. ok */ switch (func_code) { case ENC_FUNC_DEFAULT: /* ok, added a new class */ /* TODO: do things here */ break; case ENC_FUNC_ADD_METHOD: case ENC_FUNC_ADD_FIELD: /* ok, adding a new field or method to a new class */ /* TODO: do we need to do anything special? Conceptually * this is the same as modifying an existing class - * especially since from the next generation's point of view * that's what adding a field/method will be. */ break; case ENC_FUNC_ADD_PROPERTY: case ENC_FUNC_ADD_EVENT: g_assert_not_reached (); /* FIXME: implement me */ default: g_assert_not_reached (); /* unknown func_code */ } break; } #endif /* modifying an existing class by adding a method or field, etc. */ g_assert (!is_addition); #if !defined(ALLOW_METHOD_ADD) && !defined(ALLOW_FIELD_ADD) g_assert_not_reached (); #else g_assert (func_code != ENC_FUNC_DEFAULT); #endif break; } case MONO_TABLE_PROPERTY: { /* allow updates to existing properties. */ /* FIXME: use DeltaInfo:prev_gen_rows instead of image_base */ g_assert (token_index <= table_info_get_rows (&image_base->tables [token_table])); /* assuming that property attributes and type haven't changed. */ break; } case MONO_TABLE_CUSTOMATTRIBUTE: { /* ok, pass1 checked for disallowed modifications */ break; } case MONO_TABLE_PARAM: { /* ok, pass1 checked for disallowed modifications */ /* ALLOW_METHOD_ADD: FIXME: here we would really like to update the method's paramlist column to point to the new params. */ /* if there were multiple added methods, this comes in as several method * additions, followed by the parameter additions. * * 10: 0x02000002 (TypeDef) 0x00000001 (AddMethod) * 11: 0x06000006 (MethodDef) 0 * 12: 0x02000002 (TypeDef) 0x00000001 (AddMethod) * 13: 0x06000007 (MethodDef) 0 * 14: 0x06000006 (MethodDef) 0x00000003 (AddParameter) * 15: 0x08000003 (Param) 0 * 16: 0x06000006 (MethodDef) 0x00000003 (AddParameter) * 17: 0x08000004 (Param) 0 * 18: 0x06000007 (MethodDef) 0x00000003 (AddParameter) * 19: 0x08000005 (Param) 0 * * So by the time we see the param additions, the methods are already in. * * FIXME: we need a lookaside table (like member_parent) for every place * that looks at MONO_METHOD_PARAMLIST */ break; } default: { g_assert (token_index > table_info_get_rows (&image_base->tables [token_table])); if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) g_print ("todo: do something about this table index: 0x%02x\n", token_table); } } } return TRUE; } static void dump_methodbody (MonoImage *image) { if (!mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) return; MonoTableInfo *t = &image->tables [MONO_TABLE_METHODBODY]; uint32_t rows = table_info_get_rows (t); for (uint32_t i = 0; i < rows; ++i) { uint32_t cols[MONO_METHODBODY_SIZE]; mono_metadata_decode_row (t, i, cols, MONO_METHODBODY_SIZE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, " row[%02d] = doc: 0x%08x seq: 0x%08x", i + 1, cols [MONO_METHODBODY_DOCUMENT], cols [MONO_METHODBODY_SEQ_POINTS]); } } /** * * LOCKING: Takes the publish_lock */ void hot_reload_apply_changes (int origin, MonoImage *image_base, gconstpointer dmeta_bytes, uint32_t dmeta_length, gconstpointer dil_bytes_orig, uint32_t dil_length, gconstpointer dpdb_bytes_orig, uint32_t dpdb_length, MonoError *error) { if (!assembly_update_supported (image_base->assembly)) { mono_error_set_invalid_operation (error, "The assembly can not be edited or changed."); return; } static int first_origin = -1; if (first_origin < 0) { first_origin = origin; } if (first_origin != origin) { mono_error_set_not_supported (error, "Applying deltas through the debugger and System.Reflection.Metadata.MetadataUpdater.ApplyUpdate simultaneously is not supported"); return; } const char *basename = image_base->filename; if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) { g_print ("LOADING basename=%s delta update.\ndelta image=%p & dil=%p\n", basename, dmeta_bytes, dil_bytes_orig); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "delta image size 0x%08x, delta IL size 0x%08x\n", dmeta_length, dil_length); #if 0 mono_dump_mem (dmeta_bytes, dmeta_length); mono_dump_mem (dil_bytes_orig, dil_length); #endif } uint32_t generation = hot_reload_update_prepare (); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image string size: 0x%08x", image_base->heap_strings.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image user string size: 0x%08x", image_base->heap_us.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image blob heap addr: %p", image_base->heap_blob.data); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image blob heap size: 0x%08x", image_base->heap_blob.size); /* makes a copy of dmeta_bytes */ MonoImage *image_dmeta = image_open_dmeta_from_data (image_base, generation, dmeta_bytes, dmeta_length); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image string size: 0x%08x", image_dmeta->heap_strings.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image user string size: 0x%08x", image_dmeta->heap_us.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image blob heap addr: %p", image_dmeta->heap_blob.data); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image blob heap size: 0x%08x", image_dmeta->heap_blob.size); g_assert (image_dmeta); /* makes a copy of dil_bytes_orig */ gpointer dil_bytes = open_dil_data (image_base, dil_bytes_orig, dil_length); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta IL bytes copied to addr=%p", dil_bytes); MonoPPDBFile *ppdb_file = NULL; if (dpdb_length > 0) { MonoImage *image_dpdb = image_open_dmeta_from_data (image_base, generation, dpdb_bytes_orig, dpdb_length); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image string size: 0x%08x", image_dpdb->heap_strings.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image user string size: 0x%08x", image_dpdb->heap_us.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image blob heap addr: %p", image_dpdb->heap_blob.data); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image blob heap size: 0x%08x", image_dpdb->heap_blob.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "ppdb methodbody: "); dump_methodbody (image_dpdb); ppdb_file = mono_create_ppdb_file (image_dpdb, FALSE); g_assert (ppdb_file->image == image_dpdb); } BaselineInfo *base_info = baseline_info_lookup_or_add (image_base); DeltaInfo *prev_delta_info = NULL; DeltaInfo *delta_info = delta_info_init (image_dmeta, image_base, ppdb_file, base_info, generation, &prev_delta_info); if (image_dmeta->minimal_delta) { guint32 idx = mono_metadata_decode_row_col (&image_dmeta->tables [MONO_TABLE_MODULE], 0, MONO_MODULE_NAME); const char *module_name = NULL; module_name = mono_metadata_string_heap (image_base, idx); /* Set the module name now that we know the base String heap size */ g_assert (!image_dmeta->module_name); image_dmeta->module_name = module_name; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "applied dmeta name: '%s'\n", module_name); } MonoTableInfo *table_enclog = &image_dmeta->tables [MONO_TABLE_ENCLOG]; MonoTableInfo *table_encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; if (!table_info_get_rows (table_enclog) && !table_info_get_rows (table_encmap)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "No enclog or encmap in delta image for base=%s, nothing to do", basename); hot_reload_update_cancel (generation); return; } /* Process EnCMap and compute number of added/modified rows from this * delta. This enables computing row indexes relative to the delta. * We use it in pass1 to bail out early if the EnCLog has unsupported * edits. */ if (!delta_info_compute_table_records (image_dmeta, image_base, base_info, delta_info)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Error on computing delta table info (base=%s)", basename); hot_reload_update_cancel (generation); return; } delta_info_initialize_mutants (image_base, base_info, prev_delta_info, delta_info); prepare_mutated_rows (table_enclog, image_base, image_dmeta, delta_info); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Populated mutated tables for delta image %p", image_dmeta); if (!apply_enclog_pass1 (image_base, image_dmeta, delta_info, dil_bytes, dil_length, error)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Error on sanity-checking delta image to base=%s, due to: %s", basename, mono_error_get_message (error)); hot_reload_update_cancel (generation); return; } /* if there are updates, start tracking the tables of the base image, if we weren't already. */ if (table_info_get_rows (table_enclog)) table_to_image_add (image_base); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base guid: %s", image_base->guid); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta guid: %s", image_dmeta->guid); if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) dump_update_summary (image_base, image_dmeta); if (!apply_enclog_pass2 (image_base, base_info, generation, image_dmeta, delta_info, dil_bytes, dil_length, error)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Error applying delta image to base=%s, due to: %s", basename, mono_error_get_message (error)); hot_reload_update_cancel (generation); return; } mono_error_assert_ok (error); MonoAssemblyLoadContext *alc = mono_image_get_alc (image_base); hot_reload_update_publish (alc, generation); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, ">>> EnC delta for base=%s (generation %d) applied", basename, generation); } static gpointer get_method_update_rva (MonoImage *image_base, BaselineInfo *base_info, uint32_t idx, gboolean is_pdb) { gpointer loc = NULL; uint32_t cur = hot_reload_get_thread_generation (); int generation = -1; /* Go through all the updates that the current thread can see and see * if they updated the method. Keep the latest visible update */ for (GList *ptr = base_info->delta_info; ptr != NULL; ptr = ptr->next) { DeltaInfo *delta_info = (DeltaInfo*)ptr->data; g_assert (delta_info); if (delta_info->generation > cur) break; GHashTable *table = NULL; if (is_pdb) table = delta_info->method_ppdb_table_update; else table = delta_info->method_table_update; if (table) { gpointer result = g_hash_table_lookup (table, GUINT_TO_POINTER (idx)); /* if it's not in the table of a later generation, the * later generation didn't modify the method */ if (result != NULL) { loc = result; generation = delta_info->generation; } } } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "method lookup idx=0x%08x returned gen=%d il=%p", idx, generation, loc); return loc; } gpointer hot_reload_get_updated_method_ppdb (MonoImage *base_image, uint32_t idx) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return NULL; gpointer loc = NULL; /* EnC case */ if (G_UNLIKELY (info->method_table_update)) { uint32_t gen = GPOINTER_TO_UINT (g_hash_table_lookup (info->method_table_update, GUINT_TO_POINTER (idx))); if (G_UNLIKELY (gen > 0)) { loc = get_method_update_rva (base_image, info, idx, TRUE); } /* Check the member_parent table as a way of checking if the method was added by a later generation. If so, still look for its PPDB info in our update tables */ uint32_t token = mono_metadata_make_token (MONO_TABLE_METHOD, mono_metadata_token_index (idx)); if (G_UNLIKELY (loc == 0 && info->member_parent && GPOINTER_TO_UINT (g_hash_table_lookup (info->member_parent, GUINT_TO_POINTER (token))) > 0)) { loc = get_method_update_rva (base_image, info, idx, TRUE); } } return loc; } gpointer hot_reload_get_updated_method_rva (MonoImage *base_image, uint32_t idx) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return NULL; gpointer loc = NULL; /* EnC case */ if (G_UNLIKELY (info->method_table_update)) { uint32_t gen = GPOINTER_TO_UINT (g_hash_table_lookup (info->method_table_update, GUINT_TO_POINTER (idx))); if (G_UNLIKELY (gen > 0)) { loc = get_method_update_rva (base_image, info, idx, FALSE); } } return loc; } /* returns TRUE if token index is out of bounds */ gboolean hot_reload_table_bounds_check (MonoImage *base_image, int table_index, int token_index) { BaselineInfo *base_info = baseline_info_lookup (base_image); g_assert (base_info); GList *list = base_info->delta_info; MonoTableInfo *table; /* result row, 0-based */ int ridx; uint32_t exposed_gen = hot_reload_get_thread_generation (); do { if (!list) return TRUE; DeltaInfo *delta_info = (DeltaInfo*)list->data; g_assert (delta_info); if (delta_info->generation > exposed_gen) return TRUE; list = list->next; table = &delta_info->mutants [table_index]; ridx = token_index - 1; } while (ridx < 0 || ridx >= table_info_get_rows (table)); return FALSE; } gboolean hot_reload_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, uint32_t orig_index, MonoImage **image_out, uint32_t *index_out) { g_assert (image_out); g_assert (index_out); MonoStreamHeader *heap = get_heap (base_image); g_assert (orig_index >= heap->size); BaselineInfo *base_info = baseline_info_lookup (base_image); g_assert (base_info); g_assert (base_info->delta_info); *image_out = base_image; *index_out = orig_index; guint32 prev_size = heap->size; uint32_t current_gen = hot_reload_get_thread_generation (); GList *cur; for (cur = base_info->delta_info; cur; cur = cur->next) { DeltaInfo *delta_info = (DeltaInfo*)cur->data; g_assert (delta_info); MonoImage *delta_image = delta_info->delta_image; g_assert (delta_image); heap = get_heap (delta_image); *image_out = delta_image; if (delta_info->generation > current_gen) return FALSE; /* FIXME: for non-minimal deltas we should just look in the last published image. */ if (G_LIKELY (delta_image->minimal_delta)) *index_out -= prev_size; if (*index_out < heap->size) break; prev_size = heap->size; } return (cur != NULL); } static gboolean hot_reload_has_modified_rows (const MonoTableInfo *table) { MonoImage *base; int tbl_index; if (!table_info_find_in_base (table, &base, &tbl_index)) return FALSE; BaselineInfo *info = baseline_info_lookup (base); if (!info) return FALSE; return info->any_modified_rows[tbl_index]; } static int hot_reload_table_num_rows_slow (MonoImage *base, int table_index) { BaselineInfo *base_info = baseline_info_lookup (base); if (!base_info) return FALSE; uint32_t current_gen = hot_reload_get_thread_generation (); int rows = table_info_get_rows (&base->tables [table_index]); GList *cur; for (cur = base_info->delta_info; cur; cur = cur->next) { DeltaInfo *delta_info = (DeltaInfo*)cur->data; g_assert (delta_info); if (delta_info->generation > current_gen) break; rows = delta_info->count [table_index].prev_gen_rows + delta_info->count [table_index].inserted_rows; } return rows; } static void add_member_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t member_token) { /* Check they really passed a table token, not just a table row index */ g_assert (mono_metadata_token_table (member_token) != 0); if (!base_info->member_parent) { base_info->member_parent = g_hash_table_new (g_direct_hash, g_direct_equal); } MonoClassMetadataUpdateInfo *klass_info = mono_class_get_or_add_metadata_update_info (klass); GSList *members = klass_info->added_members; klass_info->added_members = g_slist_prepend_mem_manager (m_class_get_mem_manager (klass), members, GUINT_TO_POINTER (member_token)); g_hash_table_insert (base_info->member_parent, GUINT_TO_POINTER (member_token), GUINT_TO_POINTER (m_class_get_type_token (klass))); } static void add_method_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t method_token, MonoDebugInformationEnc* pdb_address) { add_member_to_baseline (base_info, delta_info, klass, method_token); if (pdb_address) set_delta_method_debug_info (delta_info, method_token, pdb_address); } static GSList* hot_reload_get_added_members (MonoClass *klass) { /* FIXME: locking for the GArray? */ MonoImage *image = m_class_get_image (klass); if (!image->has_updates) return NULL; MonoClassMetadataUpdateInfo *klass_info = mono_class_get_metadata_update_info (klass); if (!klass_info) return NULL; return klass_info->added_members; } static uint32_t hot_reload_member_parent (MonoImage *base_image, uint32_t member_token) { /* make sure they passed a token, not just a table row index */ g_assert (mono_metadata_token_table (member_token) != 0); if (!base_image->has_updates) return 0; BaselineInfo *base_info = baseline_info_lookup (base_image); if (!base_info || base_info->member_parent == NULL) return 0; uint32_t res = GPOINTER_TO_UINT (g_hash_table_lookup (base_info->member_parent, GUINT_TO_POINTER (member_token))); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "member_parent lookup: 0x%08x returned 0x%08x\n", member_token, res); return res; } static uint32_t hot_reload_method_parent (MonoImage *base_image, uint32_t method_token) { /* the callers might pass just an index without a table */ uint32_t lookup_token = mono_metadata_make_token (MONO_TABLE_METHOD, mono_metadata_token_index (method_token)); return hot_reload_member_parent (base_image, lookup_token); } static void add_field_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t field_token) { add_member_to_baseline (base_info, delta_info, klass, field_token); } static uint32_t hot_reload_field_parent (MonoImage *base_image, uint32_t field_token) { /* the callers might pass just an index without a table */ uint32_t lookup_token = mono_metadata_make_token (MONO_TABLE_FIELD, mono_metadata_token_index (field_token)); return hot_reload_member_parent (base_image, lookup_token); } /* HACK - keep in sync with locator_t in metadata/metadata.c */ typedef struct { int idx; /* The index that we are trying to locate */ int col_idx; /* The index in the row where idx may be stored */ MonoTableInfo *t; /* pointer to the table */ guint32 result; } upd_locator_t; void* hot_reload_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer) { BaselineInfo *base_info = baseline_info_lookup (base_image); g_assert (base_info); g_assert (base_image->tables < base_table && base_table < &base_image->tables [MONO_TABLE_LAST]); int tbl_index; { size_t s = ALIGN_TO (sizeof (MonoTableInfo), sizeof (gpointer)); tbl_index = ((intptr_t) base_table - (intptr_t) base_image->tables) / s; } DeltaInfo *delta_info = NULL; const MonoTableInfo *latest_mod_table = base_table; gboolean success = effective_table_mutant (base_image, base_info, tbl_index, &latest_mod_table, &delta_info); g_assert (success); uint32_t rows = table_info_get_rows (latest_mod_table); upd_locator_t *loc = (upd_locator_t*)key; g_assert (loc); loc->result = 0; /* HACK: this is so that the locator can compute the row index of the given row. but passing the mutant table to other metadata functions could backfire. */ loc->t = (MonoTableInfo*)latest_mod_table; for (uint32_t idx = 0; idx < rows; ++idx) { const char *row = latest_mod_table->base + idx * latest_mod_table->row_size; if (!comparer (loc, row)) return (void*)row; } return NULL; } static uint32_t hot_reload_get_field_idx (MonoClassField *field) { g_assert (m_field_is_from_update (field)); MonoClassMetadataUpdateField *field_info = (MonoClassMetadataUpdateField*)field; return mono_metadata_token_index (field_info->token); } static MonoClassField * hot_reload_get_field (MonoClass *klass, uint32_t fielddef_token) { MonoClassMetadataUpdateInfo *info = mono_class_get_or_add_metadata_update_info (klass); g_assert (mono_metadata_token_table (fielddef_token) == MONO_TABLE_FIELD); /* FIXME: this needs locking in the multi-threaded case. There could be an update happening that resizes the array. */ GPtrArray *added_fields = info->added_fields; uint32_t count = added_fields->len; for (uint32_t i = 0; i < count; ++i) { MonoClassMetadataUpdateField *field = (MonoClassMetadataUpdateField *)g_ptr_array_index (added_fields, i); if (field->token == fielddef_token) return &field->field; } return NULL; } static MonoClassMetadataUpdateField * metadata_update_field_setup_basic_info_and_resolve (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, DeltaInfo *delta_info, MonoClass *parent_klass, uint32_t fielddef_token, MonoError *error) { // TODO: hang a "pending field" struct off the parent_klass if !parent_klass->fields // In that case we can do things simpler, maybe by just creating the MonoClassField array as usual, and just relying on the normal layout algorithm to make space for the instance. MonoClassMetadataUpdateInfo *parent_info = mono_class_get_or_add_metadata_update_info (parent_klass); MonoClassMetadataUpdateField *field = mono_class_alloc0 (parent_klass, sizeof (MonoClassMetadataUpdateField)); m_field_set_parent (&field->field, parent_klass); m_field_set_meta_flags (&field->field, MONO_CLASS_FIELD_META_FLAG_FROM_UPDATE); /* It's a special field */ field->field.offset = -1; field->generation = generation; field->token = fielddef_token; uint32_t name_idx = mono_metadata_decode_table_row_col (image_base, MONO_TABLE_FIELD, mono_metadata_token_index (fielddef_token) - 1, MONO_FIELD_NAME); field->field.name = mono_metadata_string_heap (image_base, name_idx); mono_field_resolve_type (&field->field, error); if (!is_ok (error)) return NULL; if (!parent_info->added_fields) { parent_info->added_fields = g_ptr_array_new (); } g_ptr_array_add (parent_info->added_fields, field); return field; } static void ensure_class_runtime_info_inited (MonoClass *klass, MonoClassRuntimeMetadataUpdateInfo *runtime_info) { if (runtime_info->inited) return; mono_loader_lock (); if (runtime_info->inited) { mono_loader_unlock (); return; } mono_coop_mutex_init (&runtime_info->static_fields_lock); /* FIXME: is it ok to re-use MONO_ROOT_SOURCE_STATIC here? */ runtime_info->static_fields = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_STATIC, NULL, "Hot Reload Static Fields"); runtime_info->inited = TRUE; mono_loader_unlock (); } static void class_runtime_info_static_fields_lock (MonoClassRuntimeMetadataUpdateInfo *runtime_info) { mono_coop_mutex_lock (&runtime_info->static_fields_lock); } static void class_runtime_info_static_fields_unlock (MonoClassRuntimeMetadataUpdateInfo *runtime_info) { mono_coop_mutex_unlock (&runtime_info->static_fields_lock); } static GENERATE_GET_CLASS_WITH_CACHE_DECL (hot_reload_field_store); static GENERATE_GET_CLASS_WITH_CACHE(hot_reload_field_store, "Mono.HotReload", "FieldStore"); static MonoObject* create_static_field_storage (MonoType *t, MonoError *error) { MonoClass *klass; if (!mono_type_is_reference (t)) klass = mono_class_from_mono_type_internal (t); else klass = mono_class_get_hot_reload_field_store_class (); return mono_object_new_pinned (klass, error); } static gpointer hot_reload_get_static_field_addr (MonoClassField *field) { g_assert (m_field_is_from_update (field)); MonoClassMetadataUpdateField *f = (MonoClassMetadataUpdateField *)field; g_assert ((f->field.type->attrs & FIELD_ATTRIBUTE_STATIC) != 0); g_assert (!m_type_is_byref(f->field.type)); // byref fields only in ref structs, which aren't allowed in EnC updates MonoClass *parent = m_field_get_parent (&f->field); MonoClassMetadataUpdateInfo *parent_info = mono_class_get_or_add_metadata_update_info (parent); MonoClassRuntimeMetadataUpdateInfo *runtime_info = &parent_info->runtime; ensure_class_runtime_info_inited (parent, runtime_info); MonoObject *obj = NULL; class_runtime_info_static_fields_lock (runtime_info); obj = (MonoObject*) mono_g_hash_table_lookup (runtime_info->static_fields, GUINT_TO_POINTER (f->token)); class_runtime_info_static_fields_unlock (runtime_info); if (!obj) { ERROR_DECL (error); obj = create_static_field_storage (f->field.type, error); class_runtime_info_static_fields_lock (runtime_info); mono_error_assert_ok (error); MonoObject *obj2 = (MonoObject*) mono_g_hash_table_lookup (runtime_info->static_fields, GUINT_TO_POINTER (f->token)); if (!obj2) { // Noone else created it, use ours mono_g_hash_table_insert_internal (runtime_info->static_fields, GUINT_TO_POINTER (f->token), obj); } else { /* beaten by another thread, silently drop our storage object and use theirs */ obj = obj2; } class_runtime_info_static_fields_unlock (runtime_info); } g_assert (obj); gpointer addr = NULL; if (!mono_type_is_reference (f->field.type)) { // object is just the boxed value addr = mono_object_unbox_internal (obj); } else { // object is a Mono.HotReload.FieldStore, and the static field value is obj._loc MonoHotReloadFieldStoreObject *store = (MonoHotReloadFieldStoreObject *)obj; addr = (gpointer)&store->_loc; } g_assert (addr); return addr; } static MonoMethod * hot_reload_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error) { GSList *members = hot_reload_get_added_members (klass); if (!members) return NULL; MonoImage *image = m_class_get_image (klass); MonoMethod *res = NULL; for (GSList *ptr = members; ptr; ptr = ptr->next) { uint32_t token = GPOINTER_TO_UINT(ptr->data); if (mono_metadata_token_table (token) != MONO_TABLE_METHOD) continue; uint32_t idx = mono_metadata_token_index (token); uint32_t cols [MONO_METHOD_SIZE]; mono_metadata_decode_table_row (image, MONO_TABLE_METHOD, idx - 1, cols, MONO_METHOD_SIZE); if (!strcmp (mono_metadata_string_heap (image, cols [MONO_METHOD_NAME]), name)) { ERROR_DECL (local_error); MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, local_error); if (!method) { mono_error_cleanup (local_error); continue; } if (param_count == -1) { res = method; break; } MonoMethodSignature *sig = mono_method_signature_checked (method, local_error); if (!sig) { mono_error_cleanup (error); continue; } if ((method->flags & flags) == flags && sig->param_count == param_count) { res = method; break; } } } return res; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // #include <config.h> #include <glib.h> #include <config.h> #include "mono/utils/mono-compiler.h" #include "mono/component/hot_reload-internals.h" #include <glib.h> #include "mono/metadata/assembly-internals.h" #include "mono/metadata/mono-hash-internals.h" #include "mono/metadata/metadata-internals.h" #include "mono/metadata/metadata-update.h" #include "mono/metadata/object-internals.h" #include "mono/metadata/tokentype.h" #include "mono/utils/mono-coop-mutex.h" #include "mono/utils/mono-error-internals.h" #include "mono/utils/mono-lazy-init.h" #include "mono/utils/mono-logger-internals.h" #include "mono/utils/mono-path.h" #include "mono/metadata/debug-internals.h" #include "mono/metadata/mono-debug.h" #include "mono/metadata/debug-mono-ppdb.h" #include "mono/utils/bsearch.h" #include <mono/component/hot_reload.h> #include <mono/utils/mono-compiler.h> #define ALLOW_CLASS_ADD #define ALLOW_METHOD_ADD #define ALLOW_FIELD_ADD typedef struct _BaselineInfo BaselineInfo; typedef struct _DeltaInfo DeltaInfo; static void hot_reload_init (void); static bool hot_reload_available (void); static void hot_reload_set_fastpath_data (MonoMetadataUpdateData *data); static gboolean hot_reload_update_enabled (int *modifiable_assemblies_out); static gboolean hot_reload_no_inline (MonoMethod *caller, MonoMethod *callee); static uint32_t hot_reload_thread_expose_published (void); static uint32_t hot_reload_get_thread_generation (void); static void hot_reload_cleanup_on_close (MonoImage *image); static void hot_reload_effective_table_slow (const MonoTableInfo **t, int idx); static void hot_reload_apply_changes (int origin, MonoImage *base_image, gconstpointer dmeta, uint32_t dmeta_len, gconstpointer dil, uint32_t dil_len, gconstpointer dpdb_bytes_orig, uint32_t dpdb_length, MonoError *error); static int hot_reload_relative_delta_index (MonoImage *image_dmeta, DeltaInfo *delta_info, int token); static void hot_reload_close_except_pools_all (MonoImage *base_image); static void hot_reload_close_all (MonoImage *base_image); static gpointer hot_reload_get_updated_method_rva (MonoImage *base_image, uint32_t idx); static gboolean hot_reload_table_bounds_check (MonoImage *base_image, int table_index, int token_index); static gboolean hot_reload_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, uint32_t orig_index, MonoImage **image_out, uint32_t *index_out); static gpointer hot_reload_get_updated_method_ppdb (MonoImage *base_image, uint32_t idx); static gboolean hot_reload_has_modified_rows (const MonoTableInfo *table); static int hot_reload_table_num_rows_slow (MonoImage *image, int table_index); static GSList* hot_reload_get_added_members (MonoClass *klass); static uint32_t hot_reload_method_parent (MonoImage *base, uint32_t method_token); static void* hot_reload_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer); static uint32_t hot_reload_field_parent (MonoImage *base, uint32_t field_token); static uint32_t hot_reload_get_field_idx (MonoClassField *field); static MonoClassField * hot_reload_get_field (MonoClass *klass, uint32_t fielddef_token); static gpointer hot_reload_get_static_field_addr (MonoClassField *field); static MonoMethod * hot_reload_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error); static MonoClassMetadataUpdateField * metadata_update_field_setup_basic_info_and_resolve (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, DeltaInfo *delta_info, MonoClass *parent_klass, uint32_t fielddef_token, MonoError *error); static MonoComponentHotReload fn_table = { { MONO_COMPONENT_ITF_VERSION, &hot_reload_available }, &hot_reload_set_fastpath_data, &hot_reload_update_enabled, &hot_reload_no_inline, &hot_reload_thread_expose_published, &hot_reload_get_thread_generation, &hot_reload_cleanup_on_close, &hot_reload_effective_table_slow, &hot_reload_apply_changes, &hot_reload_close_except_pools_all, &hot_reload_close_all, &hot_reload_get_updated_method_rva, &hot_reload_table_bounds_check, &hot_reload_delta_heap_lookup, &hot_reload_get_updated_method_ppdb, &hot_reload_has_modified_rows, &hot_reload_table_num_rows_slow, &hot_reload_method_parent, &hot_reload_metadata_linear_search, &hot_reload_field_parent, &hot_reload_get_field_idx, &hot_reload_get_field, &hot_reload_get_static_field_addr, &hot_reload_find_method_by_name, }; MonoComponentHotReload * mono_component_hot_reload_init (void) { hot_reload_init (); return &fn_table; } static bool hot_reload_available (void) { return true; } static MonoMetadataUpdateData* metadata_update_data_ptr; static void hot_reload_set_fastpath_data (MonoMetadataUpdateData *ptr) { metadata_update_data_ptr = ptr; } /* TLS value is a uint32_t of the latest published generation that the thread can see */ static MonoNativeTlsKey exposed_generation_id; #if 1 #define UPDATE_DEBUG(stmt) do { stmt; } while (0) #else #define UPDATE_DEBUG(stmt) /*empty */ #endif /* For each delta image, for each table: * - the total logical number of rows for the previous generation * - the number of modified rows in the current generation * - the number of inserted rows in the current generation * * In each delta, the physical tables contain the rows that modify existing rows of a prior generation, * followed by inserted rows. * https://github.com/dotnet/runtime/blob/6072e4d3a7a2a1493f514cdf4be75a3d56580e84/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataAggregator.cs#L324 * * The total logical number of rows in a table for a particular generation is * prev_gen_rows + inserted_rows. */ typedef struct _delta_row_count { guint32 prev_gen_rows; guint32 modified_rows; guint32 inserted_rows; } delta_row_count; /* Additional informaiton for MonoImages representing deltas */ struct _DeltaInfo { uint32_t generation; /* global update ID that added this delta image */ MonoImage *delta_image; /* DeltaInfo doesn't own the image, the base MonoImage owns the reference */ /* Maps MethodDef token indices to a pointer into the RVA of the delta IL */ GHashTable *method_table_update; /* Maps MethodDef token indices to a pointer into the RVA of the delta PPDB */ GHashTable *method_ppdb_table_update; // for each table, the row in the EncMap table that has the first token for remapping it? uint32_t enc_recs [MONO_TABLE_NUM]; delta_row_count count [MONO_TABLE_NUM]; MonoPPDBFile *ppdb_file; MonoMemPool *pool; /* mutated tables are allocated here */ MonoTableInfo mutants[MONO_TABLE_NUM]; }; /* Additional informaiton for baseline MonoImages */ struct _BaselineInfo { /* List of DeltaInfos of deltas*/ GList *delta_info; /* Tail of delta_info for fast appends */ GList *delta_info_last; /* Maps MethodDef token indices to a boolean flag that there's an update for the method */ GHashTable *method_table_update; /* TRUE if any published update modified an existing row */ gboolean any_modified_rows [MONO_TABLE_NUM]; /* A list of MonoClassMetadataUpdateInfo* that need to be cleaned up */ GSList *klass_info; /* Parents for added methods, fields, etc */ GHashTable *member_parent; /* maps added methoddef or fielddef tokens to typedef tokens */ }; #define DOTNET_MODIFIABLE_ASSEMBLIES "DOTNET_MODIFIABLE_ASSEMBLIES" /* See Note: Suppressed Columns */ static guint16 m_SuppressedDeltaColumns [MONO_TABLE_NUM]; /** * mono_metadata_update_enable: * \param modifiable_assemblies_out: set to MonoModifiableAssemblies value * * Returns \c TRUE if metadata updates are enabled at runtime. False otherwise. * * If \p modifiable_assemblies_out is not \c NULL, it's set on return. * * The result depends on the value of the DOTNET_MODIFIABLE_ASSEMBLIES * environment variable. "debug" means debuggable assemblies are modifiable, * all other values are ignored and metadata updates are disabled. */ gboolean hot_reload_update_enabled (int *modifiable_assemblies_out) { static gboolean inited = FALSE; static int modifiable = MONO_MODIFIABLE_ASSM_NONE; if (!inited) { char *val = g_getenv (DOTNET_MODIFIABLE_ASSEMBLIES); if (val && !g_strcasecmp (val, "debug")) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Metadata update enabled for debuggable assemblies"); modifiable = MONO_MODIFIABLE_ASSM_DEBUG; } g_free (val); inited = TRUE; } if (modifiable_assemblies_out) *modifiable_assemblies_out = modifiable; return modifiable != MONO_MODIFIABLE_ASSM_NONE; } static gboolean assembly_update_supported (MonoAssembly *assm) { int modifiable = 0; if (!hot_reload_update_enabled (&modifiable)) return FALSE; if (modifiable == MONO_MODIFIABLE_ASSM_DEBUG && mono_assembly_is_jit_optimizer_disabled (assm)) return TRUE; return FALSE; } /** * hot_reload_update_no_inline: * \param caller: the calling method * \param callee: the method being called * * Returns \c TRUE if \p callee should not be inlined into \p caller. * * If metadata updates are enabled either for the caller or callee's module, * the callee should not be inlined. * */ gboolean hot_reload_no_inline (MonoMethod *caller, MonoMethod *callee) { if (!hot_reload_update_enabled (NULL)) return FALSE; MonoAssembly *caller_assm = m_class_get_image(caller->klass)->assembly; MonoAssembly *callee_assm = m_class_get_image(callee->klass)->assembly; return mono_assembly_is_jit_optimizer_disabled (caller_assm) || mono_assembly_is_jit_optimizer_disabled (callee_assm); } /* Maps each MonoTableInfo* to the MonoImage that it belongs to. This is * mapping the base image MonoTableInfos to the base MonoImage. We don't need * this for deltas. */ static GHashTable *table_to_image; /* Maps each delta MonoImage to its DeltaInfo. Doesn't own the DeltaInfo or the images */ static GHashTable *delta_image_to_info; /* Maps each baseline MonoImage to its BaselineInfo */ static GHashTable *baseline_image_to_info; /* Low-level lock to protects table_to_image and delta_image_to_info */ /* FIXME: use concurrent hash tables so that readers don't have to lock. */ static MonoCoopMutex table_to_image_mutex; static void table_to_image_lock (void) { mono_coop_mutex_lock (&table_to_image_mutex); } static void table_to_image_unlock (void) { mono_coop_mutex_unlock (&table_to_image_mutex); } static BaselineInfo * baseline_info_init (MonoImage *image_base) { BaselineInfo *baseline_info = g_malloc0 (sizeof (BaselineInfo)); return baseline_info; } static void klass_info_destroy (gpointer value, gpointer user_data G_GNUC_UNUSED) { MonoClassMetadataUpdateInfo *info = (MonoClassMetadataUpdateInfo *)value; /* added_members is allocated from the class mempool, don't free it here */ /* The MonoClassMetadataUpdateField is allocated from the class mempool, don't free it here */ g_ptr_array_free (info->added_fields, TRUE); if (info->runtime.static_fields) { mono_g_hash_table_destroy (info->runtime.static_fields); info->runtime.static_fields = NULL; } mono_coop_mutex_destroy (&info->runtime.static_fields_lock); /* The MonoClassMetadataUpdateInfo itself is allocated from the class mempool, don't free it here */ } static void baseline_info_destroy (BaselineInfo *info) { if (info->method_table_update) g_hash_table_destroy (info->method_table_update); if (info->klass_info) { g_slist_foreach (info->klass_info, klass_info_destroy, NULL); g_slist_free (info->klass_info); } g_free (info); } static BaselineInfo * baseline_info_lookup_or_add (MonoImage *base_image) { BaselineInfo *info; table_to_image_lock (); info = g_hash_table_lookup (baseline_image_to_info, base_image); if (!info) { info = baseline_info_init (base_image); g_hash_table_insert (baseline_image_to_info, base_image, info); } table_to_image_unlock (); return info; } static void baseline_info_remove (MonoImage *base_image) { table_to_image_lock (); g_hash_table_remove (baseline_image_to_info, base_image); table_to_image_unlock (); } static BaselineInfo * baseline_info_lookup (MonoImage *base_image) { BaselineInfo *info; table_to_image_lock (); info = g_hash_table_lookup (baseline_image_to_info, base_image); table_to_image_unlock (); return info; } static DeltaInfo* delta_info_init (MonoImage *image_dmeta, MonoImage *image_base, MonoPPDBFile *ppdb_file, BaselineInfo *base_info, uint32_t generation, DeltaInfo **prev_last_delta); static void free_ppdb_entry (gpointer key, gpointer val, gpointer user_data) { g_free (val); } static void delta_info_destroy (DeltaInfo *dinfo) { if (dinfo->method_table_update) g_hash_table_destroy (dinfo->method_table_update); if (dinfo->method_ppdb_table_update) { g_hash_table_foreach (dinfo->method_ppdb_table_update, free_ppdb_entry, NULL); g_hash_table_destroy (dinfo->method_ppdb_table_update); } mono_ppdb_close (dinfo->ppdb_file); if (dinfo->pool) mono_mempool_destroy (dinfo->pool); g_free (dinfo); } static DeltaInfo * delta_info_lookup_locked (MonoImage *delta_image) { return (DeltaInfo*)g_hash_table_lookup (delta_image_to_info, delta_image); } static DeltaInfo * delta_info_lookup (MonoImage *delta_image) { DeltaInfo *result; table_to_image_lock (); result = delta_info_lookup_locked (delta_image); g_assert (!result || result->delta_image == delta_image); table_to_image_unlock (); return result; } static void table_to_image_init (void) { mono_coop_mutex_init (&table_to_image_mutex); table_to_image = g_hash_table_new (NULL, NULL); delta_image_to_info = g_hash_table_new (NULL, NULL); baseline_image_to_info = g_hash_table_new (NULL, NULL); } static gboolean remove_base_image (gpointer key, gpointer value, gpointer user_data) { MonoImage *base_image = (MonoImage*)user_data; MonoImage *value_image = (MonoImage*)value; return (value_image == base_image); } void hot_reload_cleanup_on_close (MonoImage *image) { table_to_image_lock (); /* remove all keys (delta images) that map to the given image (base image) */ g_hash_table_foreach_remove (table_to_image, remove_base_image, (gpointer)image); table_to_image_unlock (); } void hot_reload_close_except_pools_all (MonoImage *base_image) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return; for (GList *ptr = info->delta_info; ptr; ptr = ptr->next) { DeltaInfo *info = (DeltaInfo *)ptr->data; MonoImage *image = info->delta_image; if (image) { table_to_image_lock (); g_hash_table_remove (delta_image_to_info, image); table_to_image_unlock (); /* if for some reason the image has other references, break the link to this delta_info that is going away */ if (!mono_image_close_except_pools (image)) info->delta_image = NULL; } } } void hot_reload_close_all (MonoImage *base_image) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return; for (GList *ptr = info->delta_info; ptr; ptr = ptr->next) { DeltaInfo *info = (DeltaInfo *)ptr->data; if (!info) continue; MonoImage *image = info->delta_image; if (image) { mono_image_close_finish (image); } delta_info_destroy (info); ptr->data = NULL; } g_list_free (info->delta_info); baseline_info_remove (base_image); baseline_info_destroy (info); } static void table_to_image_add (MonoImage *base_image) { /* If at least one table from this image is already here, they all are */ if (g_hash_table_contains (table_to_image, &base_image->tables[MONO_TABLE_MODULE])) return; table_to_image_lock (); if (g_hash_table_contains (table_to_image, &base_image->tables[MONO_TABLE_MODULE])) { table_to_image_unlock (); return; } for (int idx = 0; idx < MONO_TABLE_NUM; ++idx) { MonoTableInfo *table = &base_image->tables[idx]; g_hash_table_insert (table_to_image, table, base_image); } table_to_image_unlock (); } static MonoImage * table_info_get_base_image (const MonoTableInfo *t) { MonoImage *image = (MonoImage *) g_hash_table_lookup (table_to_image, t); return image; } /* Given a table, find the base image that it came from and its table index */ static gboolean table_info_find_in_base (const MonoTableInfo *table, MonoImage **base_out, int *tbl_index) { g_assert (base_out); *base_out = NULL; MonoImage *base = table_info_get_base_image (table); if (!base) return FALSE; *base_out = base; /* Invariant: `table` must be a `MonoTableInfo` of the base image. */ g_assert (base->tables < table && table < &base->tables [MONO_TABLE_LAST]); if (tbl_index) { size_t s = ALIGN_TO (sizeof (MonoTableInfo), sizeof (gpointer)); *tbl_index = ((intptr_t) table - (intptr_t) base->tables) / s; } return TRUE; } static MonoImage* image_open_dmeta_from_data (MonoImage *base_image, uint32_t generation, gconstpointer dmeta_bytes, uint32_t dmeta_length); static DeltaInfo* image_append_delta (MonoImage *base, BaselineInfo *base_info, MonoImage *delta, DeltaInfo *delta_info); /* common method, don't use directly, use add_method_to_baseline, add_field_to_baseline, etc */ static void add_member_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t member_token); static void add_method_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t method_token, MonoDebugInformationEnc* pdb_address); static void add_field_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t field_token); void hot_reload_init (void) { table_to_image_init (); mono_native_tls_alloc (&exposed_generation_id, NULL); /* See CMiniMdRW::ApplyDelta in metamodelenc.cpp in CoreCLR */ m_SuppressedDeltaColumns[MONO_TABLE_EVENTMAP] = (1 << MONO_EVENT_MAP_EVENTLIST); m_SuppressedDeltaColumns[MONO_TABLE_PROPERTYMAP] = (1 << MONO_PROPERTY_MAP_PROPERTY_LIST); m_SuppressedDeltaColumns[MONO_TABLE_METHOD] = (1 << MONO_METHOD_PARAMLIST); m_SuppressedDeltaColumns[MONO_TABLE_TYPEDEF] = (1 << MONO_TYPEDEF_FIELD_LIST)|(1<<MONO_TYPEDEF_METHOD_LIST); } static void hot_reload_update_published_invoke_hook (MonoAssemblyLoadContext *alc, uint32_t generation) { if (mono_get_runtime_callbacks ()->metadata_update_published) mono_get_runtime_callbacks ()->metadata_update_published (alc, generation); } static uint32_t update_published, update_alloc_frontier; static MonoCoopMutex publish_mutex; static void publish_lock (void) { mono_coop_mutex_lock (&publish_mutex); } static void publish_unlock (void) { mono_coop_mutex_unlock (&publish_mutex); } static mono_lazy_init_t metadata_update_lazy_init; static void initialize (void) { mono_coop_mutex_init (&publish_mutex); } static void thread_set_exposed_generation (uint32_t value) { mono_native_tls_set_value (exposed_generation_id, GUINT_TO_POINTER((guint)value)); } /** * LOCKING: assumes the publish_lock is held */ static void hot_reload_set_has_updates (void) { g_assert (metadata_update_data_ptr != NULL); metadata_update_data_ptr->has_updates = 1; } static uint32_t hot_reload_update_prepare (void) { mono_lazy_initialize (&metadata_update_lazy_init, initialize); /* * TODO: assert that the updater isn't depending on current metadata, else publishing might block. */ publish_lock (); uint32_t alloc_gen = ++update_alloc_frontier; /* Have to set this here so the updater starts using the slow path of metadata lookups */ hot_reload_set_has_updates (); /* Expose the alloc frontier to the updater thread */ thread_set_exposed_generation (alloc_gen); return alloc_gen; } static gboolean G_GNUC_UNUSED hot_reload_update_available (void) { return update_published < update_alloc_frontier; } /** * hot_reaload_thread_expose_published: * * Allow the current thread to see the latest published deltas. * * Returns the current published generation that the thread will see. */ uint32_t hot_reload_thread_expose_published (void) { mono_memory_read_barrier (); uint32_t thread_current_gen = update_published; thread_set_exposed_generation (thread_current_gen); return thread_current_gen; } /** * hot_reload_get_thread_generation: * * Return the published generation that the current thread is allowed to see. * May be behind the latest published generation if the thread hasn't called * \c mono_metadata_update_thread_expose_published in a while. */ uint32_t hot_reload_get_thread_generation (void) { return (uint32_t)GPOINTER_TO_UINT(mono_native_tls_get_value(exposed_generation_id)); } static gboolean G_GNUC_UNUSED hot_reload_wait_for_update (uint32_t timeout_ms) { /* TODO: give threads a way to voluntarily wait for an update to be published. */ g_assert_not_reached (); } static void hot_reload_update_publish (MonoAssemblyLoadContext *alc, uint32_t generation) { g_assert (update_published < generation && generation <= update_alloc_frontier); /* TODO: wait for all threads that are using old metadata to update. */ hot_reload_update_published_invoke_hook (alc, generation); update_published = update_alloc_frontier; mono_memory_write_barrier (); publish_unlock (); } static void hot_reload_update_cancel (uint32_t generation) { g_assert (update_alloc_frontier == generation); g_assert (update_alloc_frontier > 0); g_assert (update_alloc_frontier - 1 >= update_published); --update_alloc_frontier; /* Roll back exposed generation to the last published one */ thread_set_exposed_generation (update_published); publish_unlock (); } static void add_class_info_to_baseline (MonoClass *klass, MonoClassMetadataUpdateInfo *klass_info) { MonoImage *image = m_class_get_image (klass); BaselineInfo *baseline_info = baseline_info_lookup (image); baseline_info->klass_info = g_slist_prepend (baseline_info->klass_info, klass_info); } static MonoClassMetadataUpdateInfo * mono_class_get_or_add_metadata_update_info (MonoClass *klass) { MonoClassMetadataUpdateInfo *info = NULL; info = mono_class_get_metadata_update_info (klass); if (info) return info; mono_loader_lock (); info = mono_class_get_metadata_update_info (klass); if (!info) { info = mono_class_alloc0 (klass, sizeof (MonoClassMetadataUpdateInfo)); add_class_info_to_baseline (klass, info); mono_class_set_metadata_update_info (klass, info); } mono_loader_unlock (); g_assert (info); return info; } /* * Given a baseline and an (optional) previous delta, allocate space for new tables for the current delta. * * Assumes the DeltaInfo:count info has already been calculated and initialized. */ static void delta_info_initialize_mutants (const MonoImage *base, const BaselineInfo *base_info, const DeltaInfo *prev_delta, DeltaInfo *delta) { g_assert (delta->pool); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Initializing mutant tables for image %p (generation %d)", base, delta->generation); for (int i = 0; i < MONO_TABLE_NUM; ++i) { gboolean need_copy = FALSE; /* if any generation modified any row of this table, make a copy for the current generation. */ if (base_info->any_modified_rows [i]) need_copy = TRUE; delta_row_count *count = &delta->count [i]; guint32 base_rows = table_info_get_rows (&base->tables [i]); /* if some previous generation added rows, or we're adding rows, make a copy */ if (base_rows != count->prev_gen_rows || count->inserted_rows) need_copy = TRUE; if (!need_copy) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, " Table 0x%02x unchanged (rows: base %d, prev %d, inserted %d), not copied", i, base_rows, count->prev_gen_rows, count->inserted_rows); continue; } else { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, " Table 0x%02x changed (rows: base %d, prev %d, inserted %d), IS copied", i, base_rows, count->prev_gen_rows, count->inserted_rows); } /* The invariant is that once we made a copy in any previous generation, we'll make * a copy in this generation. So subsequent generations can copy either from the * immediately preceeding generation or from the baseline if the preceeding * generation didn't make a copy. */ guint32 rows = count->prev_gen_rows + count->inserted_rows; const MonoTableInfo *prev_table; if (!prev_delta || prev_delta->mutants [i].base == NULL) prev_table = &base->tables [i]; else prev_table = &prev_delta->mutants [i]; g_assert (prev_table != NULL); MonoTableInfo *tbl = &delta->mutants [i]; if (prev_table->rows_ == 0) { /* table was empty in the baseline and it was empty in the prior generation, but now we have some rows. Use the format of the mutant table. */ g_assert (prev_table->row_size == 0); tbl->row_size = delta->delta_image->tables [i].row_size; tbl->size_bitfield = delta->delta_image->tables [i].size_bitfield; } else { tbl->row_size = prev_table->row_size; tbl->size_bitfield = prev_table->size_bitfield; } tbl->rows_ = rows; g_assert (tbl->rows_ > 0 && tbl->row_size != 0); tbl->base = mono_mempool_alloc (delta->pool, tbl->row_size * rows); g_assert (table_info_get_rows (prev_table) == count->prev_gen_rows); /* copy the old rows and zero out the new ones */ memcpy ((char*)tbl->base, prev_table->base, count->prev_gen_rows * tbl->row_size); memset (((char*)tbl->base) + count->prev_gen_rows * tbl->row_size, 0, count->inserted_rows * tbl->row_size); } } /** * LOCKING: Assumes the publish_lock is held * Returns: The previous latest delta, or NULL if this is the first delta */ DeltaInfo * image_append_delta (MonoImage *base, BaselineInfo *base_info, MonoImage *delta, DeltaInfo *delta_info) { if (!base_info->delta_info) { base_info->delta_info = base_info->delta_info_last = g_list_alloc (); base_info->delta_info->data = (gpointer)delta_info; mono_memory_write_barrier (); /* Have to set this here so that passes over the metadata in the updater thread start using the slow path */ base->has_updates = TRUE; return NULL; } DeltaInfo *prev_last_delta = (DeltaInfo*)base_info->delta_info_last->data; g_assert (prev_last_delta->generation < delta_info->generation); /* g_list_append returns the given list, not the newly appended */ GList *l = g_list_append (base_info->delta_info_last, delta_info); g_assert (l != NULL && l->next != NULL && l->next->next == NULL); base_info->delta_info_last = l->next; mono_memory_write_barrier (); /* Have to set this here so that passes over the metadata in the updater thread start using the slow path */ base->has_updates = TRUE; return prev_last_delta; } /** * LOCKING: assumes the publish_lock is held */ MonoImage* image_open_dmeta_from_data (MonoImage *base_image, uint32_t generation, gconstpointer dmeta_bytes, uint32_t dmeta_length) { MonoImageOpenStatus status; MonoAssemblyLoadContext *alc = mono_image_get_alc (base_image); MonoImage *dmeta_image = mono_image_open_from_data_internal (alc, (char*)dmeta_bytes, dmeta_length, TRUE, &status, TRUE, NULL, NULL); g_assert (dmeta_image != NULL); g_assert (status == MONO_IMAGE_OK); return dmeta_image; } static gpointer open_dil_data (MonoImage *base_image G_GNUC_UNUSED, gconstpointer dil_src, uint32_t dil_length) { /* TODO: find a better memory manager. But this way we at least won't lose the IL data. */ MonoMemoryManager *mem_manager = (MonoMemoryManager *)mono_alc_get_default ()->memory_manager; gpointer dil_copy = mono_mem_manager_alloc (mem_manager, dil_length); memcpy (dil_copy, dil_src, dil_length); return dil_copy; } static const char * scope_to_string (uint32_t tok) { const char *scope; switch (tok & MONO_RESOLUTION_SCOPE_MASK) { case MONO_RESOLUTION_SCOPE_MODULE: scope = "."; break; case MONO_RESOLUTION_SCOPE_MODULEREF: scope = "M"; break; case MONO_RESOLUTION_SCOPE_TYPEREF: scope = "T"; break; case MONO_RESOLUTION_SCOPE_ASSEMBLYREF: scope = "A"; break; default: g_assert_not_reached (); } return scope; } static void dump_update_summary (MonoImage *image_base, MonoImage *image_dmeta) { int rows; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta tables:"); for (int idx = 0; idx < MONO_TABLE_NUM; ++idx) { if (image_dmeta->tables [idx].base) mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "\t0x%02x \"%s\"", idx, mono_meta_table_name (idx)); } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); rows = mono_image_get_table_rows (image_base, MONO_TABLE_TYPEREF); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_TYPEREF_SIZE]; mono_metadata_decode_row (&image_base->tables [MONO_TABLE_TYPEREF], i - 1, cols, MONO_TYPEREF_SIZE); const char *scope = scope_to_string (cols [MONO_TYPEREF_SCOPE]); const char *name = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAME]); const char *nspace = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAMESPACE]); if (!name) name = "<N/A>"; if (!nspace) nspace = "<N/A>"; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base typeref i=%d (token=0x%08x) -> scope=%s, namespace=%s, name=%s", i, MONO_TOKEN_TYPE_REF | i, scope, nspace, name); } if (!image_dmeta->minimal_delta) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "--------------------------------"); rows = mono_image_get_table_rows (image_dmeta, MONO_TABLE_TYPEREF); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_TYPEREF_SIZE]; mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_TYPEREF], i - 1, cols, MONO_TYPEREF_SIZE); const char *scope = scope_to_string (cols [MONO_TYPEREF_SCOPE]); const char *name = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAME]); const char *nspace = mono_metadata_string_heap (image_base, cols [MONO_TYPEREF_NAMESPACE]); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta typeref i=%d (token=0x%08x) -> scope=%s, nspace=%s, name=%s", i, MONO_TOKEN_TYPE_REF | i, scope, nspace, name); } } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); rows = mono_image_get_table_rows (image_base, MONO_TABLE_METHOD); for (int i = 1; i <= rows ; ++i) { guint32 cols [MONO_METHOD_SIZE]; mono_metadata_decode_row_raw (&image_base->tables [MONO_TABLE_METHOD], i - 1, cols, MONO_METHOD_SIZE); const char *name = mono_metadata_string_heap (image_base, cols [MONO_METHOD_NAME]); guint32 rva = cols [MONO_METHOD_RVA]; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base method i=%d (token=0x%08x), rva=%d/0x%04x, name=%s", i, MONO_TOKEN_METHOD_DEF | i, rva, rva, name); } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "--------------------------------"); rows = mono_image_get_table_rows (image_dmeta, MONO_TABLE_METHOD); for (int i = 1; i <= rows ; ++i) { guint32 cols [MONO_METHOD_SIZE]; mono_metadata_decode_row_raw (&image_dmeta->tables [MONO_TABLE_METHOD], i - 1, cols, MONO_METHOD_SIZE); const char *name = mono_metadata_string_heap (image_base, cols [MONO_METHOD_NAME]); guint32 rva = cols [MONO_METHOD_RVA]; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta method i=%d (token=0x%08x), rva=%d/0x%04x, name=%s", i, MONO_TOKEN_METHOD_DEF | i, rva, rva, name); } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); rows = mono_image_get_table_rows (image_base, MONO_TABLE_STANDALONESIG); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE]; mono_metadata_decode_row (&image_base->tables [MONO_TABLE_STANDALONESIG], i - 1, cols, MONO_STAND_ALONE_SIGNATURE_SIZE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base standalonesig i=%d (token=0x%08x) -> 0x%08x", i, MONO_TOKEN_SIGNATURE | i, cols [MONO_STAND_ALONE_SIGNATURE]); } if (!image_dmeta->minimal_delta) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "--------------------------------"); rows = mono_image_get_table_rows (image_dmeta, MONO_TABLE_STANDALONESIG); for (int i = 1; i <= rows; ++i) { guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE]; mono_metadata_decode_row_raw (&image_dmeta->tables [MONO_TABLE_STANDALONESIG], i - 1, cols, MONO_STAND_ALONE_SIGNATURE_SIZE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta standalonesig i=%d (token=0x%08x) -> 0x%08x", i, MONO_TOKEN_SIGNATURE | i, cols [MONO_STAND_ALONE_SIGNATURE]); } } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "================================"); } /* * Finds the latest mutated version of the table given by tbl_index * * On success returns TRUE, modifies *t and optionally updates *delta_out */ static gboolean effective_table_mutant (MonoImage *base, BaselineInfo *info, int tbl_index, const MonoTableInfo **t, DeltaInfo **delta_out) { GList *ptr =info->delta_info_last; uint32_t exposed_gen = hot_reload_get_thread_generation (); MonoImage *dmeta = NULL; DeltaInfo *delta_info = NULL; /* walk backward from the latest image until we find one that matches the current thread's exposed generation */ do { delta_info = (DeltaInfo*)ptr->data; dmeta = delta_info->delta_image; if (delta_info->generation <= exposed_gen) break; ptr = ptr->prev; } while (ptr); if (!ptr) return FALSE; g_assert (dmeta != NULL); g_assert (delta_info != NULL); *t = &delta_info->mutants [tbl_index]; if (delta_out) *delta_out = delta_info; return TRUE; } void hot_reload_effective_table_slow (const MonoTableInfo **t, int idx) { /* FIXME: don't let any thread other than the updater thread see values from a delta image * with a generation past update_published */ MonoImage *base; int tbl_index; if (!table_info_find_in_base (*t, &base, &tbl_index)) return; BaselineInfo *info = baseline_info_lookup (base); if (!info) return; gboolean success = effective_table_mutant (base, info, tbl_index, t, NULL); g_assert (success); } /* * The ENCMAP table contains the base of the relative offset. * * Returns -1 if the token does not resolve in this generation's ENCMAP. * * Example: * Say you have a base image with a METHOD table having 5 entries. The minimal * delta image adds another one, so it would be indexed with token * `MONO_TOKEN_METHOD_DEF | 6`. However, the minimal delta image only has this * single entry, and thus this would be an out-of-bounds access. That's where * the ENCMAP table comes into play: It will have an entry * `MONO_TOKEN_METHOD_DEF | 5`, so before accessing the new entry in the * minimal delta image, it has to be substracted. Thus the new relative index * is `1`, and no out-of-bounds acccess anymore. * * One can assume that ENCMAP is sorted (todo: verify this claim). * * BTW, `enc_recs` is just a pre-computed map to make the lookup for the * relative index faster. */ int hot_reload_relative_delta_index (MonoImage *image_dmeta, DeltaInfo *delta_info, int token) { MonoTableInfo *encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; int table = mono_metadata_token_table (token); int index = mono_metadata_token_index (token); int index_map = delta_info->enc_recs [table]; int encmap_rows = table_info_get_rows (encmap); if (!table_info_get_rows (encmap) || !image_dmeta->minimal_delta) return mono_metadata_token_index (token); /* if the table didn't have any updates in this generation and the * table index is bigger than the last table that got updates, * enc_recs will point past the last row */ if (index_map - 1 == encmap_rows) return -1; guint32 cols[MONO_ENCMAP_SIZE]; mono_metadata_decode_row (encmap, index_map - 1, cols, MONO_ENCMAP_SIZE); int map_entry = cols [MONO_ENCMAP_TOKEN]; /* we're looking at the beginning of a sequence of encmap rows that are all the * modifications+additions for the table we are looking for (or we're looking at an entry * for the next table after the one we wanted). the map entries will have tokens in * increasing order. skip over the rows where the tokens are not the one we want, until we * hit the rows for the next table or we hit the end of the encmap */ while (mono_metadata_token_table (map_entry) == table && mono_metadata_token_index (map_entry) < index && index_map < encmap_rows) { mono_metadata_decode_row (encmap, ++index_map - 1, cols, MONO_ENCMAP_SIZE); map_entry = cols [MONO_ENCMAP_TOKEN]; } if (mono_metadata_token_table (map_entry) == table) { if (mono_metadata_token_index (map_entry) == index) { /* token resolves to this generation */ int return_val = index_map - delta_info->enc_recs [table] + 1; g_assert (return_val > 0 && return_val <= table_info_get_rows (&image_dmeta->tables[table])); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "relative index for token 0x%08x -> table 0x%02x row 0x%08x", token, table, return_val); return return_val; } else { /* Otherwise we stopped either: because we saw an an entry for a row after * the one we wanted - we were looking for a modification, but the encmap * has an addition; or, because we saw the last entry in the encmap and it * still wasn't for a row as high as the one we wanted. either way, the * update we want is not in the delta we're looking at. */ g_assert ((mono_metadata_token_index (map_entry) > index) || (mono_metadata_token_index (map_entry) < index && index_map == encmap_rows)); return -1; } } else { /* otherwise there are no more encmap entries for this table, and we didn't see the * index, so there was no modification/addition for that index in this delta. */ g_assert (mono_metadata_token_table (map_entry) > table); return -1; } } /* LOCKING: assumes publish_lock is held */ static DeltaInfo* delta_info_init (MonoImage *image_dmeta, MonoImage *image_base, MonoPPDBFile *ppdb_file, BaselineInfo *base_info, uint32_t generation, DeltaInfo **prev_delta_info) { MonoTableInfo *encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; g_assert (!delta_info_lookup (image_dmeta)); if (!table_info_get_rows (encmap)) return NULL; DeltaInfo *delta_info = g_malloc0 (sizeof (DeltaInfo)); delta_info->generation = generation; delta_info->ppdb_file = ppdb_file; delta_info->delta_image = image_dmeta; table_to_image_lock (); g_hash_table_insert (delta_image_to_info, image_dmeta, delta_info); table_to_image_unlock (); delta_info->pool = mono_mempool_new (); g_assert (prev_delta_info); /* base_image takes ownership of 1 refcount ref of dmeta_image */ *prev_delta_info = image_append_delta (image_base, base_info, image_dmeta, delta_info); return delta_info; } /* LOCKING: assumes publish_lock is held */ static gboolean delta_info_compute_table_records (MonoImage *image_dmeta, MonoImage *image_base, BaselineInfo *base_info, DeltaInfo *delta_info) { MonoTableInfo *encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; int table, prev_table = -1, idx; /*** Compute logical table sizes ***/ if (base_info->delta_info == base_info->delta_info_last) { /* this is the first update. */ for (int i = 0; i < MONO_TABLE_NUM; ++i) { delta_info->count[i].prev_gen_rows = table_info_get_rows (&image_base->tables[i]); } } else { g_assert (delta_info == (DeltaInfo*)base_info->delta_info_last->data); g_assert (base_info->delta_info_last->prev != NULL); DeltaInfo *prev_gen_info = (DeltaInfo*)base_info->delta_info_last->prev->data; for (int i = 0; i < MONO_TABLE_NUM; ++i) { delta_info->count[i].prev_gen_rows = prev_gen_info->count[i].prev_gen_rows + prev_gen_info->count[i].inserted_rows; } } /* TODO: while going through the tables, update delta_info->count[tbl].{modified,inserted}_rows */ int encmap_rows = table_info_get_rows (encmap); for (idx = 1; idx <= encmap_rows; ++idx) { guint32 cols[MONO_ENCMAP_SIZE]; mono_metadata_decode_row (encmap, idx - 1, cols, MONO_ENCMAP_SIZE); uint32_t tok = cols [MONO_ENCMAP_TOKEN]; table = mono_metadata_token_table (tok); uint32_t rid = mono_metadata_token_index (tok); g_assert (table >= 0 && table < MONO_TABLE_NUM); g_assert (table != MONO_TABLE_ENCLOG); g_assert (table != MONO_TABLE_ENCMAP); g_assert (table >= prev_table); if (rid <= delta_info->count[table].prev_gen_rows) { base_info->any_modified_rows[table] = TRUE; delta_info->count[table].modified_rows++; } else delta_info->count[table].inserted_rows++; if (table == prev_table) continue; while (prev_table < table) { prev_table++; delta_info->enc_recs [prev_table] = idx; } } g_assert (prev_table < MONO_TABLE_NUM - 1); while (prev_table < MONO_TABLE_NUM - 1) { prev_table++; delta_info->enc_recs [prev_table] = idx; } if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) { for (int i = 0 ; i < MONO_TABLE_NUM; ++i) { if (!image_dmeta->tables [i].base) continue; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "enc_recs [%02x] / %s = 0x%02x\t(inserted: %03d, modified: %03d)", i, mono_meta_table_name (i), delta_info->enc_recs[i], delta_info->count[i].inserted_rows, delta_info->count[i].modified_rows); } } return TRUE; } enum MonoEnCFuncCode { ENC_FUNC_DEFAULT = 0, ENC_FUNC_ADD_METHOD = 1, ENC_FUNC_ADD_FIELD = 2, ENC_FUNC_ADD_PARAM = 3, ENC_FUNC_ADD_PROPERTY = 4, ENC_FUNC_ADD_EVENT = 5, }; static const char* funccode_to_str (int func_code) { switch (func_code) { case 0: return "Func default"; case 1: return "Method Create"; case 2: return "Field Create"; case 3: return "Param Create"; case 4: return "Property Create"; case 5: return "Event Create"; default: g_assert_not_reached (); } return NULL; } /* * Apply the row from the delta image given by log_token to the cur_delta mutated table. * */ static void delta_info_mutate_row (MonoImage *image_dmeta, DeltaInfo *cur_delta, guint32 log_token) { int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); /* 1-based */ gboolean modified = token_index <= cur_delta->count [token_table].prev_gen_rows; int delta_index = hot_reload_relative_delta_index (image_dmeta, cur_delta, log_token); /* The complication here is that we want the mutant table to look like the table in * the baseline image with respect to column widths, but the delta tables are generally coming in * uncompressed (4-byte columns). So we have to copy one column at a time and adjust the * widths as we go. */ guint32 dst_bitfield = cur_delta->mutants [token_table].size_bitfield; guint32 src_bitfield = image_dmeta->tables [token_table].size_bitfield; const char *src_base = image_dmeta->tables [token_table].base + (delta_index - 1) * image_dmeta->tables [token_table].row_size; char *dst_base = (char*)cur_delta->mutants [token_table].base + (token_index - 1) * cur_delta->mutants [token_table].row_size; guint32 src_offset = 0, dst_offset = 0; for (int col = 0; col < mono_metadata_table_count (dst_bitfield); ++col) { guint32 dst_col_size = mono_metadata_table_size (dst_bitfield, col); guint32 src_col_size = mono_metadata_table_size (src_bitfield, col); if ((m_SuppressedDeltaColumns [token_table] & (1 << col)) == 0) { const char *src = src_base + src_offset; char *dst = dst_base + dst_offset; /* copy src to dst, via a temporary to adjust for size differences */ /* FIXME: unaligned access, endianness */ guint32 tmp; switch (src_col_size) { case 1: tmp = *(guint8*)src; break; case 2: tmp = *(guint16*)src; break; case 4: tmp = *(guint32*)src; break; default: g_assert_not_reached (); } /* FIXME: unaligned access, endianness */ switch (dst_col_size) { case 1: *(guint8*)dst = (guint8)tmp; break; case 2: *(guint16*)dst = (guint16)tmp; break; case 4: *(guint32*)dst = tmp; break; default: g_assert_not_reached (); } } src_offset += src_col_size; dst_offset += dst_col_size; } g_assert (dst_offset == cur_delta->mutants [token_table].row_size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "mutate: table=0x%02x row=0x%04x delta row=0x%04x %s", token_table, token_index, delta_index, modified ? "Mod" : "Add"); } static void prepare_mutated_rows (const MonoTableInfo *table_enclog, MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *delta_info) { int rows = table_info_get_rows (table_enclog); /* Prepare the mutated metadata tables */ for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; if (func_code != ENC_FUNC_DEFAULT) continue; delta_info_mutate_row (image_dmeta, delta_info, log_token); } } /* Run some sanity checks first. If we detect unsupported scenarios, this * function will fail and the metadata update should be aborted. This should * run before anything in the metadata world is updated. */ static gboolean apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *delta_info, gconstpointer dil_data, uint32_t dil_length, MonoError *error) { MonoTableInfo *table_enclog = &image_dmeta->tables [MONO_TABLE_ENCLOG]; int rows = table_info_get_rows (table_enclog); gboolean unsupported_edits = FALSE; /* hack: make a pass over it, looking only for table method updates, in * order to give more meaningful error messages first */ for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); // FIXME: the top bit 0x8000000 of log_token is some kind of // indicator see IsRecId in metamodelrw.cpp and // MDInternalRW::EnumDeltaTokensInit which skips over those // records when EditAndContinueModule::ApplyEditAndContinue is // iterating. int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x (%s idx=0x%02x) (base table has 0x%04x rows; prev gen had 0x%04x rows)\t%s\tfunc=0x%02x (\"%s\")\n", i, log_token, mono_meta_table_name (token_table), token_index, table_info_get_rows (&image_base->tables [token_table]), delta_info->count[token_table].prev_gen_rows, (is_addition ? "ADD" : "UPDATE"), func_code, funccode_to_str (func_code)); if (token_table != MONO_TABLE_METHOD) continue; #ifndef ALLOW_METHOD_ADD if (is_addition) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "\tcannot add new method with token 0x%08x", log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: cannot add new method with token 0x%08x", log_token); unsupported_edits = TRUE; } #endif #ifdef ALLOW_METHOD_ADD /* adding a new parameter to a new method is ok */ if (func_code == ENC_FUNC_ADD_PARAM && is_addition) continue; #endif g_assert (func_code == 0); /* anything else doesn't make sense here */ } for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; switch (token_table) { case MONO_TABLE_ASSEMBLYREF: /* okay, supported */ break; case MONO_TABLE_METHOD: #ifdef ALLOW_METHOD_ADD if (func_code == ENC_FUNC_ADD_PARAM) continue; /* ok, allowed */ #endif /* handled above */ break; case MONO_TABLE_FIELD: #ifdef ALLOW_FIELD_ADD if (func_code == ENC_FUNC_DEFAULT) continue; /* ok, allowed */ #else /* adding or modifying a field */ mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support adding or modifying fields.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding or modifying fields. token=0x%08x", log_token); unsupported_edits = TRUE; break; #endif case MONO_TABLE_PROPERTY: { /* modifying a property, ok */ if (!is_addition) break; /* adding a property */ mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support adding new properties.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding new properties. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } case MONO_TABLE_METHODSEMANTICS: { if (is_addition) { /* new rows are fine, as long as they point at existing methods */ guint32 sema_cols [MONO_METHOD_SEMA_SIZE]; int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); g_assert (mapped_token != -1); mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_METHODSEMANTICS], mapped_token - 1, sema_cols, MONO_METHOD_SEMA_SIZE); switch (sema_cols [MONO_METHOD_SEMA_SEMANTICS]) { case METHOD_SEMANTIC_GETTER: case METHOD_SEMANTIC_SETTER: { int prop_method_index = sema_cols [MONO_METHOD_SEMA_METHOD]; /* ok, if it's pointing to an existing getter/setter */ gboolean is_prop_method_add = prop_method_index-1 >= delta_info->count[MONO_TABLE_METHOD].prev_gen_rows; if (!is_prop_method_add) break; mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x adding new getter/setter method 0x%08x to a property is not supported", i, log_token, prop_method_index); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding a new getter or setter to a property, token=0x%08x", log_token); unsupported_edits = TRUE; continue; } default: mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x adding new non-getter/setter property or event methods is not supported.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding new non-getter/setter property or event methods. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } } else { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support patching of existing table cols.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing table cols. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } } case MONO_TABLE_CUSTOMATTRIBUTE: { if (!is_addition) { /* modifying existing rows is ok, as long as the parent and ctor are the same */ guint32 ca_upd_cols [MONO_CUSTOM_ATTR_SIZE]; guint32 ca_base_cols [MONO_CUSTOM_ATTR_SIZE]; int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); g_assert (mapped_token != -1); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x CUSTOM_ATTR update. mapped index = 0x%08x\n", i, log_token, mapped_token); mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_CUSTOMATTRIBUTE], mapped_token - 1, ca_upd_cols, MONO_CUSTOM_ATTR_SIZE); mono_metadata_decode_row (&image_base->tables [MONO_TABLE_CUSTOMATTRIBUTE], token_index - 1, ca_base_cols, MONO_CUSTOM_ATTR_SIZE); /* compare the ca_upd_cols [MONO_CUSTOM_ATTR_PARENT] to ca_base_cols [MONO_CUSTOM_ATTR_PARENT]. */ mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x CUSTOM_ATTR update. Old Parent 0x%08x New Parent 0x%08x\n", i, log_token, ca_base_cols [MONO_CUSTOM_ATTR_PARENT], ca_upd_cols [MONO_CUSTOM_ATTR_PARENT]); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x CUSTOM_ATTR update. Old ctor 0x%08x New ctor 0x%08x\n", i, log_token, ca_base_cols [MONO_CUSTOM_ATTR_TYPE], ca_upd_cols [MONO_CUSTOM_ATTR_TYPE]); /* TODO: when we support the ChangeCustomAttribute capability, the * parent might become 0 to delete attributes. It may also be the * case that the MONO_CUSTOM_ATTR_TYPE will change. Without that * capability, we trust that if the TYPE is not the same token, it * still resolves to the same MonoMethod* (but we can't check it in * pass1 because we haven't added the new AssemblyRefs yet. */ /* NOTE: Apparently Roslyn sometimes sends NullableContextAttribute * deletions even if the ChangeCustomAttribute capability is unset. * So tacitly accept updates where a custom attribute is deleted * (its parent is set to 0). Once we support custom attribute * changes, we will support this kind of deletion for real. */ if (ca_base_cols [MONO_CUSTOM_ATTR_PARENT] != ca_upd_cols [MONO_CUSTOM_ATTR_PARENT] && ca_upd_cols [MONO_CUSTOM_ATTR_PARENT] != 0) { mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing CA table cols with a different Parent. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } break; } else { /* Added a row. ok */ break; } } case MONO_TABLE_PARAM: { if (!is_addition) { /* We only allow modifications where the parameter name doesn't change. */ uint32_t base_param [MONO_PARAM_SIZE]; uint32_t upd_param [MONO_PARAM_SIZE]; int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); g_assert (mapped_token != -1); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x PARAM update. mapped index = 0x%08x\n", i, log_token, mapped_token); mono_metadata_decode_row (&image_dmeta->tables [MONO_TABLE_PARAM], mapped_token - 1, upd_param, MONO_PARAM_SIZE); mono_metadata_decode_row (&image_base->tables [MONO_TABLE_PARAM], token_index - 1, base_param, MONO_PARAM_SIZE); const char *base_name = mono_metadata_string_heap (image_base, base_param [MONO_PARAM_NAME]); const char *upd_name = mono_metadata_string_heap (image_base, upd_param [MONO_PARAM_NAME]); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x: 0x%08x PARAM update: seq = %d (base = %d), name = '%s' (base = '%s')\n", i, log_token, upd_param [MONO_PARAM_SEQUENCE], base_param [MONO_PARAM_SEQUENCE], upd_name, base_name); if (strcmp (base_name, upd_name) != 0 || base_param [MONO_PARAM_SEQUENCE] != upd_param [MONO_PARAM_SEQUENCE]) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support patching of existing PARAM table cols.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing PARAM table cols. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } break; } else break; /* added a row. ok */ } case MONO_TABLE_TYPEDEF: { gboolean new_class G_GNUC_UNUSED = is_addition; #ifdef ALLOW_METHOD_ADD /* only allow adding methods to existing classes for now */ if ( #ifndef ALLOW_CLASS_ADD !new_class && #endif func_code == ENC_FUNC_ADD_METHOD) { /* next record should be a MONO_TABLE_METHOD addition (func == default) */ g_assert (i + 1 < rows); guint32 next_cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i + 1, next_cols, MONO_ENCLOG_SIZE); g_assert (next_cols [MONO_ENCLOG_FUNC_CODE] == ENC_FUNC_DEFAULT); int next_token = next_cols [MONO_ENCLOG_TOKEN]; int next_table = mono_metadata_token_table (next_token); int next_index = mono_metadata_token_index (next_token); g_assert (next_table == MONO_TABLE_METHOD); /* expecting an added method */ g_assert (next_index-1 >= delta_info->count[next_table].prev_gen_rows); i++; /* skip the next record */ continue; } #endif #ifdef ALLOW_FIELD_ADD if ( #ifndef ALLOW_CLASS_ADD !new_class && #endif func_code == ENC_FUNC_ADD_FIELD) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x AddField to klass 0x%08x, skipping next EnClog record", i, log_token, token_index); g_assert (i + 1 < rows); guint32 next_cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i + 1, next_cols, MONO_ENCLOG_SIZE); g_assert (next_cols [MONO_ENCLOG_FUNC_CODE] == ENC_FUNC_DEFAULT); int next_token = next_cols [MONO_ENCLOG_TOKEN]; int next_table = mono_metadata_token_table (next_token); int next_index = mono_metadata_token_index (next_token); g_assert (next_table == MONO_TABLE_FIELD); /* expecting an added field */ g_assert (next_index-1 >= delta_info->count[next_table].prev_gen_rows); i++; /* skip the next record */ continue; } #endif /* fallthru */ } default: if (!is_addition) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support patching of existing table cols.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing table cols. token=0x%08x", log_token); unsupported_edits = TRUE; continue; } } /* * So the way a non-default func_code works is that it's attached to the EnCLog * record preceeding the new member defintion (so e.g. an addMethod code will be on * the preceeding MONO_TABLE_TYPEDEF enc record that identifies the parent type). */ switch (func_code) { case ENC_FUNC_DEFAULT: /* default */ break; default: mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x FunCode %d (%s) not supported (token=0x%08x)", i, log_token, func_code, funccode_to_str (func_code), log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: FuncCode %d (%s) not supported (token=0x%08x)", func_code, funccode_to_str (func_code), log_token); unsupported_edits = TRUE; continue; } } return !unsupported_edits; } static void set_delta_method_debug_info (DeltaInfo *delta_info, uint32_t token_index, MonoDebugInformationEnc *pdb_address) { g_hash_table_insert (delta_info->method_ppdb_table_update, GUINT_TO_POINTER (token_index), (gpointer) pdb_address); } static void set_update_method (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, MonoImage *image_dmeta, DeltaInfo *delta_info, uint32_t token_index, const char* il_address, MonoDebugInformationEnc* pdb_address) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "setting method 0x%08x in g=%d IL=%p", token_index, generation, (void*)il_address); /* FIXME: this is a race if other threads are doing a lookup. */ g_hash_table_insert (base_info->method_table_update, GUINT_TO_POINTER (token_index), GUINT_TO_POINTER (generation)); g_hash_table_insert (delta_info->method_table_update, GUINT_TO_POINTER (token_index), (gpointer) il_address); set_delta_method_debug_info (delta_info, token_index, pdb_address); } static MonoDebugInformationEnc * hot_reload_get_method_debug_information (MonoPPDBFile *ppdb_file, int idx) { if (!ppdb_file) return NULL; MonoImage *image_dppdb = ppdb_file->image; MonoTableInfo *table_encmap = &image_dppdb->tables [MONO_TABLE_ENCMAP]; int rows = table_info_get_rows (table_encmap); for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCMAP_SIZE]; mono_metadata_decode_row (table_encmap, i, cols, MONO_ENCMAP_SIZE); int map_token = cols [MONO_ENCMAP_TOKEN]; int token_table = mono_metadata_token_table (map_token); if (token_table == MONO_TABLE_METHODBODY) { int token_index = mono_metadata_token_index (map_token); if (token_index == idx) { MonoDebugInformationEnc *encDebugInfo = g_new0 (MonoDebugInformationEnc, 1); encDebugInfo->idx = i + 1; encDebugInfo->ppdb_file = ppdb_file; return encDebugInfo; } } } return NULL; } static void G_GNUC_UNUSED dump_assembly_ref_names (MonoImage *image) { if (!mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) return; for (int i = 0; i < image->nreferences; ++i) { ERROR_DECL(local_error); MonoAssemblyName aname; mono_assembly_get_assemblyref_checked (image, i, &aname, local_error); if (is_ok (local_error)) mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Reference[%02d] = '%s'", i, aname.name); else { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Reference[%02d] error '%s'", i, mono_error_get_message (local_error)); mono_error_cleanup (local_error); } } } /* do actuall enclog application */ static gboolean apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, MonoImage *image_dmeta, DeltaInfo *delta_info, gconstpointer dil_data, uint32_t dil_length, MonoError *error) { MonoTableInfo *table_enclog = &image_dmeta->tables [MONO_TABLE_ENCLOG]; int rows = table_info_get_rows (table_enclog); /* NOTE: Suppressed colums * * Certain column values in some tables in the deltas are not meant to be applied over the * previous generation. See CMiniMdRW::m_SuppressedDeltaColumns in CoreCLR. For example the * MONO_METHOD_PARAMLIST column in MONO_TABLE_METHOD is always 0 in an update - for modified * rows the previous value must be carried over. For added rows, it is supposed to be * initialized to the end of the param table and updated with the "Param create" func code * in subsequent EnCLog records. * * For mono's immutable model (where we don't change the baseline image data), we will need * to mutate the delta image tables to incorporate the suppressed column values from the * previous generation. * * For Baseline capabilities, the only suppressed column is MONO_METHOD_PARAMLIST - which we * can ignore because we don't do anything with param updates and the only column we care * about is MONO_METHOD_RVA which gets special case treatment with set_update_method(). * * But when we implement additional capabilities (for example UpdateParameters), we will * need to start mutating the delta image tables to pick up the suppressed column values. * Fortunately whether we get the delta from the debugger or from the runtime API, we always * have it in writable memory (and not mmap-ed pages), so we can rewrite the table values. */ mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Pass 2 begin: base '%s' delta image=%p", image_base->name, image_dmeta); #if defined(ALLOW_METHOD_ADD) || defined(ALLOW_FIELD_ADD) MonoClass *add_member_klass = NULL; #endif gboolean assemblyref_updated = FALSE; for (int i = 0; i < rows ; ++i) { guint32 cols [MONO_ENCLOG_SIZE]; mono_metadata_decode_row (table_enclog, i, cols, MONO_ENCLOG_SIZE); int log_token = cols [MONO_ENCLOG_TOKEN]; int func_code = cols [MONO_ENCLOG_FUNC_CODE]; int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "enclog i=%d: token=0x%08x (table=%s): %d:\t%s", i, log_token, mono_meta_table_name (token_table), func_code, (is_addition ? "ADD" : "UPDATE")); /* TODO: See CMiniMdRW::ApplyDelta for how to drive this. */ switch (func_code) { case ENC_FUNC_DEFAULT: /* default */ break; #ifdef ALLOW_METHOD_ADD case ENC_FUNC_ADD_METHOD: { g_assert (token_table == MONO_TABLE_TYPEDEF); MonoClass *klass = mono_class_get_checked (image_base, log_token, error); if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Can't get class with token 0x%08x due to: %s", log_token, mono_error_get_message (error)); return FALSE; } add_member_klass = klass; break; } case ENC_FUNC_ADD_PARAM: { g_assert (token_table == MONO_TABLE_METHOD); break; } #endif #ifdef ALLOW_FIELD_ADD case ENC_FUNC_ADD_FIELD: { g_assert (token_table == MONO_TABLE_TYPEDEF); MonoClass *klass = mono_class_get_checked (image_base, log_token, error); if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Can't get class with token 0x%08x due to: %s", log_token, mono_error_get_message (error)); return FALSE; } add_member_klass = klass; break; } #endif default: g_error ("EnC: unsupported FuncCode, should be caught by pass1"); break; } switch (token_table) { case MONO_TABLE_ASSEMBLYREF: { g_assert (token_index > table_info_get_rows (&image_base->tables [token_table])); if (assemblyref_updated) continue; assemblyref_updated = TRUE; /* FIXME: use DeltaInfo:prev_gen_rows instead of looping */ /* TODO: do we know that there will never be modified rows in ASSEMBLYREF? */ int old_rows = table_info_get_rows (&image_base->tables [MONO_TABLE_ASSEMBLYREF]); for (GList *l = base_info->delta_info; l; l = l->next) { MonoImage *delta_child = ((DeltaInfo*)l->data)->delta_image; old_rows += table_info_get_rows (&delta_child->tables [MONO_TABLE_ASSEMBLYREF]); } int new_rows = table_info_get_rows (&image_dmeta->tables [MONO_TABLE_ASSEMBLYREF]); old_rows -= new_rows; g_assert (new_rows > 0); g_assert (old_rows > 0); /* TODO: this can end bad with code around assembly.c:mono_assembly_load_reference */ mono_image_lock (image_base); MonoAssembly **old_array = image_base->references; g_assert (image_base->nreferences == old_rows); image_base->references = g_new0 (MonoAssembly *, old_rows + new_rows + 1); memcpy (image_base->references, old_array, sizeof (gpointer) * (old_rows + 1)); image_base->nreferences = old_rows + new_rows; mono_image_unlock (image_base); #if 0 dump_assembly_ref_names (image_base); #endif g_free (old_array); break; } case MONO_TABLE_METHOD: { #ifdef ALLOW_METHOD_ADD /* if adding a param, handle it with the next record */ if (func_code == ENC_FUNC_ADD_PARAM) break; if (is_addition) { if (!add_member_klass) g_error ("EnC: new method added but I don't know the class, should be caught by pass1"); g_assert (add_member_klass); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Adding new method 0x%08x to class %s.%s", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); MonoDebugInformationEnc *method_debug_information = hot_reload_get_method_debug_information (delta_info->ppdb_file, token_index); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Debug info for method 0x%08x has ppdb idx 0x%08x", log_token, method_debug_information ? method_debug_information->idx : 0); add_method_to_baseline (base_info, delta_info, add_member_klass, log_token, method_debug_information); add_member_klass = NULL; } #endif if (!base_info->method_table_update) base_info->method_table_update = g_hash_table_new (g_direct_hash, g_direct_equal); if (!delta_info->method_table_update) delta_info->method_table_update = g_hash_table_new (g_direct_hash, g_direct_equal); if (!delta_info->method_ppdb_table_update) delta_info->method_ppdb_table_update = g_hash_table_new (g_direct_hash, g_direct_equal); int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); int rva = mono_metadata_decode_row_col (&image_dmeta->tables [MONO_TABLE_METHOD], mapped_token - 1, MONO_METHOD_RVA); if (rva < dil_length) { char *il_address = ((char *) dil_data) + rva; MonoDebugInformationEnc *method_debug_information = hot_reload_get_method_debug_information (delta_info->ppdb_file, token_index); set_update_method (image_base, base_info, generation, image_dmeta, delta_info, token_index, il_address, method_debug_information); } else { /* rva points probably into image_base IL stream. can this ever happen? */ g_print ("TODO: this case is still a bit contrived. token=0x%08x with rva=0x%04x\n", log_token, rva); } #if defined(ALLOW_METHOD_ADD) || defined(ALLOW_FIELD_ADD) add_member_klass = NULL; #endif break; } case MONO_TABLE_FIELD: { #ifdef ALLOW_FIELD_ADD g_assert (is_addition); g_assert (add_member_klass); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Adding new field 0x%08x to class %s.%s", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); uint32_t mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, log_token); uint32_t field_flags = mono_metadata_decode_row_col (&image_dmeta->tables [MONO_TABLE_FIELD], mapped_token - 1, MONO_FIELD_FLAGS); if ((field_flags & FIELD_ATTRIBUTE_STATIC) == 0) { /* TODO: implement instance (and literal?) fields */ mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_METADATA_UPDATE, "Adding non-static fields isn't implemented yet (token 0x%08x, class %s.%s)", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); mono_error_set_not_implemented (error, "Adding non-static fields isn't implemented yet (token 0x%08x, class %s.%s)", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); return FALSE; } add_field_to_baseline (base_info, delta_info, add_member_klass, log_token); /* This actually does more than mono_class_setup_basic_field_info and * resolves MonoClassField:type and sets MonoClassField:offset to -1 to make * it easier to spot that the field is special. */ metadata_update_field_setup_basic_info_and_resolve (image_base, base_info, generation, delta_info, add_member_klass, log_token, error); if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_METADATA_UPDATE, "Could not setup field (token 0x%08x) due to: %s", log_token, mono_error_get_message (error)); return FALSE; } add_member_klass = NULL; #else g_assert_not_reached (); #endif break; } case MONO_TABLE_TYPEDEF: { #ifdef ALLOW_CLASS_ADD if (is_addition) { /* Adding a new class. ok */ switch (func_code) { case ENC_FUNC_DEFAULT: /* ok, added a new class */ /* TODO: do things here */ break; case ENC_FUNC_ADD_METHOD: case ENC_FUNC_ADD_FIELD: /* ok, adding a new field or method to a new class */ /* TODO: do we need to do anything special? Conceptually * this is the same as modifying an existing class - * especially since from the next generation's point of view * that's what adding a field/method will be. */ break; case ENC_FUNC_ADD_PROPERTY: case ENC_FUNC_ADD_EVENT: g_assert_not_reached (); /* FIXME: implement me */ default: g_assert_not_reached (); /* unknown func_code */ } break; } #endif /* modifying an existing class by adding a method or field, etc. */ g_assert (!is_addition); #if !defined(ALLOW_METHOD_ADD) && !defined(ALLOW_FIELD_ADD) g_assert_not_reached (); #else g_assert (func_code != ENC_FUNC_DEFAULT); #endif break; } case MONO_TABLE_PROPERTY: { /* allow updates to existing properties. */ /* FIXME: use DeltaInfo:prev_gen_rows instead of image_base */ g_assert (token_index <= table_info_get_rows (&image_base->tables [token_table])); /* assuming that property attributes and type haven't changed. */ break; } case MONO_TABLE_CUSTOMATTRIBUTE: { /* ok, pass1 checked for disallowed modifications */ break; } case MONO_TABLE_PARAM: { /* ok, pass1 checked for disallowed modifications */ /* ALLOW_METHOD_ADD: FIXME: here we would really like to update the method's paramlist column to point to the new params. */ /* if there were multiple added methods, this comes in as several method * additions, followed by the parameter additions. * * 10: 0x02000002 (TypeDef) 0x00000001 (AddMethod) * 11: 0x06000006 (MethodDef) 0 * 12: 0x02000002 (TypeDef) 0x00000001 (AddMethod) * 13: 0x06000007 (MethodDef) 0 * 14: 0x06000006 (MethodDef) 0x00000003 (AddParameter) * 15: 0x08000003 (Param) 0 * 16: 0x06000006 (MethodDef) 0x00000003 (AddParameter) * 17: 0x08000004 (Param) 0 * 18: 0x06000007 (MethodDef) 0x00000003 (AddParameter) * 19: 0x08000005 (Param) 0 * * So by the time we see the param additions, the methods are already in. * * FIXME: we need a lookaside table (like member_parent) for every place * that looks at MONO_METHOD_PARAMLIST */ break; } default: { g_assert (token_index > table_info_get_rows (&image_base->tables [token_table])); if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) g_print ("todo: do something about this table index: 0x%02x\n", token_table); } } } return TRUE; } static void dump_methodbody (MonoImage *image) { if (!mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) return; MonoTableInfo *t = &image->tables [MONO_TABLE_METHODBODY]; uint32_t rows = table_info_get_rows (t); for (uint32_t i = 0; i < rows; ++i) { uint32_t cols[MONO_METHODBODY_SIZE]; mono_metadata_decode_row (t, i, cols, MONO_METHODBODY_SIZE); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, " row[%02d] = doc: 0x%08x seq: 0x%08x", i + 1, cols [MONO_METHODBODY_DOCUMENT], cols [MONO_METHODBODY_SEQ_POINTS]); } } /** * * LOCKING: Takes the publish_lock */ void hot_reload_apply_changes (int origin, MonoImage *image_base, gconstpointer dmeta_bytes, uint32_t dmeta_length, gconstpointer dil_bytes_orig, uint32_t dil_length, gconstpointer dpdb_bytes_orig, uint32_t dpdb_length, MonoError *error) { if (!assembly_update_supported (image_base->assembly)) { mono_error_set_invalid_operation (error, "The assembly can not be edited or changed."); return; } static int first_origin = -1; if (first_origin < 0) { first_origin = origin; } if (first_origin != origin) { mono_error_set_not_supported (error, "Applying deltas through the debugger and System.Reflection.Metadata.MetadataUpdater.ApplyUpdate simultaneously is not supported"); return; } const char *basename = image_base->filename; if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) { g_print ("LOADING basename=%s delta update.\ndelta image=%p & dil=%p\n", basename, dmeta_bytes, dil_bytes_orig); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "delta image size 0x%08x, delta IL size 0x%08x\n", dmeta_length, dil_length); #if 0 mono_dump_mem (dmeta_bytes, dmeta_length); mono_dump_mem (dil_bytes_orig, dil_length); #endif } uint32_t generation = hot_reload_update_prepare (); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image string size: 0x%08x", image_base->heap_strings.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image user string size: 0x%08x", image_base->heap_us.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image blob heap addr: %p", image_base->heap_blob.data); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base image blob heap size: 0x%08x", image_base->heap_blob.size); /* makes a copy of dmeta_bytes */ MonoImage *image_dmeta = image_open_dmeta_from_data (image_base, generation, dmeta_bytes, dmeta_length); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image string size: 0x%08x", image_dmeta->heap_strings.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image user string size: 0x%08x", image_dmeta->heap_us.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image blob heap addr: %p", image_dmeta->heap_blob.data); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta image blob heap size: 0x%08x", image_dmeta->heap_blob.size); g_assert (image_dmeta); /* makes a copy of dil_bytes_orig */ gpointer dil_bytes = open_dil_data (image_base, dil_bytes_orig, dil_length); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "delta IL bytes copied to addr=%p", dil_bytes); MonoPPDBFile *ppdb_file = NULL; if (dpdb_length > 0) { MonoImage *image_dpdb = image_open_dmeta_from_data (image_base, generation, dpdb_bytes_orig, dpdb_length); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image string size: 0x%08x", image_dpdb->heap_strings.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image user string size: 0x%08x", image_dpdb->heap_us.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image blob heap addr: %p", image_dpdb->heap_blob.data); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "pdb image blob heap size: 0x%08x", image_dpdb->heap_blob.size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "ppdb methodbody: "); dump_methodbody (image_dpdb); ppdb_file = mono_create_ppdb_file (image_dpdb, FALSE); g_assert (ppdb_file->image == image_dpdb); } BaselineInfo *base_info = baseline_info_lookup_or_add (image_base); DeltaInfo *prev_delta_info = NULL; DeltaInfo *delta_info = delta_info_init (image_dmeta, image_base, ppdb_file, base_info, generation, &prev_delta_info); if (image_dmeta->minimal_delta) { guint32 idx = mono_metadata_decode_row_col (&image_dmeta->tables [MONO_TABLE_MODULE], 0, MONO_MODULE_NAME); const char *module_name = NULL; module_name = mono_metadata_string_heap (image_base, idx); /* Set the module name now that we know the base String heap size */ g_assert (!image_dmeta->module_name); image_dmeta->module_name = module_name; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "applied dmeta name: '%s'\n", module_name); } MonoTableInfo *table_enclog = &image_dmeta->tables [MONO_TABLE_ENCLOG]; MonoTableInfo *table_encmap = &image_dmeta->tables [MONO_TABLE_ENCMAP]; if (!table_info_get_rows (table_enclog) && !table_info_get_rows (table_encmap)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "No enclog or encmap in delta image for base=%s, nothing to do", basename); hot_reload_update_cancel (generation); return; } /* Process EnCMap and compute number of added/modified rows from this * delta. This enables computing row indexes relative to the delta. * We use it in pass1 to bail out early if the EnCLog has unsupported * edits. */ if (!delta_info_compute_table_records (image_dmeta, image_base, base_info, delta_info)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Error on computing delta table info (base=%s)", basename); hot_reload_update_cancel (generation); return; } delta_info_initialize_mutants (image_base, base_info, prev_delta_info, delta_info); prepare_mutated_rows (table_enclog, image_base, image_dmeta, delta_info); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Populated mutated tables for delta image %p", image_dmeta); if (!apply_enclog_pass1 (image_base, image_dmeta, delta_info, dil_bytes, dil_length, error)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Error on sanity-checking delta image to base=%s, due to: %s", basename, mono_error_get_message (error)); hot_reload_update_cancel (generation); return; } /* if there are updates, start tracking the tables of the base image, if we weren't already. */ if (table_info_get_rows (table_enclog)) table_to_image_add (image_base); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "base guid: %s", image_base->guid); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "dmeta guid: %s", image_dmeta->guid); if (mono_trace_is_traced (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE)) dump_update_summary (image_base, image_dmeta); if (!apply_enclog_pass2 (image_base, base_info, generation, image_dmeta, delta_info, dil_bytes, dil_length, error)) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "Error applying delta image to base=%s, due to: %s", basename, mono_error_get_message (error)); hot_reload_update_cancel (generation); return; } mono_error_assert_ok (error); MonoAssemblyLoadContext *alc = mono_image_get_alc (image_base); hot_reload_update_publish (alc, generation); mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, ">>> EnC delta for base=%s (generation %d) applied", basename, generation); } static gpointer get_method_update_rva (MonoImage *image_base, BaselineInfo *base_info, uint32_t idx, gboolean is_pdb) { gpointer loc = NULL; uint32_t cur = hot_reload_get_thread_generation (); int generation = -1; /* Go through all the updates that the current thread can see and see * if they updated the method. Keep the latest visible update */ for (GList *ptr = base_info->delta_info; ptr != NULL; ptr = ptr->next) { DeltaInfo *delta_info = (DeltaInfo*)ptr->data; g_assert (delta_info); if (delta_info->generation > cur) break; GHashTable *table = NULL; if (is_pdb) table = delta_info->method_ppdb_table_update; else table = delta_info->method_table_update; if (table) { gpointer result = g_hash_table_lookup (table, GUINT_TO_POINTER (idx)); /* if it's not in the table of a later generation, the * later generation didn't modify the method */ if (result != NULL) { loc = result; generation = delta_info->generation; } } } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "method lookup idx=0x%08x returned gen=%d il=%p", idx, generation, loc); return loc; } gpointer hot_reload_get_updated_method_ppdb (MonoImage *base_image, uint32_t idx) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return NULL; gpointer loc = NULL; /* EnC case */ if (G_UNLIKELY (info->method_table_update)) { uint32_t gen = GPOINTER_TO_UINT (g_hash_table_lookup (info->method_table_update, GUINT_TO_POINTER (idx))); if (G_UNLIKELY (gen > 0)) { loc = get_method_update_rva (base_image, info, idx, TRUE); } /* Check the member_parent table as a way of checking if the method was added by a later generation. If so, still look for its PPDB info in our update tables */ uint32_t token = mono_metadata_make_token (MONO_TABLE_METHOD, mono_metadata_token_index (idx)); if (G_UNLIKELY (loc == 0 && info->member_parent && GPOINTER_TO_UINT (g_hash_table_lookup (info->member_parent, GUINT_TO_POINTER (token))) > 0)) { loc = get_method_update_rva (base_image, info, idx, TRUE); } } return loc; } gpointer hot_reload_get_updated_method_rva (MonoImage *base_image, uint32_t idx) { BaselineInfo *info = baseline_info_lookup (base_image); if (!info) return NULL; gpointer loc = NULL; /* EnC case */ if (G_UNLIKELY (info->method_table_update)) { uint32_t gen = GPOINTER_TO_UINT (g_hash_table_lookup (info->method_table_update, GUINT_TO_POINTER (idx))); if (G_UNLIKELY (gen > 0)) { loc = get_method_update_rva (base_image, info, idx, FALSE); } } return loc; } /* returns TRUE if token index is out of bounds */ gboolean hot_reload_table_bounds_check (MonoImage *base_image, int table_index, int token_index) { BaselineInfo *base_info = baseline_info_lookup (base_image); g_assert (base_info); GList *list = base_info->delta_info; MonoTableInfo *table; /* result row, 0-based */ int ridx; uint32_t exposed_gen = hot_reload_get_thread_generation (); do { if (!list) return TRUE; DeltaInfo *delta_info = (DeltaInfo*)list->data; g_assert (delta_info); if (delta_info->generation > exposed_gen) return TRUE; list = list->next; table = &delta_info->mutants [table_index]; ridx = token_index - 1; } while (ridx < 0 || ridx >= table_info_get_rows (table)); return FALSE; } gboolean hot_reload_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, uint32_t orig_index, MonoImage **image_out, uint32_t *index_out) { g_assert (image_out); g_assert (index_out); MonoStreamHeader *heap = get_heap (base_image); g_assert (orig_index >= heap->size); BaselineInfo *base_info = baseline_info_lookup (base_image); g_assert (base_info); g_assert (base_info->delta_info); *image_out = base_image; *index_out = orig_index; guint32 prev_size = heap->size; uint32_t current_gen = hot_reload_get_thread_generation (); GList *cur; for (cur = base_info->delta_info; cur; cur = cur->next) { DeltaInfo *delta_info = (DeltaInfo*)cur->data; g_assert (delta_info); MonoImage *delta_image = delta_info->delta_image; g_assert (delta_image); heap = get_heap (delta_image); *image_out = delta_image; if (delta_info->generation > current_gen) return FALSE; /* FIXME: for non-minimal deltas we should just look in the last published image. */ if (G_LIKELY (delta_image->minimal_delta)) *index_out -= prev_size; if (*index_out < heap->size) break; prev_size = heap->size; } return (cur != NULL); } static gboolean hot_reload_has_modified_rows (const MonoTableInfo *table) { MonoImage *base; int tbl_index; if (!table_info_find_in_base (table, &base, &tbl_index)) return FALSE; BaselineInfo *info = baseline_info_lookup (base); if (!info) return FALSE; return info->any_modified_rows[tbl_index]; } static int hot_reload_table_num_rows_slow (MonoImage *base, int table_index) { BaselineInfo *base_info = baseline_info_lookup (base); if (!base_info) return FALSE; uint32_t current_gen = hot_reload_get_thread_generation (); int rows = table_info_get_rows (&base->tables [table_index]); GList *cur; for (cur = base_info->delta_info; cur; cur = cur->next) { DeltaInfo *delta_info = (DeltaInfo*)cur->data; g_assert (delta_info); if (delta_info->generation > current_gen) break; rows = delta_info->count [table_index].prev_gen_rows + delta_info->count [table_index].inserted_rows; } return rows; } static void add_member_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t member_token) { /* Check they really passed a table token, not just a table row index */ g_assert (mono_metadata_token_table (member_token) != 0); if (!base_info->member_parent) { base_info->member_parent = g_hash_table_new (g_direct_hash, g_direct_equal); } MonoClassMetadataUpdateInfo *klass_info = mono_class_get_or_add_metadata_update_info (klass); GSList *members = klass_info->added_members; klass_info->added_members = g_slist_prepend_mem_manager (m_class_get_mem_manager (klass), members, GUINT_TO_POINTER (member_token)); g_hash_table_insert (base_info->member_parent, GUINT_TO_POINTER (member_token), GUINT_TO_POINTER (m_class_get_type_token (klass))); } static void add_method_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t method_token, MonoDebugInformationEnc* pdb_address) { add_member_to_baseline (base_info, delta_info, klass, method_token); if (pdb_address) set_delta_method_debug_info (delta_info, method_token, pdb_address); } static GSList* hot_reload_get_added_members (MonoClass *klass) { /* FIXME: locking for the GArray? */ MonoImage *image = m_class_get_image (klass); if (!image->has_updates) return NULL; MonoClassMetadataUpdateInfo *klass_info = mono_class_get_metadata_update_info (klass); if (!klass_info) return NULL; return klass_info->added_members; } static uint32_t hot_reload_member_parent (MonoImage *base_image, uint32_t member_token) { /* make sure they passed a token, not just a table row index */ g_assert (mono_metadata_token_table (member_token) != 0); if (!base_image->has_updates) return 0; BaselineInfo *base_info = baseline_info_lookup (base_image); if (!base_info || base_info->member_parent == NULL) return 0; uint32_t res = GPOINTER_TO_UINT (g_hash_table_lookup (base_info->member_parent, GUINT_TO_POINTER (member_token))); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "member_parent lookup: 0x%08x returned 0x%08x\n", member_token, res); return res; } static uint32_t hot_reload_method_parent (MonoImage *base_image, uint32_t method_token) { /* the callers might pass just an index without a table */ uint32_t lookup_token = mono_metadata_make_token (MONO_TABLE_METHOD, mono_metadata_token_index (method_token)); return hot_reload_member_parent (base_image, lookup_token); } static void add_field_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t field_token) { add_member_to_baseline (base_info, delta_info, klass, field_token); } static uint32_t hot_reload_field_parent (MonoImage *base_image, uint32_t field_token) { /* the callers might pass just an index without a table */ uint32_t lookup_token = mono_metadata_make_token (MONO_TABLE_FIELD, mono_metadata_token_index (field_token)); return hot_reload_member_parent (base_image, lookup_token); } /* HACK - keep in sync with locator_t in metadata/metadata.c */ typedef struct { int idx; /* The index that we are trying to locate */ int col_idx; /* The index in the row where idx may be stored */ MonoTableInfo *t; /* pointer to the table */ guint32 result; } upd_locator_t; void* hot_reload_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer) { BaselineInfo *base_info = baseline_info_lookup (base_image); g_assert (base_info); g_assert (base_image->tables < base_table && base_table < &base_image->tables [MONO_TABLE_LAST]); int tbl_index; { size_t s = ALIGN_TO (sizeof (MonoTableInfo), sizeof (gpointer)); tbl_index = ((intptr_t) base_table - (intptr_t) base_image->tables) / s; } DeltaInfo *delta_info = NULL; const MonoTableInfo *latest_mod_table = base_table; gboolean success = effective_table_mutant (base_image, base_info, tbl_index, &latest_mod_table, &delta_info); g_assert (success); uint32_t rows = table_info_get_rows (latest_mod_table); upd_locator_t *loc = (upd_locator_t*)key; g_assert (loc); loc->result = 0; /* HACK: this is so that the locator can compute the row index of the given row. but passing the mutant table to other metadata functions could backfire. */ loc->t = (MonoTableInfo*)latest_mod_table; for (uint32_t idx = 0; idx < rows; ++idx) { const char *row = latest_mod_table->base + idx * latest_mod_table->row_size; if (!comparer (loc, row)) return (void*)row; } return NULL; } static uint32_t hot_reload_get_field_idx (MonoClassField *field) { g_assert (m_field_is_from_update (field)); MonoClassMetadataUpdateField *field_info = (MonoClassMetadataUpdateField*)field; return mono_metadata_token_index (field_info->token); } static MonoClassField * hot_reload_get_field (MonoClass *klass, uint32_t fielddef_token) { MonoClassMetadataUpdateInfo *info = mono_class_get_or_add_metadata_update_info (klass); g_assert (mono_metadata_token_table (fielddef_token) == MONO_TABLE_FIELD); /* FIXME: this needs locking in the multi-threaded case. There could be an update happening that resizes the array. */ GPtrArray *added_fields = info->added_fields; uint32_t count = added_fields->len; for (uint32_t i = 0; i < count; ++i) { MonoClassMetadataUpdateField *field = (MonoClassMetadataUpdateField *)g_ptr_array_index (added_fields, i); if (field->token == fielddef_token) return &field->field; } return NULL; } static MonoClassMetadataUpdateField * metadata_update_field_setup_basic_info_and_resolve (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, DeltaInfo *delta_info, MonoClass *parent_klass, uint32_t fielddef_token, MonoError *error) { // TODO: hang a "pending field" struct off the parent_klass if !parent_klass->fields // In that case we can do things simpler, maybe by just creating the MonoClassField array as usual, and just relying on the normal layout algorithm to make space for the instance. MonoClassMetadataUpdateInfo *parent_info = mono_class_get_or_add_metadata_update_info (parent_klass); MonoClassMetadataUpdateField *field = mono_class_alloc0 (parent_klass, sizeof (MonoClassMetadataUpdateField)); m_field_set_parent (&field->field, parent_klass); m_field_set_meta_flags (&field->field, MONO_CLASS_FIELD_META_FLAG_FROM_UPDATE); /* It's a special field */ field->field.offset = -1; field->generation = generation; field->token = fielddef_token; uint32_t name_idx = mono_metadata_decode_table_row_col (image_base, MONO_TABLE_FIELD, mono_metadata_token_index (fielddef_token) - 1, MONO_FIELD_NAME); field->field.name = mono_metadata_string_heap (image_base, name_idx); mono_field_resolve_type (&field->field, error); if (!is_ok (error)) return NULL; if (!parent_info->added_fields) { parent_info->added_fields = g_ptr_array_new (); } g_ptr_array_add (parent_info->added_fields, field); return field; } static void ensure_class_runtime_info_inited (MonoClass *klass, MonoClassRuntimeMetadataUpdateInfo *runtime_info) { if (runtime_info->inited) return; mono_loader_lock (); if (runtime_info->inited) { mono_loader_unlock (); return; } mono_coop_mutex_init (&runtime_info->static_fields_lock); /* FIXME: is it ok to re-use MONO_ROOT_SOURCE_STATIC here? */ runtime_info->static_fields = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_STATIC, NULL, "Hot Reload Static Fields"); runtime_info->inited = TRUE; mono_loader_unlock (); } static void class_runtime_info_static_fields_lock (MonoClassRuntimeMetadataUpdateInfo *runtime_info) { mono_coop_mutex_lock (&runtime_info->static_fields_lock); } static void class_runtime_info_static_fields_unlock (MonoClassRuntimeMetadataUpdateInfo *runtime_info) { mono_coop_mutex_unlock (&runtime_info->static_fields_lock); } static GENERATE_GET_CLASS_WITH_CACHE_DECL (hot_reload_field_store); static GENERATE_GET_CLASS_WITH_CACHE(hot_reload_field_store, "Mono.HotReload", "FieldStore"); static MonoObject* create_static_field_storage (MonoType *t, MonoError *error) { MonoClass *klass; if (!mono_type_is_reference (t)) klass = mono_class_from_mono_type_internal (t); else klass = mono_class_get_hot_reload_field_store_class (); return mono_object_new_pinned (klass, error); } static gpointer hot_reload_get_static_field_addr (MonoClassField *field) { g_assert (m_field_is_from_update (field)); MonoClassMetadataUpdateField *f = (MonoClassMetadataUpdateField *)field; g_assert ((f->field.type->attrs & FIELD_ATTRIBUTE_STATIC) != 0); g_assert (!m_type_is_byref(f->field.type)); // byref fields only in ref structs, which aren't allowed in EnC updates MonoClass *parent = m_field_get_parent (&f->field); MonoClassMetadataUpdateInfo *parent_info = mono_class_get_or_add_metadata_update_info (parent); MonoClassRuntimeMetadataUpdateInfo *runtime_info = &parent_info->runtime; ensure_class_runtime_info_inited (parent, runtime_info); MonoObject *obj = NULL; class_runtime_info_static_fields_lock (runtime_info); obj = (MonoObject*) mono_g_hash_table_lookup (runtime_info->static_fields, GUINT_TO_POINTER (f->token)); class_runtime_info_static_fields_unlock (runtime_info); if (!obj) { ERROR_DECL (error); obj = create_static_field_storage (f->field.type, error); class_runtime_info_static_fields_lock (runtime_info); mono_error_assert_ok (error); MonoObject *obj2 = (MonoObject*) mono_g_hash_table_lookup (runtime_info->static_fields, GUINT_TO_POINTER (f->token)); if (!obj2) { // Noone else created it, use ours mono_g_hash_table_insert_internal (runtime_info->static_fields, GUINT_TO_POINTER (f->token), obj); } else { /* beaten by another thread, silently drop our storage object and use theirs */ obj = obj2; } class_runtime_info_static_fields_unlock (runtime_info); } g_assert (obj); gpointer addr = NULL; if (!mono_type_is_reference (f->field.type)) { // object is just the boxed value addr = mono_object_unbox_internal (obj); } else { // object is a Mono.HotReload.FieldStore, and the static field value is obj._loc MonoHotReloadFieldStoreObject *store = (MonoHotReloadFieldStoreObject *)obj; addr = (gpointer)&store->_loc; } g_assert (addr); return addr; } static MonoMethod * hot_reload_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error) { GSList *members = hot_reload_get_added_members (klass); if (!members) return NULL; MonoImage *image = m_class_get_image (klass); MonoMethod *res = NULL; for (GSList *ptr = members; ptr; ptr = ptr->next) { uint32_t token = GPOINTER_TO_UINT(ptr->data); if (mono_metadata_token_table (token) != MONO_TABLE_METHOD) continue; uint32_t idx = mono_metadata_token_index (token); uint32_t cols [MONO_METHOD_SIZE]; mono_metadata_decode_table_row (image, MONO_TABLE_METHOD, idx - 1, cols, MONO_METHOD_SIZE); if (!strcmp (mono_metadata_string_heap (image, cols [MONO_METHOD_NAME]), name)) { ERROR_DECL (local_error); MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, local_error); if (!method) { mono_error_cleanup (local_error); continue; } if (param_count == -1) { res = method; break; } MonoMethodSignature *sig = mono_method_signature_checked (method, local_error); if (!sig) { mono_error_cleanup (error); continue; } if ((method->flags & flags) == flags && sig->param_count == param_count) { res = method; break; } } } return res; }
1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/mono/mono/metadata/metadata.c
/** * \file * Routines for accessing the metadata * * Authors: * Miguel de Icaza ([email protected]) * Paolo Molaro ([email protected]) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glib.h> #include <mono/metadata/metadata.h> #include "tabledefs.h" #include "mono-endian.h" #include "cil-coff.h" #include <mono/metadata/tokentype.h> #include "class-internals.h" #include "metadata-internals.h" #include "reflection-internals.h" #include "metadata-update.h" #include <mono/metadata/class.h> #include "marshal.h" #include <mono/metadata/debug-helpers.h> #include "abi-details.h" #include "cominterop.h" #include "components.h" #include <mono/metadata/exception-internals.h> #include <mono/utils/mono-error-internals.h> #include <mono/utils/mono-memory-model.h> #include <mono/utils/mono-digest.h> #include <mono/utils/bsearch.h> #include <mono/utils/atomic.h> #include <mono/utils/unlocked.h> #include <mono/utils/mono-counters.h> /* Auxiliary structure used for caching inflated signatures */ typedef struct { MonoMethodSignature *sig; MonoGenericContext context; } MonoInflatedMethodSignature; static gboolean do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container, gboolean transient, const char *ptr, const char **rptr, MonoError *error); static gboolean do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only); static gboolean mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only); static gboolean mono_metadata_fnptr_equal (MonoMethodSignature *s1, MonoMethodSignature *s2, gboolean signature_only); static gboolean _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only); static void free_generic_inst (MonoGenericInst *ginst); static void free_generic_class (MonoGenericClass *ginst); static void free_inflated_signature (MonoInflatedMethodSignature *sig); static void free_aggregate_modifiers (MonoAggregateModContainer *amods); static void mono_metadata_field_info_full (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec, gboolean alloc_from_image); static MonoType* mono_signature_get_params_internal (MonoMethodSignature *sig, gpointer *iter); /* * This enumeration is used to describe the data types in the metadata * tables */ enum { MONO_MT_END, /* Sized elements */ MONO_MT_UINT32, MONO_MT_UINT16, MONO_MT_UINT8, /* Index into Blob heap */ MONO_MT_BLOB_IDX, /* Index into String heap */ MONO_MT_STRING_IDX, /* GUID index */ MONO_MT_GUID_IDX, /* Pointer into a table */ MONO_MT_TABLE_IDX, /* HasConstant:Parent pointer (Param, Field or Property) */ MONO_MT_CONST_IDX, /* HasCustomAttribute index. Indexes any table except CustomAttribute */ MONO_MT_HASCAT_IDX, /* CustomAttributeType encoded index */ MONO_MT_CAT_IDX, /* HasDeclSecurity index: TypeDef Method or Assembly */ MONO_MT_HASDEC_IDX, /* Implementation coded index: File, Export AssemblyRef */ MONO_MT_IMPL_IDX, /* HasFieldMarshal coded index: Field or Param table */ MONO_MT_HFM_IDX, /* MemberForwardedIndex: Field or Method */ MONO_MT_MF_IDX, /* TypeDefOrRef coded index: typedef, typeref, typespec */ MONO_MT_TDOR_IDX, /* MemberRefParent coded index: typeref, moduleref, method, memberref, typesepc, typedef */ MONO_MT_MRP_IDX, /* MethodDefOrRef coded index: Method or Member Ref table */ MONO_MT_MDOR_IDX, /* HasSemantic coded index: Event or Property */ MONO_MT_HS_IDX, /* ResolutionScope coded index: Module, ModuleRef, AssemblytRef, TypeRef */ MONO_MT_RS_IDX, /* CustomDebugInformation parent encoded index */ MONO_MT_HASCUSTDEBUG_IDX }; const static unsigned char TableSchemas [] = { #define ASSEMBLY_SCHEMA_OFFSET 0 MONO_MT_UINT32, /* "HashId" }, */ MONO_MT_UINT16, /* "Major" }, */ MONO_MT_UINT16, /* "Minor" }, */ MONO_MT_UINT16, /* "BuildNumber" }, */ MONO_MT_UINT16, /* "RevisionNumber" }, */ MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_BLOB_IDX, /* "PublicKey" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Culture" }, */ MONO_MT_END, #define ASSEMBLYOS_SCHEMA_OFFSET ASSEMBLY_SCHEMA_OFFSET + 10 MONO_MT_UINT32, /* "OSPlatformID" }, */ MONO_MT_UINT32, /* "OSMajor" }, */ MONO_MT_UINT32, /* "OSMinor" }, */ MONO_MT_END, #define ASSEMBLYPROC_SCHEMA_OFFSET ASSEMBLYOS_SCHEMA_OFFSET + 4 MONO_MT_UINT32, /* "Processor" }, */ MONO_MT_END, #define ASSEMBLYREF_SCHEMA_OFFSET ASSEMBLYPROC_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Major" }, */ MONO_MT_UINT16, /* "Minor" }, */ MONO_MT_UINT16, /* "Build" }, */ MONO_MT_UINT16, /* "Revision" }, */ MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_BLOB_IDX, /* "PublicKeyOrToken" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Culture" }, */ MONO_MT_BLOB_IDX, /* "HashValue" }, */ MONO_MT_END, #define ASSEMBLYREFOS_SCHEMA_OFFSET ASSEMBLYREF_SCHEMA_OFFSET + 10 MONO_MT_UINT32, /* "OSPlatformID" }, */ MONO_MT_UINT32, /* "OSMajorVersion" }, */ MONO_MT_UINT32, /* "OSMinorVersion" }, */ MONO_MT_TABLE_IDX, /* "AssemblyRef:AssemblyRef" }, */ MONO_MT_END, #define ASSEMBLYREFPROC_SCHEMA_OFFSET ASSEMBLYREFOS_SCHEMA_OFFSET + 5 MONO_MT_UINT32, /* "Processor" }, */ MONO_MT_TABLE_IDX, /* "AssemblyRef:AssemblyRef" }, */ MONO_MT_END, #define CLASS_LAYOUT_SCHEMA_OFFSET ASSEMBLYREFPROC_SCHEMA_OFFSET + 3 MONO_MT_UINT16, /* "PackingSize" }, */ MONO_MT_UINT32, /* "ClassSize" }, */ MONO_MT_TABLE_IDX, /* "Parent:TypeDef" }, */ MONO_MT_END, #define CONSTANT_SCHEMA_OFFSET CLASS_LAYOUT_SCHEMA_OFFSET + 4 MONO_MT_UINT8, /* "Type" }, */ MONO_MT_UINT8, /* "PaddingZero" }, */ MONO_MT_CONST_IDX, /* "Parent" }, */ MONO_MT_BLOB_IDX, /* "Value" }, */ MONO_MT_END, #define CUSTOM_ATTR_SCHEMA_OFFSET CONSTANT_SCHEMA_OFFSET + 5 MONO_MT_HASCAT_IDX, /* "Parent" }, */ MONO_MT_CAT_IDX, /* "Type" }, */ MONO_MT_BLOB_IDX, /* "Value" }, */ MONO_MT_END, #define DECL_SEC_SCHEMA_OFFSET CUSTOM_ATTR_SCHEMA_OFFSET + 4 MONO_MT_UINT16, /* "Action" }, */ MONO_MT_HASDEC_IDX, /* "Parent" }, */ MONO_MT_BLOB_IDX, /* "PermissionSet" }, */ MONO_MT_END, #define EVENTMAP_SCHEMA_OFFSET DECL_SEC_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Parent:TypeDef" }, */ MONO_MT_TABLE_IDX, /* "EventList:Event" }, */ MONO_MT_END, #define EVENT_SCHEMA_OFFSET EVENTMAP_SCHEMA_OFFSET + 3 MONO_MT_UINT16, /* "EventFlags#EventAttribute" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_TDOR_IDX, /* "EventType" }, TypeDef or TypeRef or TypeSpec */ MONO_MT_END, #define EVENT_POINTER_SCHEMA_OFFSET EVENT_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Event" }, */ MONO_MT_END, #define EXPORTED_TYPE_SCHEMA_OFFSET EVENT_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_TABLE_IDX, /* "TypeDefId" }, */ MONO_MT_STRING_IDX, /* "TypeName" }, */ MONO_MT_STRING_IDX, /* "TypeNameSpace" }, */ MONO_MT_IMPL_IDX, /* "Implementation" }, */ MONO_MT_END, #define FIELD_SCHEMA_OFFSET EXPORTED_TYPE_SCHEMA_OFFSET + 6 MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define FIELD_LAYOUT_SCHEMA_OFFSET FIELD_SCHEMA_OFFSET + 4 MONO_MT_UINT32, /* "Offset" }, */ MONO_MT_TABLE_IDX, /* "Field:Field" }, */ MONO_MT_END, #define FIELD_MARSHAL_SCHEMA_OFFSET FIELD_LAYOUT_SCHEMA_OFFSET + 3 MONO_MT_HFM_IDX, /* "Parent" }, */ MONO_MT_BLOB_IDX, /* "NativeType" }, */ MONO_MT_END, #define FIELD_RVA_SCHEMA_OFFSET FIELD_MARSHAL_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "RVA" }, */ MONO_MT_TABLE_IDX, /* "Field:Field" }, */ MONO_MT_END, #define ENCLOG_SCHEMA_OFFSET FIELD_RVA_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "Token" }, */ MONO_MT_UINT32, /* "FuncCode" }, */ MONO_MT_END, #define ENCMAP_SCHEMA_OFFSET ENCLOG_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "Token" }, */ MONO_MT_END, #define FIELD_POINTER_SCHEMA_OFFSET ENCMAP_SCHEMA_OFFSET + 2 MONO_MT_TABLE_IDX, /* "Field" }, */ MONO_MT_END, #define FILE_SCHEMA_OFFSET FIELD_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Value" }, */ MONO_MT_END, #define IMPLMAP_SCHEMA_OFFSET FILE_SCHEMA_OFFSET + 4 MONO_MT_UINT16, /* "MappingFlag" }, */ MONO_MT_MF_IDX, /* "MemberForwarded" }, */ MONO_MT_STRING_IDX, /* "ImportName" }, */ MONO_MT_TABLE_IDX, /* "ImportScope:ModuleRef" }, */ MONO_MT_END, #define IFACEMAP_SCHEMA_OFFSET IMPLMAP_SCHEMA_OFFSET + 5 MONO_MT_TABLE_IDX, /* "Class:TypeDef" }, */ MONO_MT_TDOR_IDX, /* "Interface=TypeDefOrRef" }, */ MONO_MT_END, #define MANIFEST_SCHEMA_OFFSET IFACEMAP_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "Offset" }, */ MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_IMPL_IDX, /* "Implementation" }, */ MONO_MT_END, #define MEMBERREF_SCHEMA_OFFSET MANIFEST_SCHEMA_OFFSET + 5 MONO_MT_MRP_IDX, /* "Class" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define METHOD_SCHEMA_OFFSET MEMBERREF_SCHEMA_OFFSET + 4 MONO_MT_UINT32, /* "RVA" }, */ MONO_MT_UINT16, /* "ImplFlags#MethodImplAttributes" }, */ MONO_MT_UINT16, /* "Flags#MethodAttribute" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_TABLE_IDX, /* "ParamList:Param" }, */ MONO_MT_END, #define METHOD_IMPL_SCHEMA_OFFSET METHOD_SCHEMA_OFFSET + 7 MONO_MT_TABLE_IDX, /* "Class:TypeDef" }, */ MONO_MT_MDOR_IDX, /* "MethodBody" }, */ MONO_MT_MDOR_IDX, /* "MethodDeclaration" }, */ MONO_MT_END, #define METHOD_SEMA_SCHEMA_OFFSET METHOD_IMPL_SCHEMA_OFFSET + 4 MONO_MT_UINT16, /* "MethodSemantic" }, */ MONO_MT_TABLE_IDX, /* "Method:Method" }, */ MONO_MT_HS_IDX, /* "Association" }, */ MONO_MT_END, #define METHOD_POINTER_SCHEMA_OFFSET METHOD_SEMA_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Method" }, */ MONO_MT_END, #define MODULE_SCHEMA_OFFSET METHOD_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Generation" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_GUID_IDX, /* "MVID" }, */ MONO_MT_GUID_IDX, /* "EncID" }, */ MONO_MT_GUID_IDX, /* "EncBaseID" }, */ MONO_MT_END, #define MODULEREF_SCHEMA_OFFSET MODULE_SCHEMA_OFFSET + 6 MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_END, #define NESTED_CLASS_SCHEMA_OFFSET MODULEREF_SCHEMA_OFFSET + 2 MONO_MT_TABLE_IDX, /* "NestedClass:TypeDef" }, */ MONO_MT_TABLE_IDX, /* "EnclosingClass:TypeDef" }, */ MONO_MT_END, #define PARAM_SCHEMA_OFFSET NESTED_CLASS_SCHEMA_OFFSET + 3 MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_UINT16, /* "Sequence" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_END, #define PARAM_POINTER_SCHEMA_OFFSET PARAM_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Param" }, */ MONO_MT_END, #define PROPERTY_SCHEMA_OFFSET PARAM_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Type" }, */ MONO_MT_END, #define PROPERTY_POINTER_SCHEMA_OFFSET PROPERTY_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Property" }, */ MONO_MT_END, #define PROPERTY_MAP_SCHEMA_OFFSET PROPERTY_POINTER_SCHEMA_OFFSET + 2 MONO_MT_TABLE_IDX, /* "Parent:TypeDef" }, */ MONO_MT_TABLE_IDX, /* "PropertyList:Property" }, */ MONO_MT_END, #define STDALON_SIG_SCHEMA_OFFSET PROPERTY_MAP_SCHEMA_OFFSET + 3 MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define TYPEDEF_SCHEMA_OFFSET STDALON_SIG_SCHEMA_OFFSET + 2 MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Namespace" }, */ MONO_MT_TDOR_IDX, /* "Extends" }, */ MONO_MT_TABLE_IDX, /* "FieldList:Field" }, */ MONO_MT_TABLE_IDX, /* "MethodList:Method" }, */ MONO_MT_END, #define TYPEREF_SCHEMA_OFFSET TYPEDEF_SCHEMA_OFFSET + 7 MONO_MT_RS_IDX, /* "ResolutionScope=ResolutionScope" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Namespace" }, */ MONO_MT_END, #define TYPESPEC_SCHEMA_OFFSET TYPEREF_SCHEMA_OFFSET + 4 MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define GENPARAM_SCHEMA_OFFSET TYPESPEC_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Number" }, */ MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_TABLE_IDX, /* "Owner" }, TypeDef or MethodDef */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_END, #define METHOD_SPEC_SCHEMA_OFFSET GENPARAM_SCHEMA_OFFSET + 5 MONO_MT_MDOR_IDX, /* "Method" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define GEN_CONSTRAINT_SCHEMA_OFFSET METHOD_SPEC_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* "GenericParam" }, */ MONO_MT_TDOR_IDX, /* "Constraint" }, */ MONO_MT_END, #define DOCUMENT_SCHEMA_OFFSET GEN_CONSTRAINT_SCHEMA_OFFSET + 3 MONO_MT_BLOB_IDX, /* Name */ MONO_MT_GUID_IDX, /* HashAlgorithm */ MONO_MT_BLOB_IDX, /* Hash */ MONO_MT_GUID_IDX, /* Language */ MONO_MT_END, #define METHODBODY_SCHEMA_OFFSET DOCUMENT_SCHEMA_OFFSET + 5 MONO_MT_TABLE_IDX, /* Document */ MONO_MT_BLOB_IDX, /* SequencePoints */ MONO_MT_END, #define LOCALSCOPE_SCHEMA_OFFSET METHODBODY_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* Method */ MONO_MT_TABLE_IDX, /* ImportScope */ MONO_MT_TABLE_IDX, /* VariableList */ MONO_MT_TABLE_IDX, /* ConstantList */ MONO_MT_UINT32, /* StartOffset */ MONO_MT_UINT32, /* Length */ MONO_MT_END, #define LOCALVARIABLE_SCHEMA_OFFSET LOCALSCOPE_SCHEMA_OFFSET + 7 MONO_MT_UINT16, /* Attributes */ MONO_MT_UINT16, /* Index */ MONO_MT_STRING_IDX, /* Name */ MONO_MT_END, #define LOCALCONSTANT_SCHEMA_OFFSET LOCALVARIABLE_SCHEMA_OFFSET + 4 MONO_MT_STRING_IDX, /* Name (String heap index) */ MONO_MT_BLOB_IDX, /* Signature (Blob heap index, LocalConstantSig blob) */ MONO_MT_END, #define IMPORTSCOPE_SCHEMA_OFFSET LOCALCONSTANT_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* Parent (ImportScope row id or nil) */ MONO_MT_BLOB_IDX, /* Imports (Blob index, encoding: Imports blob) */ MONO_MT_END, #define ASYNCMETHOD_SCHEMA_OFFSET IMPORTSCOPE_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* MoveNextMethod (MethodDef row id) */ MONO_MT_TABLE_IDX, /* KickoffMethod (MethodDef row id) */ MONO_MT_END, #define CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET ASYNCMETHOD_SCHEMA_OFFSET + 3 MONO_MT_HASCUSTDEBUG_IDX, /* Parent (HasCustomDebugInformation coded index) */ MONO_MT_GUID_IDX, /* Kind (Guid heap index) */ MONO_MT_BLOB_IDX, /* Value (Blob heap index) */ MONO_MT_END, #define NULL_SCHEMA_OFFSET CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET + 4 MONO_MT_END }; /* Must be the same order as MONO_TABLE_* */ const static unsigned char table_description [] = { MODULE_SCHEMA_OFFSET, TYPEREF_SCHEMA_OFFSET, TYPEDEF_SCHEMA_OFFSET, FIELD_POINTER_SCHEMA_OFFSET, FIELD_SCHEMA_OFFSET, METHOD_POINTER_SCHEMA_OFFSET, METHOD_SCHEMA_OFFSET, PARAM_POINTER_SCHEMA_OFFSET, PARAM_SCHEMA_OFFSET, IFACEMAP_SCHEMA_OFFSET, MEMBERREF_SCHEMA_OFFSET, /* 0xa */ CONSTANT_SCHEMA_OFFSET, CUSTOM_ATTR_SCHEMA_OFFSET, FIELD_MARSHAL_SCHEMA_OFFSET, DECL_SEC_SCHEMA_OFFSET, CLASS_LAYOUT_SCHEMA_OFFSET, FIELD_LAYOUT_SCHEMA_OFFSET, /* 0x10 */ STDALON_SIG_SCHEMA_OFFSET, EVENTMAP_SCHEMA_OFFSET, EVENT_POINTER_SCHEMA_OFFSET, EVENT_SCHEMA_OFFSET, PROPERTY_MAP_SCHEMA_OFFSET, PROPERTY_POINTER_SCHEMA_OFFSET, PROPERTY_SCHEMA_OFFSET, METHOD_SEMA_SCHEMA_OFFSET, METHOD_IMPL_SCHEMA_OFFSET, MODULEREF_SCHEMA_OFFSET, /* 0x1a */ TYPESPEC_SCHEMA_OFFSET, IMPLMAP_SCHEMA_OFFSET, FIELD_RVA_SCHEMA_OFFSET, ENCLOG_SCHEMA_OFFSET, ENCMAP_SCHEMA_OFFSET, ASSEMBLY_SCHEMA_OFFSET, /* 0x20 */ ASSEMBLYPROC_SCHEMA_OFFSET, ASSEMBLYOS_SCHEMA_OFFSET, ASSEMBLYREF_SCHEMA_OFFSET, ASSEMBLYREFPROC_SCHEMA_OFFSET, ASSEMBLYREFOS_SCHEMA_OFFSET, FILE_SCHEMA_OFFSET, EXPORTED_TYPE_SCHEMA_OFFSET, MANIFEST_SCHEMA_OFFSET, NESTED_CLASS_SCHEMA_OFFSET, GENPARAM_SCHEMA_OFFSET, /* 0x2a */ METHOD_SPEC_SCHEMA_OFFSET, GEN_CONSTRAINT_SCHEMA_OFFSET, NULL_SCHEMA_OFFSET, NULL_SCHEMA_OFFSET, NULL_SCHEMA_OFFSET, DOCUMENT_SCHEMA_OFFSET, /* 0x30 */ METHODBODY_SCHEMA_OFFSET, LOCALSCOPE_SCHEMA_OFFSET, LOCALVARIABLE_SCHEMA_OFFSET, LOCALCONSTANT_SCHEMA_OFFSET, IMPORTSCOPE_SCHEMA_OFFSET, ASYNCMETHOD_SCHEMA_OFFSET, CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET }; // This, instead of an array of pointers, to optimize away a pointer and a relocation per string. #define MSGSTRFIELD(line) MSGSTRFIELD1(line) #define MSGSTRFIELD1(line) str##line static const struct msgstr_t { #define TABLEDEF(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #include "mono/cil/tables.def" #undef TABLEDEF } tablestr = { #define TABLEDEF(a,b) b, #include "mono/cil/tables.def" #undef TABLEDEF }; static const gint16 tableidx [] = { #define TABLEDEF(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "mono/cil/tables.def" #undef TABLEDEF }; /* On legacy, if TRUE (but also see DISABLE_DESKTOP_LOADER #define), Mono will check * that the public key token, culture and version of a candidate assembly matches * the requested strong name. On netcore, it will check the culture and version. * If FALSE, as long as the name matches, the candidate will be allowed. */ static gboolean check_assembly_names_strictly = FALSE; // Amount initially reserved in each imageset's mempool. // FIXME: This number is arbitrary, a more practical number should be found #define INITIAL_IMAGE_SET_SIZE 1024 /** * mono_meta_table_name: * \param table table index * * Returns the name of the given ECMA metadata logical format table * as described in ECMA 335, Partition II, Section 22. * * \returns the name for the \p table index */ const char * mono_meta_table_name (int table) { if ((table < 0) || (table > MONO_TABLE_LAST)) return ""; return (const char*)&tablestr + tableidx [table]; } /* The guy who wrote the spec for this should not be allowed near a * computer again. If e is a coded token(see clause 23.1.7) that points into table ti out of n possible tables t0, .. tn-1, then it is stored as e << (log n) & tag{ t0, .. tn-1}[ ti] using 2 bytes if the maximum number of rows of tables t0, ..tn-1, is less than 2^16 - (log n), and using 4 bytes otherwise. The family of finite maps tag{ t0, ..tn-1} is defined below. Note that to decode a physical row, you need the inverse of this mapping. */ static int rtsize (MonoImage *meta, int sz, int bits) { if (G_UNLIKELY (meta->minimal_delta)) return 4; if (sz < (1 << bits)) return 2; else return 4; } static int idx_size (MonoImage *meta, int idx) { if (G_UNLIKELY (meta->minimal_delta)) return 4; if (meta->referenced_tables && (meta->referenced_tables & ((guint64)1 << idx))) return meta->referenced_table_rows [idx] < 65536 ? 2 : 4; else return table_info_get_rows (&meta->tables [idx]) < 65536 ? 2 : 4; } static int get_nrows (MonoImage *meta, int idx) { if (meta->referenced_tables && (meta->referenced_tables & ((guint64)1 << idx))) return meta->referenced_table_rows [idx]; else return table_info_get_rows (&meta->tables [idx]); } /* Reference: Partition II - 23.2.6 */ /** * mono_metadata_compute_size: * \param meta metadata context * \param tableindex metadata table number * \param result_bitfield pointer to \c guint32 where to store additional info * * \c mono_metadata_compute_size computes the length in bytes of a single * row in a metadata table. The size of each column is encoded in the * \p result_bitfield return value along with the number of columns in the table. * the resulting bitfield should be handed to the \c mono_metadata_table_size * and \c mono_metadata_table_count macros. * This is a Mono runtime internal only function. */ int mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bitfield) { guint32 bitfield = 0; int size = 0, field_size = 0; int i, n, code; int shift = 0; const unsigned char *description = TableSchemas + table_description [tableindex]; for (i = 0; (code = description [i]) != MONO_MT_END; i++){ switch (code){ case MONO_MT_UINT32: field_size = 4; break; case MONO_MT_UINT16: field_size = 2; break; case MONO_MT_UINT8: field_size = 1; break; case MONO_MT_BLOB_IDX: field_size = meta->idx_blob_wide ? 4 : 2; break; case MONO_MT_STRING_IDX: field_size = meta->idx_string_wide ? 4 : 2; break; case MONO_MT_GUID_IDX: field_size = meta->idx_guid_wide ? 4 : 2; break; case MONO_MT_TABLE_IDX: /* Uhm, a table index can point to other tables besides the current one * so, it's not correct to use the rowcount of the current table to * get the size for this column - lupus */ switch (tableindex) { case MONO_TABLE_ASSEMBLYREFOS: g_assert (i == 3); field_size = idx_size (meta, MONO_TABLE_ASSEMBLYREF); break; case MONO_TABLE_ASSEMBLYREFPROCESSOR: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_ASSEMBLYREF); break; case MONO_TABLE_CLASSLAYOUT: g_assert (i == 2); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_EVENTMAP: g_assert (i == 0 || i == 1); field_size = i ? idx_size (meta, MONO_TABLE_EVENT): idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_EVENT_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_EVENT); break; case MONO_TABLE_EXPORTEDTYPE: g_assert (i == 1); /* the index is in another metadata file, so it must be 4 */ field_size = 4; break; case MONO_TABLE_FIELDLAYOUT: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_FIELD); break; case MONO_TABLE_FIELDRVA: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_FIELD); break; case MONO_TABLE_FIELD_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_FIELD); break; case MONO_TABLE_IMPLMAP: g_assert (i == 3); field_size = idx_size (meta, MONO_TABLE_MODULEREF); break; case MONO_TABLE_INTERFACEIMPL: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_METHOD: g_assert (i == 5); field_size = idx_size (meta, MONO_TABLE_PARAM); break; case MONO_TABLE_METHODIMPL: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_METHODSEMANTICS: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_METHOD); break; case MONO_TABLE_METHOD_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_METHOD); break; case MONO_TABLE_NESTEDCLASS: g_assert (i == 0 || i == 1); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_PARAM_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_PARAM); break; case MONO_TABLE_PROPERTYMAP: g_assert (i == 0 || i == 1); field_size = i ? idx_size (meta, MONO_TABLE_PROPERTY): idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_PROPERTY_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_PROPERTY); break; case MONO_TABLE_TYPEDEF: g_assert (i == 4 || i == 5); field_size = i == 4 ? idx_size (meta, MONO_TABLE_FIELD): idx_size (meta, MONO_TABLE_METHOD); break; case MONO_TABLE_GENERICPARAM: g_assert (i == 2); n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_TYPEDEF)); /*This is a coded token for 2 tables, so takes 1 bit */ field_size = rtsize (meta, n, 16 - MONO_TYPEORMETHOD_BITS); break; case MONO_TABLE_GENERICPARAMCONSTRAINT: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_GENERICPARAM); break; case MONO_TABLE_LOCALSCOPE: switch (i) { case 0: // FIXME: This table is in another file field_size = idx_size (meta, MONO_TABLE_METHOD); break; case 1: field_size = idx_size (meta, MONO_TABLE_IMPORTSCOPE); break; case 2: field_size = idx_size (meta, MONO_TABLE_LOCALVARIABLE); break; case 3: field_size = idx_size (meta, MONO_TABLE_LOCALCONSTANT); break; default: g_assert_not_reached (); break; } break; case MONO_TABLE_METHODBODY: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_DOCUMENT); break; case MONO_TABLE_IMPORTSCOPE: g_assert(i == 0); field_size = idx_size (meta, MONO_TABLE_IMPORTSCOPE); break; case MONO_TABLE_STATEMACHINEMETHOD: g_assert(i == 0 || i == 1); field_size = idx_size(meta, MONO_TABLE_METHOD); break; default: g_error ("Can't handle MONO_MT_TABLE_IDX for table %d element %d", tableindex, i); } break; /* * HasConstant: ParamDef, FieldDef, Property */ case MONO_MT_CONST_IDX: n = MAX (get_nrows (meta, MONO_TABLE_PARAM), get_nrows (meta, MONO_TABLE_FIELD)); n = MAX (n, get_nrows (meta, MONO_TABLE_PROPERTY)); /* 2 bits to encode tag */ field_size = rtsize (meta, n, 16-2); break; /* * HasCustomAttribute: points to any table but * itself. */ case MONO_MT_HASCAT_IDX: /* * We believe that since the signature and * permission are indexing the Blob heap, * we should consider the blob size first */ /* I'm not a believer - lupus if (meta->idx_blob_wide){ field_size = 4; break; }*/ n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_FIELD)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEDEF)); n = MAX (n, get_nrows (meta, MONO_TABLE_PARAM)); n = MAX (n, get_nrows (meta, MONO_TABLE_INTERFACEIMPL)); n = MAX (n, get_nrows (meta, MONO_TABLE_MEMBERREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_MODULE)); n = MAX (n, get_nrows (meta, MONO_TABLE_DECLSECURITY)); n = MAX (n, get_nrows (meta, MONO_TABLE_PROPERTY)); n = MAX (n, get_nrows (meta, MONO_TABLE_EVENT)); n = MAX (n, get_nrows (meta, MONO_TABLE_STANDALONESIG)); n = MAX (n, get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLY)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_FILE)); n = MAX (n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE)); n = MAX (n, get_nrows (meta, MONO_TABLE_MANIFESTRESOURCE)); n = MAX (n, get_nrows (meta, MONO_TABLE_GENERICPARAM)); n = MAX (n, get_nrows (meta, MONO_TABLE_GENERICPARAMCONSTRAINT)); n = MAX (n, get_nrows (meta, MONO_TABLE_METHODSPEC)); /* 5 bits to encode */ field_size = rtsize (meta, n, 16-5); break; /* * HasCustomAttribute: points to any table but * itself. */ case MONO_MT_HASCUSTDEBUG_IDX: n = MAX(get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_FIELD)); n = MAX(n, get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_TYPEDEF)); n = MAX(n, get_nrows (meta, MONO_TABLE_PARAM)); n = MAX(n, get_nrows (meta, MONO_TABLE_INTERFACEIMPL)); n = MAX(n, get_nrows (meta, MONO_TABLE_MEMBERREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_MODULE)); n = MAX(n, get_nrows (meta, MONO_TABLE_DECLSECURITY)); n = MAX(n, get_nrows (meta, MONO_TABLE_PROPERTY)); n = MAX(n, get_nrows (meta, MONO_TABLE_EVENT)); n = MAX(n, get_nrows (meta, MONO_TABLE_STANDALONESIG)); n = MAX(n, get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_TYPESPEC)); n = MAX(n, get_nrows (meta, MONO_TABLE_ASSEMBLY)); n = MAX(n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_FILE)); n = MAX(n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE)); n = MAX(n, get_nrows (meta, MONO_TABLE_MANIFESTRESOURCE)); n = MAX(n, get_nrows (meta, MONO_TABLE_GENERICPARAM)); n = MAX(n, get_nrows (meta, MONO_TABLE_GENERICPARAMCONSTRAINT)); n = MAX(n, get_nrows (meta, MONO_TABLE_METHODSPEC)); n = MAX(n, get_nrows (meta, MONO_TABLE_DOCUMENT)); n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALSCOPE)); n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALVARIABLE)); n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALCONSTANT)); n = MAX(n, get_nrows (meta, MONO_TABLE_IMPORTSCOPE)); /* 5 bits to encode */ field_size = rtsize(meta, n, 16 - 5); break; /* * CustomAttributeType: MethodDef, MemberRef. */ case MONO_MT_CAT_IDX: n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_MEMBERREF)); /* 3 bits to encode */ field_size = rtsize (meta, n, 16-3); break; /* * HasDeclSecurity: Typedef, MethodDef, Assembly */ case MONO_MT_HASDEC_IDX: n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF), get_nrows (meta, MONO_TABLE_METHOD)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLY)); /* 2 bits to encode */ field_size = rtsize (meta, n, 16-2); break; /* * Implementation: File, AssemblyRef, ExportedType */ case MONO_MT_IMPL_IDX: n = MAX (get_nrows (meta, MONO_TABLE_FILE), get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE)); /* 2 bits to encode tag */ field_size = rtsize (meta, n, 16-2); break; /* * HasFieldMarshall: FieldDef, ParamDef */ case MONO_MT_HFM_IDX: n = MAX (get_nrows (meta, MONO_TABLE_FIELD), get_nrows (meta, MONO_TABLE_PARAM)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * MemberForwarded: FieldDef, MethodDef */ case MONO_MT_MF_IDX: n = MAX (get_nrows (meta, MONO_TABLE_FIELD), get_nrows (meta, MONO_TABLE_METHOD)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * TypeDefOrRef: TypeDef, ParamDef, TypeSpec * LAMESPEC * It is TypeDef, _TypeRef_, TypeSpec, instead. */ case MONO_MT_TDOR_IDX: n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF), get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC)); /* 2 bits to encode */ field_size = rtsize (meta, n, 16-2); break; /* * MemberRefParent: TypeDef, TypeRef, MethodDef, ModuleRef, TypeSpec, MemberRef */ case MONO_MT_MRP_IDX: n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF), get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_METHOD)); n = MAX (n, get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC)); /* 3 bits to encode */ field_size = rtsize (meta, n, 16 - 3); break; /* * MethodDefOrRef: MethodDef, MemberRef */ case MONO_MT_MDOR_IDX: n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_MEMBERREF)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * HasSemantics: Property, Event */ case MONO_MT_HS_IDX: n = MAX (get_nrows (meta, MONO_TABLE_PROPERTY), get_nrows (meta, MONO_TABLE_EVENT)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * ResolutionScope: Module, ModuleRef, AssemblyRef, TypeRef */ case MONO_MT_RS_IDX: n = MAX (get_nrows (meta, MONO_TABLE_MODULE), get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEREF)); /* 2 bits used to encode tag (ECMA spec claims 3) */ field_size = rtsize (meta, n, 16 - 2); break; } /* * encode field size as follows (we just need to * distinguish them). * * 4 -> 3 * 2 -> 1 * 1 -> 0 */ bitfield |= (field_size-1) << shift; shift += 2; size += field_size; /*g_print ("table %02x field %d size %d\n", tableindex, i, field_size);*/ } *result_bitfield = (i << 24) | bitfield; return size; } /* returns true if given index is not in bounds with provided table/index pair */ gboolean mono_metadata_table_bounds_check_slow (MonoImage *image, int table_index, int token_index) { if (G_LIKELY (token_index <= table_info_get_rows (&image->tables [table_index]))) return FALSE; if (G_LIKELY (!image->has_updates)) return TRUE; return mono_metadata_update_table_bounds_check (image, table_index, token_index); } /** * mono_metadata_compute_table_bases: * \param meta metadata context to compute table values * * Computes the table bases for the metadata structure. * This is an internal function used by the image loader code. */ void mono_metadata_compute_table_bases (MonoImage *meta) { int i; const char *base = meta->tables_base; for (i = 0; i < MONO_TABLE_NUM; i++) { MonoTableInfo *table = &meta->tables [i]; if (table_info_get_rows (table) == 0) continue; table->row_size = mono_metadata_compute_size (meta, i, &table->size_bitfield); table->base = base; base += table_info_get_rows (table) * table->row_size; } } /** * mono_metadata_locate: * \param meta metadata context * \param table table code. * \param idx index of element to retrieve from \p table. * * \returns a pointer to the \p idx element in the metadata table * whose code is \p table. */ const char * mono_metadata_locate (MonoImage *meta, int table, int idx) { /* FIXME: metadata-update */ /* idx == 0 refers always to NULL */ g_return_val_if_fail (idx > 0 && idx <= table_info_get_rows (&meta->tables [table]), ""); /*FIXME shouldn't we return NULL here?*/ return meta->tables [table].base + (meta->tables [table].row_size * (idx - 1)); } /** * mono_metadata_locate_token: * \param meta metadata context * \param token metadata token * * \returns a pointer to the data in the metadata represented by the * token \p token . */ const char * mono_metadata_locate_token (MonoImage *meta, guint32 token) { return mono_metadata_locate (meta, token >> 24, token & 0xffffff); } static MonoStreamHeader * get_string_heap (MonoImage *image) { return &image->heap_strings; } static MonoStreamHeader * get_user_string_heap (MonoImage *image) { return &image->heap_us; } static MonoStreamHeader * get_blob_heap (MonoImage *image) { return &image->heap_blob; } static gboolean mono_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, guint32 orig_index, MonoImage **image_out, guint32 *index_out) { return mono_metadata_update_delta_heap_lookup (base_image, get_heap, orig_index, image_out, index_out); } /** * mono_metadata_string_heap: * \param meta metadata context * \param index index into the string heap. * \returns an in-memory pointer to the \p index in the string heap. */ const char * mono_metadata_string_heap (MonoImage *meta, guint32 index) { if (G_UNLIKELY (index >= meta->heap_strings.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_string_heap, index, &dmeta, &dindex); g_assertf (ok, "Could not find token=0x%08x in string heap of assembly=%s and its delta images", index, meta && meta->name ? meta->name : "unknown image"); meta = dmeta; index = dindex; } g_assertf (index < meta->heap_strings.size, " index = 0x%08x size = 0x%08x meta=%s ", index, meta->heap_strings.size, meta && meta->name ? meta->name : "unknown image" ); g_return_val_if_fail (index < meta->heap_strings.size, ""); return meta->heap_strings.data + index; } /** * mono_metadata_string_heap_checked: * \param meta metadata context * \param index index into the string heap. * \param error set on error * \returns an in-memory pointer to the \p index in the string heap. * On failure returns NULL and sets \p error. */ const char * mono_metadata_string_heap_checked (MonoImage *meta, guint32 index, MonoError *error) { if (mono_image_is_dynamic (meta)) { MonoDynamicImage* img = (MonoDynamicImage*) meta; const char *image_name = meta && meta->name ? meta->name : "unknown image"; if (G_UNLIKELY (!(index < img->sheap.index))) { mono_error_set_bad_image_by_name (error, image_name, "string heap index %ud out bounds %u: %s", index, img->sheap.index, image_name); return NULL; } return img->sheap.data + index; } if (G_UNLIKELY (index >= meta->heap_strings.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_string_heap, index, &dmeta, &dindex); if (G_UNLIKELY (!ok)) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "string heap index %ud out bounds %u: %s, also checked delta images", index, meta->heap_strings.size, image_name); return NULL; } meta = dmeta; index = dindex; } if (G_UNLIKELY (!(index < meta->heap_strings.size))) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "string heap index %ud out bounds %u: %s", index, meta->heap_strings.size, image_name); return NULL; } return meta->heap_strings.data + index; } /** * mono_metadata_user_string: * \param meta metadata context * \param index index into the user string heap. * \returns an in-memory pointer to the \p index in the user string heap (<code>#US</code>). */ const char * mono_metadata_user_string (MonoImage *meta, guint32 index) { if (G_UNLIKELY (index >= meta->heap_us.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_user_string_heap, index, &dmeta, &dindex); g_assertf (ok, "Could not find token=0x%08x in user string heap of assembly=%s and its delta images", index, meta && meta->name ? meta->name : "unknown image"); meta = dmeta; index = dindex; } g_assert (index < meta->heap_us.size); g_return_val_if_fail (index < meta->heap_us.size, ""); return meta->heap_us.data + index; } /** * mono_metadata_blob_heap: * \param meta metadata context * \param index index into the blob. * \returns an in-memory pointer to the \p index in the Blob heap. */ const char * mono_metadata_blob_heap (MonoImage *meta, guint32 index) { /* Some tools can produce assemblies with a size 0 Blob stream. If a * blob value is optional, if the index == 0 and heap_blob.size == 0 * assertion is hit, consider updating caller to use * mono_metadata_blob_heap_null_ok and handling a null return value. */ g_assert (!(index == 0 && meta->heap_blob.size == 0)); if (G_UNLIKELY (index >= meta->heap_blob.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_blob_heap, index, &dmeta, &dindex); g_assertf (ok, "Could not find token=0x%08x in blob heap of assembly=%s and its delta images", index, meta && meta->name ? meta->name : "unknown image"); meta = dmeta; index = dindex; } g_assert (index < meta->heap_blob.size); return meta->heap_blob.data + index; } /** * mono_metadata_blob_heap_null_ok: * \param meta metadata context * \param index index into the blob. * \return an in-memory pointer to the \p index in the Blob heap. * If the Blob heap is empty or missing and index is 0 returns NULL, instead of asserting. */ const char * mono_metadata_blob_heap_null_ok (MonoImage *meta, guint32 index) { if (G_UNLIKELY (index == 0 && meta->heap_blob.size == 0)) return NULL; else return mono_metadata_blob_heap (meta, index); } /** * mono_metadata_blob_heap_checked: * \param meta metadata context * \param index index into the blob. * \param error set on error * \returns an in-memory pointer to the \p index in the Blob heap. On failure sets \p error and returns NULL; * If the Blob heap is empty or missing and \p index is 0 returns NULL, without setting error. * */ const char * mono_metadata_blob_heap_checked (MonoImage *meta, guint32 index, MonoError *error) { if (mono_image_is_dynamic (meta)) { MonoDynamicImage* img = (MonoDynamicImage*) meta; const char *image_name = meta && meta->name ? meta->name : "unknown image"; if (G_UNLIKELY (!(index < img->blob.index))) { mono_error_set_bad_image_by_name (error, image_name, "blob heap index %u out of bounds %u: %s", index, img->blob.index, image_name); return NULL; } if (G_UNLIKELY (index == 0 && img->blob.alloc_size == 0)) return NULL; return img->blob.data + index; } if (G_UNLIKELY (index == 0 && meta->heap_blob.size == 0)) return NULL; if (G_UNLIKELY (index >= meta->heap_blob.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_blob_heap, index, &dmeta, &dindex); if (G_UNLIKELY(!ok)) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "Could not find token=0x%08x in blob heap of assembly=%s and its delta images", index, image_name); return NULL; } meta = dmeta; index = dindex; } if (G_UNLIKELY (!(index < meta->heap_blob.size))) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "blob heap index %u out of bounds %u: %s", index, meta->heap_blob.size, image_name); return NULL; } return meta->heap_blob.data + index; } /** * mono_metadata_guid_heap: * \param meta metadata context * \param index index into the guid heap. * \returns an in-memory pointer to the \p index in the guid heap. */ const char * mono_metadata_guid_heap (MonoImage *meta, guint32 index) { /* EnC TODO: lookup in DeltaInfo:delta_image_last. Unlike the other heaps, the GUID heaps are always full in every delta, even in minimal delta images. */ --index; index *= 16; /* adjust for guid size and 1-based index */ g_return_val_if_fail (index < meta->heap_guid.size, ""); return meta->heap_guid.data + index; } static const unsigned char * dword_align (const unsigned char *ptr) { return (const unsigned char *) (((gsize) (ptr + 3)) & ~3); } static void mono_metadata_decode_row_slow (const MonoTableInfo *t, int idx, guint32 *res, int res_size); /** * mono_metadata_decode_row: * \param t table to extract information from. * \param idx index in table. * \param res array of \p res_size cols to store the results in * * This decompresses the metadata element \p idx in table \p t * into the \c guint32 \p res array that has \p res_size elements */ void mono_metadata_decode_row (const MonoTableInfo *t, int idx, guint32 *res, int res_size) { if (G_UNLIKELY (mono_metadata_has_updates ())) { mono_metadata_decode_row_slow (t, idx, res, res_size); } else { mono_metadata_decode_row_raw (t, idx, res, res_size); } } void mono_metadata_decode_row_slow (const MonoTableInfo *t, int idx, guint32 *res, int res_size) { mono_image_effective_table (&t, idx); mono_metadata_decode_row_raw (t, idx, res, res_size); } /** * same as mono_metadata_decode_row, but ignores potential delta images */ void mono_metadata_decode_row_raw (const MonoTableInfo *t, int idx, guint32 *res, int res_size) { guint32 bitfield = t->size_bitfield; int i, count = mono_metadata_table_count (bitfield); const char *data; g_assert (idx < table_info_get_rows (t)); g_assert (idx >= 0); data = t->base + idx * t->row_size; g_assert (res_size == count); for (i = 0; i < count; i++) { int n = mono_metadata_table_size (bitfield, i); switch (n){ case 1: res [i] = *data; break; case 2: res [i] = read16 (data); break; case 4: res [i] = read32 (data); break; default: g_assert_not_reached (); } data += n; } } /** * mono_metadata_decode_row_checked: * \param image the \c MonoImage the table belongs to * \param t table to extract information from. * \param idx index in the table. * \param res array of \p res_size cols to store the results in * \param error set on bounds error * * * This decompresses the metadata element \p idx in the table \p t * into the \c guint32 \p res array that has \p res_size elements. * * \returns TRUE if the read succeeded. Otherwise sets \p error and returns FALSE. */ gboolean mono_metadata_decode_row_checked (const MonoImage *image, const MonoTableInfo *t, int idx, guint32 *res, int res_size, MonoError *error) { const char *image_name = image && image->name ? image->name : "unknown image"; mono_image_effective_table (&t, idx); guint32 bitfield = t->size_bitfield; int i, count = mono_metadata_table_count (bitfield); if (G_UNLIKELY (! (idx < table_info_get_rows (t) && idx >= 0))) { mono_error_set_bad_image_by_name (error, image_name, "row index %d out of bounds: %d rows: %s", idx, table_info_get_rows (t), image_name); return FALSE; } const char *data = t->base + idx * t->row_size; if (G_UNLIKELY (res_size != count)) { mono_error_set_bad_image_by_name (error, image_name, "res_size %d != count %d: %s", res_size, count, image_name); return FALSE; } for (i = 0; i < count; i++) { int n = mono_metadata_table_size (bitfield, i); switch (n) { case 1: res [i] = *data; break; case 2: res [i] = read16 (data); break; case 4: res [i] = read32 (data); break; default: mono_error_set_bad_image_by_name (error, image_name, "unexpected table [%d] size %d: %s", i, n, image_name); return FALSE; } data += n; } return TRUE; } gboolean mono_metadata_decode_row_dynamic_checked (const MonoDynamicImage *image, const MonoDynamicTable *t, int idx, guint32 *res, int res_size, MonoError *error) { int i, count = t->columns; const char *image_name = image && image->image.name ? image->image.name : "unknown image"; if (G_UNLIKELY (! (idx < t->rows && idx >= 0))) { mono_error_set_bad_image_by_name (error, image_name, "row index %d out of bounds: %d rows: %s", idx, t->rows, image_name); return FALSE; } guint32 *data = t->values + (idx + 1) * count; if (G_UNLIKELY (res_size != count)) { mono_error_set_bad_image_by_name (error, image_name, "res_size %d != count %d: %s", res_size, count, image_name); return FALSE; } for (i = 0; i < count; i++) { res [i] = *data; data++; } return TRUE; } static guint32 mono_metadata_decode_row_col_raw (const MonoTableInfo *t, int idx, guint col); static guint32 mono_metadata_decode_row_col_slow (const MonoTableInfo *t, int idx, guint col); /** * mono_metadata_decode_row_col: * \param t table to extract information from. * \param idx index for row in table. * \param col column in the row. * * This function returns the value of column \p col from the \p idx * row in the table \p t . */ guint32 mono_metadata_decode_row_col (const MonoTableInfo *t, int idx, guint col) { if (G_UNLIKELY (mono_metadata_has_updates ())) { return mono_metadata_decode_row_col_slow (t, idx, col); } else { return mono_metadata_decode_row_col_raw (t, idx, col); } } guint32 mono_metadata_decode_row_col_slow (const MonoTableInfo *t, int idx, guint col) { mono_image_effective_table (&t, idx); return mono_metadata_decode_row_col_raw (t, idx, col); } /** * mono_metadata_decode_row_col_raw: * * Same as \c mono_metadata_decode_row_col but doesn't look for the effective * table on metadata updates. */ guint32 mono_metadata_decode_row_col_raw (const MonoTableInfo *t, int idx, guint col) { int i; const char *data; int n; guint32 bitfield = t->size_bitfield; g_assert (idx < table_info_get_rows (t)); g_assert (col < mono_metadata_table_count (bitfield)); data = t->base + idx * t->row_size; n = mono_metadata_table_size (bitfield, 0); for (i = 0; i < col; ++i) { data += n; n = mono_metadata_table_size (bitfield, i + 1); } switch (n) { case 1: return *data; case 2: return read16 (data); case 4: return read32 (data); default: g_assert_not_reached (); } return 0; } /** * mono_metadata_decode_blob_size: * \param ptr pointer to a blob object * \param rptr the new position of the pointer * * This decodes a compressed size as described by 24.2.4 (#US and #Blob a blob or user string object) * * \returns the size of the blob object */ guint32 mono_metadata_decode_blob_size (const char *xptr, const char **rptr) { const unsigned char *ptr = (const unsigned char *)xptr; guint32 size; if ((*ptr & 0x80) == 0){ size = ptr [0] & 0x7f; ptr++; } else if ((*ptr & 0x40) == 0){ size = ((ptr [0] & 0x3f) << 8) + ptr [1]; ptr += 2; } else { size = ((ptr [0] & 0x1f) << 24) + (ptr [1] << 16) + (ptr [2] << 8) + ptr [3]; ptr += 4; } if (rptr) *rptr = (char*)ptr; return size; } /** * mono_metadata_decode_value: * \param ptr pointer to decode from * \param rptr the new position of the pointer * * This routine decompresses 32-bit values as specified in the "Blob and * Signature" section (23.2) * * \returns the decoded value */ guint32 mono_metadata_decode_value (const char *_ptr, const char **rptr) { const unsigned char *ptr = (const unsigned char *) _ptr; unsigned char b = *ptr; guint32 len; if ((b & 0x80) == 0){ len = b; ++ptr; } else if ((b & 0x40) == 0){ len = ((b & 0x3f) << 8 | ptr [1]); ptr += 2; } else { len = ((b & 0x1f) << 24) | (ptr [1] << 16) | (ptr [2] << 8) | ptr [3]; ptr += 4; } if (rptr) *rptr = (char*)ptr; return len; } /** * mono_metadata_decode_signed_value: * \param ptr pointer to decode from * \param rptr the new position of the pointer * * This routine decompresses 32-bit signed values * (not specified in the spec) * * \returns the decoded value */ gint32 mono_metadata_decode_signed_value (const char *ptr, const char **rptr) { guint32 uval = mono_metadata_decode_value (ptr, rptr); gint32 ival = uval >> 1; if (!(uval & 1)) return ival; /* ival is a truncated 2's complement negative number. */ if (ival < 0x40) /* 6 bits = 7 bits for compressed representation (top bit is '0') - 1 sign bit */ return ival - 0x40; if (ival < 0x2000) /* 13 bits = 14 bits for compressed representation (top bits are '10') - 1 sign bit */ return ival - 0x2000; if (ival < 0x10000000) /* 28 bits = 29 bits for compressed representation (top bits are '110') - 1 sign bit */ return ival - 0x10000000; g_assert (ival < 0x20000000); g_warning ("compressed signed value appears to use 29 bits for compressed representation: %x (raw: %8x)", ival, uval); return ival - 0x20000000; } /** * mono_metadata_translate_token_index: * Translates the given 1-based index into the \c Method, \c Field, \c Event, or \c Param tables * using the \c *Ptr tables in uncompressed metadata, if they are available. * * FIXME: The caller is not forced to call this function, which is error-prone, since * forgetting to call it would only show up as a bug on uncompressed metadata. */ guint32 mono_metadata_translate_token_index (MonoImage *image, int table, guint32 idx) { if (!image->uncompressed_metadata) return idx; switch (table) { case MONO_TABLE_METHOD: if (table_info_get_rows (&image->tables [MONO_TABLE_METHOD_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD_POINTER], idx - 1, MONO_METHOD_POINTER_METHOD); else return idx; case MONO_TABLE_FIELD: if (table_info_get_rows (&image->tables [MONO_TABLE_FIELD_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_FIELD_POINTER], idx - 1, MONO_FIELD_POINTER_FIELD); else return idx; case MONO_TABLE_EVENT: if (table_info_get_rows (&image->tables [MONO_TABLE_EVENT_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_EVENT_POINTER], idx - 1, MONO_EVENT_POINTER_EVENT); else return idx; case MONO_TABLE_PROPERTY: if (table_info_get_rows (&image->tables [MONO_TABLE_PROPERTY_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_PROPERTY_POINTER], idx - 1, MONO_PROPERTY_POINTER_PROPERTY); else return idx; case MONO_TABLE_PARAM: if (table_info_get_rows (&image->tables [MONO_TABLE_PARAM_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_PARAM_POINTER], idx - 1, MONO_PARAM_POINTER_PARAM); else return idx; default: return idx; } } /** * mono_metadata_decode_table_row: * * Same as \c mono_metadata_decode_row, but takes an \p image + \p table ID pair, and takes * uncompressed metadata into account, so it should be used to access the * \c Method, \c Field, \c Param and \c Event tables when the access is made from metadata, i.e. * \p idx is retrieved from a metadata table, like \c MONO_TYPEDEF_FIELD_LIST. */ void mono_metadata_decode_table_row (MonoImage *image, int table, int idx, guint32 *res, int res_size) { if (image->uncompressed_metadata) idx = mono_metadata_translate_token_index (image, table, idx + 1) - 1; mono_metadata_decode_row (&image->tables [table], idx, res, res_size); } /** * mono_metadata_decode_table_row_col: * * Same as \c mono_metadata_decode_row_col, but takes an \p image + \p table ID pair, and takes * uncompressed metadata into account, so it should be used to access the * \c Method, \c Field, \c Param and \c Event tables. */ guint32 mono_metadata_decode_table_row_col (MonoImage *image, int table, int idx, guint col) { if (image->uncompressed_metadata) idx = mono_metadata_translate_token_index (image, table, idx + 1) - 1; return mono_metadata_decode_row_col (&image->tables [table], idx, col); } /** * mono_metadata_parse_typedef_or_ref: * \param m a metadata context. * \param ptr a pointer to an encoded TypedefOrRef in \p m * \param rptr pointer updated to match the end of the decoded stream * \returns a token valid in the \p m metadata decoded from * the compressed representation. */ guint32 mono_metadata_parse_typedef_or_ref (MonoImage *m, const char *ptr, const char **rptr) { guint32 token; token = mono_metadata_decode_value (ptr, &ptr); if (rptr) *rptr = ptr; return mono_metadata_token_from_dor (token); } /** * mono_metadata_parse_custom_mod: * \param m a metadata context. * \param dest storage where the info about the custom modifier is stored (may be NULL) * \param ptr a pointer to (possibly) the start of a custom modifier list * \param rptr pointer updated to match the end of the decoded stream * * Checks if \p ptr points to a type custom modifier compressed representation. * * \returns TRUE if a custom modifier was found, FALSE if not. */ int mono_metadata_parse_custom_mod (MonoImage *m, MonoCustomMod *dest, const char *ptr, const char **rptr) { MonoCustomMod local; if ((*ptr == MONO_TYPE_CMOD_OPT) || (*ptr == MONO_TYPE_CMOD_REQD)) { if (!dest) dest = &local; dest->required = *ptr == MONO_TYPE_CMOD_REQD ? 1 : 0; dest->token = mono_metadata_parse_typedef_or_ref (m, ptr + 1, rptr); return TRUE; } return FALSE; } /* * mono_metadata_parse_array_internal: * @m: a metadata context. * @transient: whenever to allocate data from the heap * @ptr: a pointer to an encoded array description. * @rptr: pointer updated to match the end of the decoded stream * * Decodes the compressed array description found in the metadata @m at @ptr. * * Returns: a #MonoArrayType structure describing the array type * and dimensions. Memory is allocated from the heap or from the image mempool, depending * on the value of @transient. * * LOCKING: Acquires the loader lock */ static MonoArrayType * mono_metadata_parse_array_internal (MonoImage *m, MonoGenericContainer *container, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { int i; MonoArrayType *array; MonoType *etype; etype = mono_metadata_parse_type_checked (m, container, 0, FALSE, ptr, &ptr, error); //FIXME this doesn't respect @transient if (!etype) return NULL; array = transient ? (MonoArrayType *)g_malloc0 (sizeof (MonoArrayType)) : (MonoArrayType *)mono_image_alloc0 (m, sizeof (MonoArrayType)); array->eklass = mono_class_from_mono_type_internal (etype); array->rank = mono_metadata_decode_value (ptr, &ptr); array->numsizes = mono_metadata_decode_value (ptr, &ptr); if (array->numsizes) array->sizes = transient ? (int *)g_malloc0 (sizeof (int) * array->numsizes) : (int *)mono_image_alloc0 (m, sizeof (int) * array->numsizes); for (i = 0; i < array->numsizes; ++i) array->sizes [i] = mono_metadata_decode_value (ptr, &ptr); array->numlobounds = mono_metadata_decode_value (ptr, &ptr); if (array->numlobounds) array->lobounds = transient ? (int *)g_malloc0 (sizeof (int) * array->numlobounds) : (int *)mono_image_alloc0 (m, sizeof (int) * array->numlobounds); for (i = 0; i < array->numlobounds; ++i) array->lobounds [i] = mono_metadata_decode_signed_value (ptr, &ptr); if (rptr) *rptr = ptr; return array; } /** * mono_metadata_parse_array: */ MonoArrayType * mono_metadata_parse_array (MonoImage *m, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoArrayType *ret = mono_metadata_parse_array_internal (m, NULL, FALSE, ptr, rptr, error); mono_error_cleanup (error); return ret; } /** * mono_metadata_free_array: * \param array array description * * Frees the array description returned from \c mono_metadata_parse_array. */ void mono_metadata_free_array (MonoArrayType *array) { g_free (array->sizes); g_free (array->lobounds); g_free (array); } /* * need to add common field and param attributes combinations: * [out] param * public static * public static literal * private * private static * private static literal */ static const MonoType builtin_types[] = { /* data, attrs, type, nmods, byref, pinned */ {{NULL}, 0, MONO_TYPE_VOID, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_BOOLEAN, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_BOOLEAN, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_CHAR, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_CHAR, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I1, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I1, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U1, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U1, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I2, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I2, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U2, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U2, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I4, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I4, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U4, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U4, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I8, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I8, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U8, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U8, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_R4, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_R4, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_R8, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_R8, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_STRING, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_STRING, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_OBJECT, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_OBJECT, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_TYPEDBYREF, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U, 0, 1, 0}, }; static GHashTable *type_cache = NULL; static gint32 next_generic_inst_id = 0; static guint mono_generic_class_hash (gconstpointer data); /* * MonoTypes with modifies are never cached, so we never check or use that field. */ static guint mono_type_hash (gconstpointer data) { const MonoType *type = (const MonoType *) data; if (type->type == MONO_TYPE_GENERICINST) return mono_generic_class_hash (type->data.generic_class); else return type->type | ((m_type_is_byref (type) ? 1 : 0) << 8) | (type->attrs << 9); } static gint mono_type_equal (gconstpointer ka, gconstpointer kb) { const MonoType *a = (const MonoType *) ka; const MonoType *b = (const MonoType *) kb; if (a->type != b->type || m_type_is_byref (a) != m_type_is_byref (b) || a->attrs != b->attrs || a->pinned != b->pinned) return 0; /* need other checks */ return 1; } guint mono_metadata_generic_inst_hash (gconstpointer data) { const MonoGenericInst *ginst = (const MonoGenericInst *) data; guint hash = 0; int i; g_assert (ginst); g_assert (ginst->type_argv); for (i = 0; i < ginst->type_argc; ++i) { hash *= 13; g_assert (ginst->type_argv [i]); hash += mono_metadata_type_hash (ginst->type_argv [i]); } return hash ^ (ginst->is_open << 8); } static gboolean mono_generic_inst_equal_full (const MonoGenericInst *a, const MonoGenericInst *b, gboolean signature_only) { int i; // An optimization: if the ids of two insts are the same, we know they are the same inst and don't check contents. // Furthermore, because we perform early de-duping, if the ids differ, we know the contents differ. #ifndef MONO_SMALL_CONFIG // Optimization does not work in MONO_SMALL_CONFIG: There are no IDs if (a->id && b->id) { // "id 0" means "object has no id"-- de-duping hasn't been performed yet, must check contents. if (a->id == b->id) return TRUE; // In signature-comparison mode id equality implies object equality, but this is not true for inequality. // Two separate objects could have signature-equavalent contents. if (!signature_only) return FALSE; } #endif if (a->is_open != b->is_open || a->type_argc != b->type_argc) return FALSE; for (i = 0; i < a->type_argc; ++i) { if (!do_mono_metadata_type_equal (a->type_argv [i], b->type_argv [i], signature_only)) return FALSE; } return TRUE; } gboolean mono_metadata_generic_inst_equal (gconstpointer ka, gconstpointer kb) { const MonoGenericInst *a = (const MonoGenericInst *) ka; const MonoGenericInst *b = (const MonoGenericInst *) kb; return mono_generic_inst_equal_full (a, b, FALSE); } static guint mono_generic_class_hash (gconstpointer data) { const MonoGenericClass *gclass = (const MonoGenericClass *) data; guint hash = mono_metadata_type_hash (m_class_get_byval_arg (gclass->container_class)); hash *= 13; hash += gclass->is_tb_open; hash += mono_metadata_generic_context_hash (&gclass->context); return hash; } static gboolean mono_generic_class_equal (gconstpointer ka, gconstpointer kb) { const MonoGenericClass *a = (const MonoGenericClass *) ka; const MonoGenericClass *b = (const MonoGenericClass *) kb; return _mono_metadata_generic_class_equal (a, b, FALSE); } /** * mono_metadata_init: * * Initialize the global variables of this module. * This is a Mono runtime internal function. */ void mono_metadata_init (void) { int i; /* We guard against double initialization due to how pedump in verification mode works. Until runtime initialization is properly factored to work with what it needs we need workarounds like this. FIXME: https://bugzilla.xamarin.com/show_bug.cgi?id=58793 */ static gboolean inited; if (inited) return; inited = TRUE; type_cache = g_hash_table_new (mono_type_hash, mono_type_equal); for (i = 0; i < G_N_ELEMENTS (builtin_types); ++i) g_hash_table_insert (type_cache, (gpointer) &builtin_types [i], (gpointer) &builtin_types [i]); mono_metadata_update_init (); } /* * Make a pass over the metadata signature blob starting at \p tmp_ptr and count the custom modifiers. */ static int count_custom_modifiers (MonoImage *m, const char *tmp_ptr) { int count = 0; gboolean found = TRUE; while (found) { switch (*tmp_ptr) { case MONO_TYPE_PINNED: case MONO_TYPE_BYREF: ++tmp_ptr; break; case MONO_TYPE_CMOD_REQD: case MONO_TYPE_CMOD_OPT: count ++; mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr); break; default: found = FALSE; } } return count; } /* * Decode the (expected \p count, possibly 0) custom modifiers as well as the "byref" and "pinned" * markers from the metadata stream \p ptr and put them into \p cmods * * Sets \p rptr past the end of the parsed metadata. Sets \p pinned and \p byref if those modifiers * were present. */ static void decode_custom_modifiers (MonoImage *m, MonoCustomModContainer *cmods, int count, const char *ptr, const char **rptr, gboolean *pinned, gboolean *byref) { gboolean found = TRUE; /* cmods are encoded in reverse order from how we normally see them. * "int32 modopt (Foo) modopt (Bar)" is encoded as "cmod_opt [typedef_or_ref "Bar"] cmod_opt [typedef_or_ref "Foo"] I4" */ while (found) { switch (*ptr) { case MONO_TYPE_PINNED: *pinned = TRUE; ++ptr; break; case MONO_TYPE_BYREF: *byref = TRUE; ++ptr; break; case MONO_TYPE_CMOD_REQD: case MONO_TYPE_CMOD_OPT: g_assert (count > 0); mono_metadata_parse_custom_mod (m, &(cmods->modifiers [--count]), ptr, &ptr); break; default: found = FALSE; } } // either there were no cmods, or else we iterated through all of cmods backwards to populate it. g_assert (count == 0); *rptr = ptr; } /* * Allocate the memory necessary to hold a \c MonoType with \p count custom modifiers. * If \p transient is true, allocate from the heap, otherwise allocate from the mempool of image \p m */ static MonoType * alloc_type_with_cmods (MonoImage *m, gboolean transient, int count) { g_assert (count > 0); MonoType *type; size_t size = mono_sizeof_type_with_mods (count, FALSE); type = transient ? (MonoType *)g_malloc0 (size) : (MonoType *)mono_image_alloc0 (m, size); type->has_cmods = TRUE; MonoCustomModContainer *cmods = mono_type_get_cmods (type); cmods->count = count; cmods->image = m; return type; } /* * If \p transient is true, free \p type, otherwise no-op */ static void free_parsed_type (MonoType *type, gboolean transient) { if (transient) mono_metadata_free_type (type); } /* * Try to find a pre-allocated version of the given \p type. * Returns true and sets \p canonical_type if found, otherwise return false. * * For classes and valuetypes, this returns their embedded byval_arg or * this_arg types. For base types, it returns the global versions. */ static gboolean try_get_canonical_type (MonoType *type, MonoType **canonical_type) { /* Note: If the type has any attribtues or modifiers the function currently returns false, * although there's no fundamental reason we can't have cached copies in those instances (or * indeed cached arrays, pointers or some generic instances). However in that case there's * limited utility in returning a cached copy because the parsing code in * do_mono_metadata_parse_type could have allocated some mempool or heap memory already. * * This function should be kept closely in sync with mono_metadata_free_type so that it * doesn't try to free canonical MonoTypes (which might not even be heap allocated). */ g_assert (!type->has_cmods); if ((type->type == MONO_TYPE_CLASS || type->type == MONO_TYPE_VALUETYPE) && !type->pinned && !type->attrs) { MonoType *ret = m_type_is_byref (type) ? m_class_get_this_arg (type->data.klass) : m_class_get_byval_arg (type->data.klass); /* Consider the case: class Foo<T> { class Bar {} } class Test : Foo<Test>.Bar {} When Foo<Test> is being expanded, 'Test' isn't yet initialized. It's actually in a really pristine state: it doesn't even know whether 'Test' is a reference or a value type. We ensure that the MonoClass is in a state that we can canonicalize to: klass->_byval_arg.data.klass == klass klass->this_arg.data.klass == klass If we can't canonicalize 'type', it doesn't matter, since later users of 'type' will do it. LOCKING: even though we don't explicitly hold a lock, in the problematic case 'ret' is a field of a MonoClass which currently holds the loader lock. 'type' is local. */ if (ret->data.klass == type->data.klass) { *canonical_type = ret; return TRUE; } } /* Maybe it's one of the globaly-known basic types */ MonoType *cached; /* No need to use locking since nobody is modifying the hash table */ if ((cached = (MonoType *)g_hash_table_lookup (type_cache, type))) { *canonical_type = cached; return TRUE; } return FALSE; } /* * Fill in \p type (expecting \p cmod_count custom modifiers) by parsing it from the metadata stream pointed at by \p ptr. * * On success returns true and sets \p rptr past the parsed stream data. On failure return false and sets \p error. */ static gboolean do_mono_metadata_parse_type_with_cmods (MonoType *type, int cmod_count, MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { gboolean byref= FALSE; gboolean pinned = FALSE; error_init (error); /* Iterate again, but now parse pinned, byref and custom modifiers */ decode_custom_modifiers (m, mono_type_get_cmods (type), cmod_count, ptr, &ptr, &pinned, &byref); type->attrs = opt_attrs; type->byref__ = byref; type->pinned = pinned ? 1 : 0; if (!do_mono_metadata_parse_type (type, m, container, transient, ptr, &ptr, error)) return FALSE; if (rptr) *rptr = ptr; return TRUE; } /** * mono_metadata_parse_type: * \param m metadata context * \param mode kind of type that may be found at \p ptr * \param opt_attrs optional attributes to store in the returned type * \param ptr pointer to the type representation * \param rptr pointer updated to match the end of the decoded stream * \param transient whenever to allocate the result from the heap or from a mempool * * Decode a compressed type description found at \p ptr in \p m . * \p mode can be one of \c MONO_PARSE_MOD_TYPE, \c MONO_PARSE_PARAM, \c MONO_PARSE_RET, * \c MONO_PARSE_FIELD, \c MONO_PARSE_LOCAL, \c MONO_PARSE_TYPE. * This function can be used to decode type descriptions in method signatures, * field signatures, locals signatures etc. * * To parse a generic type, \c generic_container points to the current class'es * (the \c generic_container field in the <code>MonoClass</code>) or the current generic method's * (stored in <code>image->property_hash</code>) generic container. * When we encounter a \c MONO_TYPE_VAR or \c MONO_TYPE_MVAR, it's looked up in * this \c MonoGenericContainer. * * LOCKING: Acquires the loader lock. * * \returns a \c MonoType structure representing the decoded type. */ static MonoType* mono_metadata_parse_type_internal (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { MonoType *type; MonoType stype; int count = 0; // Number of mod arguments gboolean allocated = FALSE; error_init (error); /* * Q: What's going on with `stype` and `allocated`? A: A very common case is that we're * parsing "int" or "string" or "Dictionary<K,V>" non-transiently. In that case we don't * want to flood the mempool with millions of copies of MonoType 'int' (etc). So we parse * it into a stack variable and try_get_canonical_type, below. As long as the type is * normal, we will avoid having to make an extra copy in the mempool. */ /* * According to the spec, custom modifiers should come before the byref * flag, but the IL produced by ilasm from the following signature: * object modopt(...) & * starts with a byref flag, followed by the modifiers. (bug #49802) * Also, this type seems to be different from 'object & modopt(...)'. Maybe * it would be better to treat byref as real type constructor instead of * a modifier... * Also, pinned should come before anything else, but some MSV++ produced * assemblies violate this (#bug 61990). */ /* Count the modifiers first */ count = count_custom_modifiers (m, ptr); if (count) { // There are mods, so the MonoType will be of nonstandard size. allocated = TRUE; if (count > 64) { mono_error_set_bad_image (error, m, "Invalid type with more than 64 modifiers"); return NULL; } type = alloc_type_with_cmods (m, transient, count); } else { // The type is of standard size, so we can allocate it on the stack. type = &stype; memset (type, 0, MONO_SIZEOF_TYPE); } if (!do_mono_metadata_parse_type_with_cmods (type, count, m, container, opt_attrs, transient, ptr, rptr, error)) { if (allocated) free_parsed_type (type, transient); return NULL; } // Possibly we can return an already-allocated type instead of the one we decoded if (!allocated && !transient) { /* no need to free type here, because it is on the stack */ MonoType *ret_type = NULL; if (try_get_canonical_type (type, &ret_type)) return ret_type; } /* printf ("%x %x %c %s\n", type->attrs, type->num_mods, type->pinned ? 'p' : ' ', mono_type_full_name (type)); */ // Otherwise return the type we decoded if (!allocated) { // Type was allocated on the stack, so we need to copy it to safety type = transient ? (MonoType *)g_malloc (MONO_SIZEOF_TYPE) : (MonoType *)mono_image_alloc (m, MONO_SIZEOF_TYPE); memcpy (type, &stype, MONO_SIZEOF_TYPE); } g_assert (type != &stype); return type; } MonoType* mono_metadata_parse_type_checked (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { return mono_metadata_parse_type_internal (m, container, opt_attrs, transient, ptr, rptr, error); } /* * LOCKING: Acquires the loader lock. */ MonoType* mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoType * type = mono_metadata_parse_type_internal (m, NULL, opt_attrs, FALSE, ptr, rptr, error); mono_error_cleanup (error); return type; } gboolean mono_metadata_method_has_param_attrs (MonoImage *m, int def) { MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM]; MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD]; guint lastp, i, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST); /* FIXME: metadata-update */ if (def < table_info_get_rows (methodt)) lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST); else lastp = table_info_get_rows (&m->tables [MONO_TABLE_PARAM]) + 1; for (i = param_index; i < lastp; ++i) { guint32 flags = mono_metadata_decode_row_col (paramt, i - 1, MONO_PARAM_FLAGS); if (flags) return TRUE; } return FALSE; } /* * mono_metadata_get_param_attrs: * * @m The image to loader parameter attributes from * @def method def token (one based) * @param_count number of params to decode including the return value * * Return the parameter attributes for the method whose MethodDef index is DEF. The * returned memory needs to be freed by the caller. If all the param attributes are * 0, then NULL is returned. */ int* mono_metadata_get_param_attrs (MonoImage *m, int def, int param_count) { MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM]; MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD]; guint32 cols [MONO_PARAM_SIZE]; guint lastp, i, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST); int *pattrs = NULL; /* hot reload deltas may specify 0 for the param table index */ if (param_index == 0) return NULL; /* FIXME: metadata-update */ int rows = mono_metadata_table_num_rows (m, MONO_TABLE_METHOD); if (def < rows) lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST); else lastp = table_info_get_rows (paramt) + 1; for (i = param_index; i < lastp; ++i) { mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE); if (cols [MONO_PARAM_FLAGS]) { if (!pattrs) pattrs = g_new0 (int, param_count); /* at runtime we just ignore this kind of malformed file: * the verifier can signal the error to the user */ if (cols [MONO_PARAM_SEQUENCE] >= param_count) continue; pattrs [cols [MONO_PARAM_SEQUENCE]] = cols [MONO_PARAM_FLAGS]; } } return pattrs; } /** * mono_metadata_parse_signature: * \param image metadata context * \param token metadata token * * Decode a method signature stored in the \c StandAloneSig table * * \returns a \c MonoMethodSignature describing the signature. */ MonoMethodSignature* mono_metadata_parse_signature (MonoImage *image, guint32 token) { ERROR_DECL (error); MonoMethodSignature *ret; ret = mono_metadata_parse_signature_checked (image, token, error); mono_error_cleanup (error); return ret; } /* * mono_metadata_parse_signature_checked: * @image: metadata context * @token: metadata token * @error: set on error * * Decode a method signature stored in the STANDALONESIG table * * Returns: a MonoMethodSignature describing the signature. On failure * returns NULL and sets @error. */ MonoMethodSignature* mono_metadata_parse_signature_checked (MonoImage *image, guint32 token, MonoError *error) { error_init (error); MonoTableInfo *tables = image->tables; guint32 idx = mono_metadata_token_index (token); guint32 sig; const char *ptr; if (image_is_dynamic (image)) { return (MonoMethodSignature *)mono_lookup_dynamic_token (image, token, NULL, error); } g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG); sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0); ptr = mono_metadata_blob_heap (image, sig); mono_metadata_decode_blob_size (ptr, &ptr); return mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error); } /** * mono_metadata_signature_alloc: * \param image metadata context * \param nparams number of parameters in the signature * * Allocate a \c MonoMethodSignature structure with the specified number of params. * The return type and the params types need to be filled later. * This is a Mono runtime internal function. * * LOCKING: Assumes the loader lock is held. * * \returns the new \c MonoMethodSignature structure. */ MonoMethodSignature* mono_metadata_signature_alloc (MonoImage *m, guint32 nparams) { MonoMethodSignature *sig; sig = (MonoMethodSignature *)mono_image_alloc0 (m, MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)nparams) * sizeof (MonoType*)); sig->param_count = nparams; sig->sentinelpos = -1; return sig; } static MonoMethodSignature* mono_metadata_signature_dup_internal (MonoImage *image, MonoMemPool *mp, MonoMemoryManager *mem_manager, MonoMethodSignature *sig, size_t padding) { int sigsize, sig_header_size; MonoMethodSignature *ret; sigsize = sig_header_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *) + padding; if (sig->ret) sigsize += mono_sizeof_type (sig->ret); if (image) { ret = (MonoMethodSignature *)mono_image_alloc (image, sigsize); } else if (mp) { ret = (MonoMethodSignature *)mono_mempool_alloc (mp, sigsize); } else if (mem_manager) { ret = (MonoMethodSignature *)mono_mem_manager_alloc (mem_manager, sigsize); } else { ret = (MonoMethodSignature *)g_malloc (sigsize); } memcpy (ret, sig, sig_header_size - padding); // Copy return value because of ownership semantics. if (sig->ret) { // Danger! Do not alter padding use without changing the dup_add_this below intptr_t end_of_header = (intptr_t)( (char*)(ret) + sig_header_size); ret->ret = (MonoType *)end_of_header; memcpy (ret->ret, sig->ret, mono_sizeof_type (sig->ret)); } return ret; } /* * signature_dup_add_this: * * Make a copy of @sig, adding an explicit this argument. */ MonoMethodSignature* mono_metadata_signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass) { MonoMethodSignature *ret; ret = mono_metadata_signature_dup_internal (image, NULL, NULL, sig, sizeof (MonoType *)); ret->param_count = sig->param_count + 1; ret->hasthis = FALSE; for (int i = sig->param_count - 1; i >= 0; i --) ret->params [i + 1] = sig->params [i]; ret->params [0] = m_class_is_valuetype (klass) ? m_class_get_this_arg (klass) : m_class_get_byval_arg (klass); for (int i = sig->param_count - 1; i >= 0; i --) g_assert(ret->params [i + 1]->type == sig->params [i]->type && ret->params [i+1]->type != MONO_TYPE_END); g_assert (ret->ret->type == sig->ret->type && ret->ret->type != MONO_TYPE_END); return ret; } MonoMethodSignature* mono_metadata_signature_dup_full (MonoImage *image, MonoMethodSignature *sig) { MonoMethodSignature *ret = mono_metadata_signature_dup_internal (image, NULL, NULL, sig, 0); for (int i = 0 ; i < sig->param_count; i ++) g_assert (ret->params [i]->type == sig->params [i]->type); g_assert (ret->ret->type == sig->ret->type); return ret; } /*The mempool is accessed without synchronization*/ MonoMethodSignature* mono_metadata_signature_dup_mempool (MonoMemPool *mp, MonoMethodSignature *sig) { return mono_metadata_signature_dup_internal (NULL, mp, NULL, sig, 0); } MonoMethodSignature* mono_metadata_signature_dup_mem_manager (MonoMemoryManager *mem_manager, MonoMethodSignature *sig) { return mono_metadata_signature_dup_internal (NULL, NULL, mem_manager, sig, 0); } /** * mono_metadata_signature_dup: * \param sig method signature * * Duplicate an existing \c MonoMethodSignature so it can be modified. * This is a Mono runtime internal function. * * \returns the new \c MonoMethodSignature structure. */ MonoMethodSignature* mono_metadata_signature_dup (MonoMethodSignature *sig) { return mono_metadata_signature_dup_full (NULL, sig); } /* * mono_metadata_signature_size: * * Return the amount of memory allocated to SIG. */ guint32 mono_metadata_signature_size (MonoMethodSignature *sig) { return MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *); } /** * metadata_signature_set_modopt_call_conv: * * Reads the custom attributes from \p cmod_type and adds them to the signature \p sig. * * This follows the C# unmanaged function pointer encoding. * The modopts are from the System.Runtime.CompilerServices namespace and all have a name of the form CallConvXXX. * * The calling convention will be one of: * Cdecl, Thiscall, Stdcall, Fastcall * plus an optional SuppressGCTransition */ static void metadata_signature_set_modopt_call_conv (MonoMethodSignature *sig, MonoType *cmod_type, MonoError *error) { uint8_t count = mono_type_custom_modifier_count (cmod_type); if (count == 0) return; int base_callconv = sig->call_convention; gboolean suppress_gc_transition = sig->suppress_gc_transition; for (uint8_t i = 0; i < count; ++i) { gboolean req = FALSE; MonoType *cmod = mono_type_get_custom_modifier (cmod_type, i, &req, error); return_if_nok (error); /* callconv is a modopt, not a modreq */ if (req) continue; /* shouldn't be a valuetype, array, gparam, gtd, ginst etc */ if (cmod->type != MONO_TYPE_CLASS) continue; MonoClass *cmod_klass = mono_class_from_mono_type_internal (cmod); if (m_class_get_image (cmod_klass) != mono_defaults.corlib) continue; if (strcmp (m_class_get_name_space (cmod_klass), "System.Runtime.CompilerServices")) continue; const char *name = m_class_get_name (cmod_klass); if (strstr (name, "CallConv") != name) continue; name += strlen ("CallConv"); /* skip the prefix */ /* Check for the known base unmanaged calling conventions */ if (!strcmp (name, "Cdecl")) { base_callconv = MONO_CALL_C; continue; } else if (!strcmp (name, "Stdcall")) { base_callconv = MONO_CALL_STDCALL; continue; } else if (!strcmp (name, "Thiscall")) { base_callconv = MONO_CALL_THISCALL; continue; } else if (!strcmp (name, "Fastcall")) { base_callconv = MONO_CALL_FASTCALL; continue; } /* Check for known calling convention modifiers */ if (!strcmp (name, "SuppressGCTransition")) { suppress_gc_transition = TRUE; continue; } } sig->call_convention = base_callconv; sig->suppress_gc_transition = suppress_gc_transition; } /** * mono_metadata_parse_method_signature_full: * \param m metadata context * \param generic_container: generics container * \param def the \c MethodDef index or 0 for \c Ref signatures. * \param ptr pointer to the signature metadata representation * \param rptr pointer updated to match the end of the decoded stream * \param error set on error * * * Decode a method signature stored at \p ptr. * This is a Mono runtime internal function. * * LOCKING: Assumes the loader lock is held. * * \returns a \c MonoMethodSignature describing the signature. On error sets * \p error and returns \c NULL. */ MonoMethodSignature * mono_metadata_parse_method_signature_full (MonoImage *m, MonoGenericContainer *container, int def, const char *ptr, const char **rptr, MonoError *error) { MonoMethodSignature *method; int i, *pattrs = NULL; guint32 hasthis = 0, explicit_this = 0, call_convention, param_count; guint32 gen_param_count = 0; gboolean is_open = FALSE; error_init (error); if (*ptr & 0x10) gen_param_count = 1; if (*ptr & 0x20) hasthis = 1; if (*ptr & 0x40) explicit_this = 1; call_convention = *ptr & 0x0F; ptr++; if (gen_param_count) gen_param_count = mono_metadata_decode_value (ptr, &ptr); param_count = mono_metadata_decode_value (ptr, &ptr); if (def) pattrs = mono_metadata_get_param_attrs (m, def, param_count + 1); /*Must be + 1 since signature's param count doesn't account for the return value */ method = mono_metadata_signature_alloc (m, param_count); method->hasthis = hasthis; method->explicit_this = explicit_this; method->call_convention = call_convention; method->generic_param_count = gen_param_count; switch (method->call_convention) { case MONO_CALL_DEFAULT: case MONO_CALL_VARARG: method->pinvoke = 0; break; case MONO_CALL_C: case MONO_CALL_STDCALL: case MONO_CALL_THISCALL: case MONO_CALL_FASTCALL: case MONO_CALL_UNMANAGED_MD: method->pinvoke = 1; break; } if (call_convention != 0xa) { method->ret = mono_metadata_parse_type_checked (m, container, pattrs ? pattrs [0] : 0, FALSE, ptr, &ptr, error); if (!method->ret) { mono_metadata_free_method_signature (method); g_free (pattrs); return NULL; } is_open = mono_class_is_open_constructed_type (method->ret); if (G_UNLIKELY (method->ret->has_cmods && method->call_convention == MONO_CALL_UNMANAGED_MD)) { /* calling convention encoded in modopts */ metadata_signature_set_modopt_call_conv (method, method->ret, error); if (!is_ok (error)) { g_free (pattrs); return NULL; } } } for (i = 0; i < method->param_count; ++i) { if (*ptr == MONO_TYPE_SENTINEL) { if (method->call_convention != MONO_CALL_VARARG || def) { mono_error_set_bad_image (error, m, "Found sentinel for methoddef or no vararg"); g_free (pattrs); return NULL; } if (method->sentinelpos >= 0) { mono_error_set_bad_image (error, m, "Found sentinel twice in the same signature."); g_free (pattrs); return NULL; } method->sentinelpos = i; ptr++; } method->params [i] = mono_metadata_parse_type_checked (m, container, pattrs ? pattrs [i+1] : 0, FALSE, ptr, &ptr, error); if (!method->params [i]) { mono_metadata_free_method_signature (method); g_free (pattrs); return NULL; } if (!is_open) is_open = mono_class_is_open_constructed_type (method->params [i]); } /* The sentinel could be missing if the caller does not pass any additional arguments */ if (!def && method->call_convention == MONO_CALL_VARARG && method->sentinelpos < 0) method->sentinelpos = method->param_count; method->has_type_parameters = is_open; if (def && (method->call_convention == MONO_CALL_VARARG)) method->sentinelpos = method->param_count; g_free (pattrs); if (rptr) *rptr = ptr; /* * Add signature to a cache and increase ref count... */ return method; } /** * mono_metadata_parse_method_signature: * \param m metadata context * \param def the \c MethodDef index or 0 for \c Ref signatures. * \param ptr pointer to the signature metadata representation * \param rptr pointer updated to match the end of the decoded stream * * Decode a method signature stored at \p ptr. * This is a Mono runtime internal function. * * LOCKING: Assumes the loader lock is held. * * \returns a \c MonoMethodSignature describing the signature. */ MonoMethodSignature * mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr) { /* * This function MUST NOT be called by runtime code as it does error handling incorrectly. * Use mono_metadata_parse_method_signature_full instead. * It's ok to asser on failure as we no longer use it. */ ERROR_DECL (error); MonoMethodSignature *ret; ret = mono_metadata_parse_method_signature_full (m, NULL, def, ptr, rptr, error); mono_error_assert_ok (error); return ret; } /** * mono_metadata_free_method_signature: * \param sig signature to destroy * * Free the memory allocated in the signature \p sig. * This method needs to be robust and work also on partially-built * signatures, so it does extra checks. */ void mono_metadata_free_method_signature (MonoMethodSignature *sig) { /* Everything is allocated from mempools */ /* int i; if (sig->ret) mono_metadata_free_type (sig->ret); for (i = 0; i < sig->param_count; ++i) { if (sig->params [i]) mono_metadata_free_type (sig->params [i]); } */ } void mono_metadata_free_inflated_signature (MonoMethodSignature *sig) { int i; /* Allocated in inflate_generic_signature () */ if (sig->ret) mono_metadata_free_type (sig->ret); for (i = 0; i < sig->param_count; ++i) { if (sig->params [i]) mono_metadata_free_type (sig->params [i]); } g_free (sig); } static gboolean inflated_method_equal (gconstpointer a, gconstpointer b) { const MonoMethodInflated *ma = (const MonoMethodInflated *)a; const MonoMethodInflated *mb = (const MonoMethodInflated *)b; if (ma->declaring != mb->declaring) return FALSE; return mono_metadata_generic_context_equal (&ma->context, &mb->context); } static guint inflated_method_hash (gconstpointer a) { const MonoMethodInflated *ma = (const MonoMethodInflated *)a; return (mono_metadata_generic_context_hash (&ma->context) ^ mono_aligned_addr_hash (ma->declaring)); } static gboolean inflated_signature_equal (gconstpointer a, gconstpointer b) { const MonoInflatedMethodSignature *sig1 = (const MonoInflatedMethodSignature *)a; const MonoInflatedMethodSignature *sig2 = (const MonoInflatedMethodSignature *)b; /* sig->sig is assumed to be canonized */ if (sig1->sig != sig2->sig) return FALSE; /* The generic instances are canonized */ return mono_metadata_generic_context_equal (&sig1->context, &sig2->context); } static guint inflated_signature_hash (gconstpointer a) { const MonoInflatedMethodSignature *sig = (const MonoInflatedMethodSignature *)a; /* sig->sig is assumed to be canonized */ return mono_metadata_generic_context_hash (&sig->context) ^ mono_aligned_addr_hash (sig->sig); } /*static void dump_ginst (MonoGenericInst *ginst) { int i; char *name; g_print ("Ginst: <"); for (i = 0; i < ginst->type_argc; ++i) { if (i != 0) g_print (", "); name = mono_type_get_name (ginst->type_argv [i]); g_print ("%s", name); g_free (name); } g_print (">"); }*/ static gboolean aggregate_modifiers_equal (gconstpointer ka, gconstpointer kb) { MonoAggregateModContainer *amods1 = (MonoAggregateModContainer *)ka; MonoAggregateModContainer *amods2 = (MonoAggregateModContainer *)kb; if (amods1->count != amods2->count) return FALSE; for (int i = 0; i < amods1->count; ++i) { if (amods1->modifiers [i].required != amods2->modifiers [i].required) return FALSE; if (!mono_metadata_type_equal_full (amods1->modifiers [i].type, amods2->modifiers [i].type, TRUE)) return FALSE; } return TRUE; } static guint aggregate_modifiers_hash (gconstpointer a) { const MonoAggregateModContainer *amods = (const MonoAggregateModContainer *)a; guint hash = 0; for (int i = 0; i < amods->count; ++i) { // hash details borrowed from mono_metadata_generic_inst_hash hash *= 13; hash ^= (amods->modifiers [i].required << 8); hash += mono_metadata_type_hash (amods->modifiers [i].type); } return hash; } static gboolean type_in_image (MonoType *type, MonoImage *image); static gboolean aggregate_modifiers_in_image (MonoAggregateModContainer *amods, MonoImage *image); static gboolean signature_in_image (MonoMethodSignature *sig, MonoImage *image) { gpointer iter = NULL; MonoType *p; while ((p = mono_signature_get_params_internal (sig, &iter)) != NULL) if (type_in_image (p, image)) return TRUE; return type_in_image (mono_signature_get_return_type_internal (sig), image); } static gboolean ginst_in_image (MonoGenericInst *ginst, MonoImage *image) { int i; for (i = 0; i < ginst->type_argc; ++i) { if (type_in_image (ginst->type_argv [i], image)) return TRUE; } return FALSE; } static gboolean gclass_in_image (MonoGenericClass *gclass, MonoImage *image) { return m_class_get_image (gclass->container_class) == image || ginst_in_image (gclass->context.class_inst, image); } static gboolean type_in_image (MonoType *type, MonoImage *image) { retry: if (type->has_cmods && mono_type_is_aggregate_mods (type)) if (aggregate_modifiers_in_image (mono_type_get_amods (type), image)) return TRUE; switch (type->type) { case MONO_TYPE_GENERICINST: return gclass_in_image (type->data.generic_class, image); case MONO_TYPE_PTR: type = type->data.type; goto retry; case MONO_TYPE_SZARRAY: type = m_class_get_byval_arg (type->data.klass); goto retry; case MONO_TYPE_ARRAY: type = m_class_get_byval_arg (type->data.array->eklass); goto retry; case MONO_TYPE_FNPTR: return signature_in_image (type->data.method, image); case MONO_TYPE_VAR: case MONO_TYPE_MVAR: if (image == mono_get_image_for_generic_param (type->data.generic_param)) return TRUE; else if (type->data.generic_param->gshared_constraint) { type = type->data.generic_param->gshared_constraint; goto retry; } return FALSE; default: /* At this point, we should've avoided all potential allocations in mono_class_from_mono_type_internal () */ return image == m_class_get_image (mono_class_from_mono_type_internal (type)); } } gboolean mono_type_in_image (MonoType *type, MonoImage *image) { return type_in_image (type, image); } gboolean aggregate_modifiers_in_image (MonoAggregateModContainer *amods, MonoImage *image) { for (int i = 0; i < amods->count; i++) if (type_in_image (amods->modifiers [i].type, image)) return TRUE; return FALSE; } /* * Structure used by the collect_..._images functions to store the image list. */ typedef struct { MonoImage *image_buf [64]; MonoImage **images; int nimages, images_len; } CollectData; static void collect_data_init (CollectData *data) { data->images = data->image_buf; data->images_len = 64; data->nimages = 0; } static void collect_data_free (CollectData *data) { if (data->images != data->image_buf) g_free (data->images); } static void enlarge_data (CollectData *data) { int new_len = data->images_len < 16 ? 16 : data->images_len * 2; MonoImage **d = g_new (MonoImage *, new_len); // FIXME: test this g_assert_not_reached (); memcpy (d, data->images, data->images_len); if (data->images != data->image_buf) g_free (data->images); data->images = d; data->images_len = new_len; } static void add_image (MonoImage *image, CollectData *data) { int i; /* The arrays are small, so use a linear search instead of a hash table */ for (i = 0; i < data->nimages; ++i) if (data->images [i] == image) return; if (data->nimages == data->images_len) enlarge_data (data); data->images [data->nimages ++] = image; } static void collect_type_images (MonoType *type, CollectData *data); static void collect_ginst_images (MonoGenericInst *ginst, CollectData *data) { int i; for (i = 0; i < ginst->type_argc; ++i) { collect_type_images (ginst->type_argv [i], data); } } static void collect_gclass_images (MonoGenericClass *gclass, CollectData *data) { add_image (m_class_get_image (gclass->container_class), data); if (gclass->context.class_inst) collect_ginst_images (gclass->context.class_inst, data); } static void collect_signature_images (MonoMethodSignature *sig, CollectData *data) { gpointer iter = NULL; MonoType *p; collect_type_images (mono_signature_get_return_type_internal (sig), data); while ((p = mono_signature_get_params_internal (sig, &iter)) != NULL) collect_type_images (p, data); } static void collect_inflated_signature_images (MonoInflatedMethodSignature *sig, CollectData *data) { collect_signature_images (sig->sig, data); if (sig->context.class_inst) collect_ginst_images (sig->context.class_inst, data); if (sig->context.method_inst) collect_ginst_images (sig->context.method_inst, data); } static void collect_method_images (MonoMethodInflated *method, CollectData *data) { MonoMethod *m = method->declaring; add_image (m_class_get_image (method->declaring->klass), data); if (method->context.class_inst) collect_ginst_images (method->context.class_inst, data); if (method->context.method_inst) collect_ginst_images (method->context.method_inst, data); /* * Dynamic assemblies have no references, so the images they depend on can be unloaded before them. */ if (image_is_dynamic (m_class_get_image (m->klass))) collect_signature_images (mono_method_signature_internal (m), data); } static void collect_aggregate_modifiers_images (MonoAggregateModContainer *amods, CollectData *data) { for (int i = 0; i < amods->count; ++i) collect_type_images (amods->modifiers [i].type, data); } static void collect_type_images (MonoType *type, CollectData *data) { retry: if (G_UNLIKELY (type->has_cmods && mono_type_is_aggregate_mods (type))) { collect_aggregate_modifiers_images (mono_type_get_amods (type), data); } switch (type->type) { case MONO_TYPE_GENERICINST: collect_gclass_images (type->data.generic_class, data); break; case MONO_TYPE_PTR: type = type->data.type; goto retry; case MONO_TYPE_SZARRAY: type = m_class_get_byval_arg (type->data.klass); goto retry; case MONO_TYPE_ARRAY: type = m_class_get_byval_arg (type->data.array->eklass); goto retry; case MONO_TYPE_FNPTR: collect_signature_images (type->data.method, data); break; case MONO_TYPE_VAR: case MONO_TYPE_MVAR: { MonoImage *image = mono_get_image_for_generic_param (type->data.generic_param); add_image (image, data); type = type->data.generic_param->gshared_constraint; if (type) goto retry; break; } case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: add_image (m_class_get_image (mono_class_from_mono_type_internal (type)), data); break; default: add_image (mono_defaults.corlib, data); } } typedef struct { MonoImage *image; GSList *list; } CleanForImageUserData; static gboolean steal_gclass_in_image (gpointer key, gpointer value, gpointer data) { MonoGenericClass *gclass = (MonoGenericClass *)key; CleanForImageUserData *user_data = (CleanForImageUserData *)data; g_assert (gclass_in_image (gclass, user_data->image)); user_data->list = g_slist_prepend (user_data->list, gclass); return TRUE; } static gboolean steal_ginst_in_image (gpointer key, gpointer value, gpointer data) { MonoGenericInst *ginst = (MonoGenericInst *)key; CleanForImageUserData *user_data = (CleanForImageUserData *)data; // This doesn't work during corlib compilation //g_assert (ginst_in_image (ginst, user_data->image)); user_data->list = g_slist_prepend (user_data->list, ginst); return TRUE; } static gboolean steal_aggregate_modifiers_in_image (gpointer key, gpointer value, gpointer data) { MonoAggregateModContainer *amods = (MonoAggregateModContainer *)key; CleanForImageUserData *user_data = (CleanForImageUserData *)data; g_assert (aggregate_modifiers_in_image (amods, user_data->image)); user_data->list = g_slist_prepend (user_data->list, amods); return TRUE; } static gboolean inflated_method_in_image (gpointer key, gpointer value, gpointer data) { MonoImage *image = (MonoImage *)data; MonoMethodInflated *method = (MonoMethodInflated *)key; // FIXME: // https://bugzilla.novell.com/show_bug.cgi?id=458168 g_assert (m_class_get_image (method->declaring->klass) == image || (method->context.class_inst && ginst_in_image (method->context.class_inst, image)) || (method->context.method_inst && ginst_in_image (method->context.method_inst, image)) || (((MonoMethod*)method)->signature && signature_in_image (mono_method_signature_internal ((MonoMethod*)method), image))); return TRUE; } static gboolean inflated_signature_in_image (gpointer key, gpointer value, gpointer data) { MonoImage *image = (MonoImage *)data; MonoInflatedMethodSignature *sig = (MonoInflatedMethodSignature *)key; return signature_in_image (sig->sig, image) || (sig->context.class_inst && ginst_in_image (sig->context.class_inst, image)) || (sig->context.method_inst && ginst_in_image (sig->context.method_inst, image)); } static gboolean class_in_image (gpointer key, gpointer value, gpointer data) { MonoImage *image = (MonoImage *)data; MonoClass *klass = (MonoClass *)key; g_assert (type_in_image (m_class_get_byval_arg (klass), image)); return TRUE; } static void check_gmethod (gpointer key, gpointer value, gpointer data) { MonoMethodInflated *method = (MonoMethodInflated *)key; MonoImage *image = (MonoImage *)data; if (method->context.class_inst) g_assert (!ginst_in_image (method->context.class_inst, image)); if (method->context.method_inst) g_assert (!ginst_in_image (method->context.method_inst, image)); if (((MonoMethod*)method)->signature) g_assert (!signature_in_image (mono_method_signature_internal ((MonoMethod*)method), image)); } static void free_generic_inst (MonoGenericInst *ginst) { int i; /* The ginst itself is allocated from the image set mempool */ for (i = 0; i < ginst->type_argc; ++i) mono_metadata_free_type (ginst->type_argv [i]); } static void free_generic_class (MonoGenericClass *gclass) { /* The gclass itself is allocated from the image set mempool */ if (gclass->cached_class && m_class_get_interface_id (gclass->cached_class)) mono_unload_interface_id (gclass->cached_class); } static void free_inflated_signature (MonoInflatedMethodSignature *sig) { mono_metadata_free_inflated_signature (sig->sig); } static void free_aggregate_modifiers (MonoAggregateModContainer *amods) { for (int i = 0; i < amods->count; i++) mono_metadata_free_type (amods->modifiers [i].type); /* the container itself is allocated in the image set mempool */ } /* * mono_metadata_get_inflated_signature: * * Given an inflated signature and a generic context, return a canonical copy of the * signature. The returned signature might be equal to SIG or it might be a cached copy. */ MonoMethodSignature * mono_metadata_get_inflated_signature (MonoMethodSignature *sig, MonoGenericContext *context) { MonoInflatedMethodSignature helper; MonoInflatedMethodSignature *res; CollectData data; helper.sig = sig; helper.context.class_inst = context->class_inst; helper.context.method_inst = context->method_inst; collect_data_init (&data); collect_inflated_signature_images (&helper, &data); MonoMemoryManager *mm = mono_mem_manager_get_generic (data.images, data.nimages); collect_data_free (&data); mono_mem_manager_lock (mm); if (!mm->gsignature_cache) mm->gsignature_cache = g_hash_table_new_full (inflated_signature_hash, inflated_signature_equal, NULL, (GDestroyNotify)free_inflated_signature); res = (MonoInflatedMethodSignature *)g_hash_table_lookup (mm->gsignature_cache, &helper); if (!res) { res = mono_mem_manager_alloc0 (mm, sizeof (MonoInflatedMethodSignature)); res->sig = sig; res->context.class_inst = context->class_inst; res->context.method_inst = context->method_inst; g_hash_table_insert (mm->gsignature_cache, res, res); } mono_mem_manager_unlock (mm); return res->sig; } MonoMemoryManager * mono_metadata_get_mem_manager_for_type (MonoType *type) { MonoMemoryManager *mm; CollectData image_set_data; collect_data_init (&image_set_data); collect_type_images (type, &image_set_data); mm = mono_mem_manager_get_generic (image_set_data.images, image_set_data.nimages); collect_data_free (&image_set_data); return mm; } MonoMemoryManager * mono_metadata_get_mem_manager_for_class (MonoClass *klass) { return mono_metadata_get_mem_manager_for_type (m_class_get_byval_arg (klass)); } MonoMemoryManager * mono_metadata_get_mem_manager_for_method (MonoMethodInflated *method) { MonoMemoryManager *mm; CollectData image_set_data; collect_data_init (&image_set_data); collect_method_images (method, &image_set_data); mm = mono_mem_manager_get_generic (image_set_data.images, image_set_data.nimages); collect_data_free (&image_set_data); return mm; } static MonoMemoryManager * mono_metadata_get_mem_manager_for_aggregate_modifiers (MonoAggregateModContainer *amods) { MonoMemoryManager *mm; CollectData image_set_data; collect_data_init (&image_set_data); collect_aggregate_modifiers_images (amods, &image_set_data); mm = mono_mem_manager_get_generic (image_set_data.images, image_set_data.nimages); collect_data_free (&image_set_data); return mm; } static gboolean type_is_gtd (MonoType *type) { switch (type->type) { case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: return mono_class_is_gtd (type->data.klass); default: return FALSE; } } /* * mono_metadata_get_generic_inst: * * Given a list of types, return a MonoGenericInst that represents that list. * The returned MonoGenericInst has its own copy of the list of types. The list * passed in the argument can be freed, modified or disposed of. * */ MonoGenericInst * mono_metadata_get_generic_inst (int type_argc, MonoType **type_argv) { MonoGenericInst *ginst; gboolean is_open; int i; int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *); for (i = 0; i < type_argc; ++i) if (mono_class_is_open_constructed_type (type_argv [i])) break; is_open = (i < type_argc); ginst = (MonoGenericInst *)g_alloca (size); memset (ginst, 0, MONO_SIZEOF_GENERIC_INST); ginst->is_open = is_open; ginst->type_argc = type_argc; memcpy (ginst->type_argv, type_argv, type_argc * sizeof (MonoType *)); for (i = 0; i < type_argc; ++i) { MonoType *t = ginst->type_argv [i]; if (type_is_gtd (t)) { ginst->type_argv [i] = mono_class_gtd_get_canonical_inst (t->data.klass); } } return mono_metadata_get_canonical_generic_inst (ginst); } /** * mono_metadata_get_canonical_generic_inst: * \param candidate an arbitrary generic instantiation * * \returns the canonical generic instantiation that represents the given * candidate by identifying the image set for the candidate instantiation and * finding the instance in the image set or adding a copy of the given instance * to the image set. * * The returned MonoGenericInst has its own copy of the list of types. The list * passed in the argument can be freed, modified or disposed of. * */ MonoGenericInst * mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate) { CollectData data; int type_argc = candidate->type_argc; gboolean is_open = candidate->is_open; collect_data_init (&data); collect_ginst_images (candidate, &data); MonoMemoryManager *mm = mono_mem_manager_get_generic (data.images, data.nimages); collect_data_free (&data); mono_mem_manager_lock (mm); if (!mm->ginst_cache) mm->ginst_cache = g_hash_table_new_full (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal, NULL, (GDestroyNotify)free_generic_inst); MonoGenericInst *ginst = (MonoGenericInst *)g_hash_table_lookup (mm->ginst_cache, candidate); if (!ginst) { int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *); ginst = (MonoGenericInst *)mono_mem_manager_alloc0 (mm, size); #ifndef MONO_SMALL_CONFIG ginst->id = mono_atomic_inc_i32 (&next_generic_inst_id); #endif ginst->is_open = is_open; ginst->type_argc = type_argc; // FIXME: Dup into the mem manager for (int i = 0; i < type_argc; ++i) ginst->type_argv [i] = mono_metadata_type_dup (NULL, candidate->type_argv [i]); g_hash_table_insert (mm->ginst_cache, ginst, ginst); } mono_mem_manager_unlock (mm); return ginst; } MonoAggregateModContainer * mono_metadata_get_canonical_aggregate_modifiers (MonoAggregateModContainer *candidate) { g_assert (candidate->count > 0); MonoMemoryManager *mm = mono_metadata_get_mem_manager_for_aggregate_modifiers (candidate); mono_mem_manager_lock (mm); if (!mm->aggregate_modifiers_cache) mm->aggregate_modifiers_cache = g_hash_table_new_full (aggregate_modifiers_hash, aggregate_modifiers_equal, NULL, (GDestroyNotify)free_aggregate_modifiers); MonoAggregateModContainer *amods = (MonoAggregateModContainer *)g_hash_table_lookup (mm->aggregate_modifiers_cache, candidate); if (!amods) { size_t size = mono_sizeof_aggregate_modifiers (candidate->count); amods = (MonoAggregateModContainer *)mono_mem_manager_alloc0 (mm, size); amods->count = candidate->count; for (int i = 0; i < candidate->count; ++i) { amods->modifiers [i].required = candidate->modifiers [i].required; amods->modifiers [i].type = mono_metadata_type_dup (NULL, candidate->modifiers [i].type); } g_hash_table_insert (mm->aggregate_modifiers_cache, amods, amods); } mono_mem_manager_unlock (mm); return amods; } static gboolean mono_metadata_is_type_builder_generic_type_definition (MonoClass *container_class, MonoGenericInst *inst, gboolean is_dynamic) { MonoGenericContainer *container = mono_class_get_generic_container (container_class); if (!is_dynamic || m_class_was_typebuilder (container_class) || container->type_argc != inst->type_argc) return FALSE; return inst == container->context.class_inst; } /* * mono_metadata_lookup_generic_class: * * Returns a MonoGenericClass with the given properties. * */ MonoGenericClass * mono_metadata_lookup_generic_class (MonoClass *container_class, MonoGenericInst *inst, gboolean is_dynamic) { MonoGenericClass *gclass; MonoGenericClass helper; gboolean is_tb_open = mono_metadata_is_type_builder_generic_type_definition (container_class, inst, is_dynamic); CollectData data; g_assert (mono_class_get_generic_container (container_class)->type_argc == inst->type_argc); memset (&helper, 0, sizeof(helper)); // act like g_new0 helper.container_class = container_class; helper.context.class_inst = inst; helper.is_dynamic = is_dynamic; /* We use this in a hash lookup, which does not attempt to downcast the pointer */ helper.is_tb_open = is_tb_open; collect_data_init (&data); collect_gclass_images (&helper, &data); MonoMemoryManager *mm = mono_mem_manager_get_generic (data.images, data.nimages); collect_data_free (&data); if (!mm->gclass_cache) { mono_mem_manager_lock (mm); if (!mm->gclass_cache) { MonoConcurrentHashTable *cache = mono_conc_hashtable_new_full (mono_generic_class_hash, mono_generic_class_equal, NULL, (GDestroyNotify)free_generic_class); mono_memory_barrier (); mm->gclass_cache = cache; } mono_mem_manager_unlock (mm); } gclass = (MonoGenericClass *)mono_conc_hashtable_lookup (mm->gclass_cache, &helper); /* A tripwire just to keep us honest */ g_assert (!helper.cached_class); if (gclass) return gclass; mono_mem_manager_lock (mm); gclass = mono_mem_manager_alloc0 (mm, sizeof (MonoGenericClass)); if (is_dynamic) gclass->is_dynamic = 1; gclass->is_tb_open = is_tb_open; gclass->container_class = container_class; gclass->context.class_inst = inst; gclass->context.method_inst = NULL; gclass->owner = mm; if (inst == mono_class_get_generic_container (container_class)->context.class_inst && !is_tb_open) gclass->cached_class = container_class; MonoGenericClass *gclass2 = (MonoGenericClass*)mono_conc_hashtable_insert (mm->gclass_cache, gclass, gclass); if (!gclass2) gclass2 = gclass; // g_hash_table_insert (set->gclass_cache, gclass, gclass); mono_mem_manager_unlock (mm); return gclass2; } /* * mono_metadata_inflate_generic_inst: * * Instantiate the generic instance @ginst with the context @context. * Check @error for success. * */ MonoGenericInst * mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context, MonoError *error) { MonoType **type_argv; MonoGenericInst *nginst = NULL; int i, count = 0; error_init (error); if (!ginst->is_open) return ginst; type_argv = g_new0 (MonoType*, ginst->type_argc); for (i = 0; i < ginst->type_argc; i++) { type_argv [i] = mono_class_inflate_generic_type_checked (ginst->type_argv [i], context, error); if (!is_ok (error)) goto cleanup; ++count; } nginst = mono_metadata_get_generic_inst (ginst->type_argc, type_argv); cleanup: for (i = 0; i < count; i++) mono_metadata_free_type (type_argv [i]); g_free (type_argv); return nginst; } MonoGenericInst * mono_metadata_parse_generic_inst (MonoImage *m, MonoGenericContainer *container, int count, const char *ptr, const char **rptr, MonoError *error) { MonoType **type_argv; MonoGenericInst *ginst = NULL; int i, parse_count = 0; error_init (error); type_argv = g_new0 (MonoType*, count); for (i = 0; i < count; i++) { /* this can be a transient type, mono_metadata_get_generic_inst will allocate * a canonical one, if needed. */ MonoType *t = mono_metadata_parse_type_checked (m, container, 0, TRUE, ptr, &ptr, error); if (!t) goto cleanup; type_argv [i] = t; parse_count++; } if (rptr) *rptr = ptr; g_assert (parse_count == count); ginst = mono_metadata_get_generic_inst (count, type_argv); cleanup: for (i = 0; i < parse_count; i++) mono_metadata_free_type (type_argv [i]); g_free (type_argv); return ginst; } static gboolean do_mono_metadata_parse_generic_class (MonoType *type, MonoImage *m, MonoGenericContainer *container, const char *ptr, const char **rptr, MonoError *error) { MonoGenericInst *inst; MonoClass *gklass; MonoType *gtype; int count; error_init (error); // XXX how about transient? gtype = mono_metadata_parse_type_checked (m, NULL, 0, FALSE, ptr, &ptr, error); if (gtype == NULL) return FALSE; gklass = mono_class_from_mono_type_internal (gtype); if (!mono_class_is_gtd (gklass)) { mono_error_set_bad_image (error, m, "Generic instance with non-generic definition"); return FALSE; } count = mono_metadata_decode_value (ptr, &ptr); inst = mono_metadata_parse_generic_inst (m, container, count, ptr, &ptr, error); if (inst == NULL) return FALSE; if (rptr) *rptr = ptr; type->data.generic_class = mono_metadata_lookup_generic_class (gklass, inst, FALSE); return TRUE; } /* * select_container: * @gc: The generic container to normalize * @type: The kind of generic parameters the resulting generic-container should contain */ static MonoGenericContainer * select_container (MonoGenericContainer *gc, MonoTypeEnum type) { gboolean is_var = (type == MONO_TYPE_VAR); if (!gc) return NULL; g_assert (is_var || type == MONO_TYPE_MVAR); if (is_var) { if (gc->is_method || gc->parent) /* * The current MonoGenericContainer is a generic method -> its `parent' * points to the containing class'es container. */ return gc->parent; } return gc; } MonoGenericContainer * mono_get_anonymous_container_for_image (MonoImage *image, gboolean is_mvar) { MonoGenericContainer **container_pointer; if (is_mvar) container_pointer = &image->anonymous_generic_method_container; else container_pointer = &image->anonymous_generic_class_container; MonoGenericContainer *result = *container_pointer; // This container has never been created; make it now. if (!result) { // Note this is never deallocated anywhere-- it exists for the lifetime of the image it's allocated from result = (MonoGenericContainer *)mono_image_alloc0 (image, sizeof (MonoGenericContainer)); result->owner.image = image; result->is_anonymous = TRUE; result->is_method = is_mvar; // If another thread already made a container, use that and leak this new one. // (Technically it would currently be safe to just assign instead of CASing.) MonoGenericContainer *exchange = (MonoGenericContainer *)mono_atomic_cas_ptr ((volatile gpointer *)container_pointer, result, NULL); if (exchange) result = exchange; } return result; } #define FAST_GPARAM_CACHE_SIZE 16 static MonoGenericParam* lookup_anon_gparam (MonoImage *image, MonoGenericContainer *container, gint32 param_num, gboolean is_mvar) { if (param_num >= 0 && param_num < FAST_GPARAM_CACHE_SIZE) { MonoGenericParam *cache = is_mvar ? image->mvar_gparam_cache_fast : image->var_gparam_cache_fast; if (!cache) return NULL; return &cache[param_num]; } else { MonoGenericParam key; memset (&key, 0, sizeof (key)); key.owner = container; key.num = param_num; key.gshared_constraint = NULL; MonoConcurrentHashTable *cache = is_mvar ? image->mvar_gparam_cache : image->var_gparam_cache; if (!cache) return NULL; return (MonoGenericParam*)mono_conc_hashtable_lookup (cache, &key); } } static MonoGenericParam* publish_anon_gparam_fast (MonoImage *image, MonoGenericContainer *container, gint32 param_num) { g_assert (param_num >= 0 && param_num < FAST_GPARAM_CACHE_SIZE); MonoGenericParam **cache = container->is_method ? &image->mvar_gparam_cache_fast : &image->var_gparam_cache_fast; if (!*cache) { mono_image_lock (image); if (!*cache) { *cache = (MonoGenericParam*)mono_image_alloc0 (image, sizeof (MonoGenericParam) * FAST_GPARAM_CACHE_SIZE); for (gint32 i = 0; i < FAST_GPARAM_CACHE_SIZE; ++i) { MonoGenericParam *param = &(*cache)[i]; param->owner = container; param->num = i; } } mono_image_unlock (image); } return &(*cache)[param_num]; } /* * publish_anon_gparam_slow: * * Publish \p gparam anonymous generic parameter to the anon gparam cache for \p image. * * LOCKING: takes the image lock. */ static MonoGenericParam* publish_anon_gparam_slow (MonoImage *image, MonoGenericParam *gparam) { MonoConcurrentHashTable **cache = gparam->owner->is_method ? &image->mvar_gparam_cache : &image->var_gparam_cache; if (!*cache) { mono_image_lock (image); if (!*cache) { MonoConcurrentHashTable *ht = mono_conc_hashtable_new ((GHashFunc)mono_metadata_generic_param_hash, (GEqualFunc) mono_metadata_generic_param_equal); mono_atomic_store_release (cache, ht); } mono_image_unlock (image); } MonoGenericParam *other = (MonoGenericParam*)mono_conc_hashtable_insert (*cache, gparam, gparam); // If another thread published first return their param, otherwise return ours. return other ? other : gparam; } /** * mono_metadata_create_anon_gparam: * \param image the MonoImage that owns the anonymous generic parameter * \param param_num the parameter number * \param is_mvar TRUE if this is a method generic parameter, FALSE if it's a class generic parameter. * * Returns: a new, or exisisting \c MonoGenericParam for an anonymous generic parameter with the given properties. * * LOCKING: takes the image lock. */ MonoGenericParam* mono_metadata_create_anon_gparam (MonoImage *image, gint32 param_num, gboolean is_mvar) { MonoGenericContainer *container = mono_get_anonymous_container_for_image (image, is_mvar); MonoGenericParam *gparam = lookup_anon_gparam (image, container, param_num, is_mvar); if (gparam) return gparam; if (param_num >= 0 && param_num < FAST_GPARAM_CACHE_SIZE) { return publish_anon_gparam_fast (image, container, param_num); } else { // Create a candidate generic param and try to insert it in the cache. // If multiple threads both try to publish the same param, all but one // will leak, but that's okay. gparam = (MonoGenericParam*)mono_image_alloc0 (image, sizeof (MonoGenericParam)); gparam->owner = container; gparam->num = param_num; return publish_anon_gparam_slow (image, gparam); } } /* * mono_metadata_parse_generic_param: * @generic_container: Our MonoClass's or MonoMethod's MonoGenericContainer; * see mono_metadata_parse_type_checked() for details. * Internal routine to parse a generic type parameter. * LOCKING: Acquires the loader lock */ static MonoGenericParam * mono_metadata_parse_generic_param (MonoImage *m, MonoGenericContainer *generic_container, MonoTypeEnum type, const char *ptr, const char **rptr, MonoError *error) { int index = mono_metadata_decode_value (ptr, &ptr); if (rptr) *rptr = ptr; error_init (error); generic_container = select_container (generic_container, type); if (!generic_container) { gboolean is_mvar = FALSE; switch (type) { case MONO_TYPE_VAR: break; case MONO_TYPE_MVAR: is_mvar = TRUE; break; default: g_error ("Cerating generic param object with invalid MonoType"); // This is not a generic param } return mono_metadata_create_anon_gparam (m, index, is_mvar); } if (index >= generic_container->type_argc) { mono_error_set_bad_image (error, m, "Invalid generic %s parameter index %d, max index is %d", generic_container->is_method ? "method" : "type", index, generic_container->type_argc); return NULL; } //This can't return NULL return mono_generic_container_get_param (generic_container, index); } /* * mono_metadata_get_shared_type: * * Return a shared instance of TYPE, if available, NULL otherwise. * Shared MonoType instances help save memory. Their contents should not be modified * by the caller. They do not need to be freed as their lifetime is bound by either * the lifetime of the runtime (builtin types), or the lifetime of the MonoClass * instance they are embedded in. If they are freed, they should be freed using * mono_metadata_free_type () instead of g_free (). */ MonoType* mono_metadata_get_shared_type (MonoType *type) { MonoType *cached; /* No need to use locking since nobody is modifying the hash table */ if ((cached = (MonoType *)g_hash_table_lookup (type_cache, type))) return cached; switch (type->type){ case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: if (type == m_class_get_byval_arg (type->data.klass)) return type; if (type == m_class_get_this_arg (type->data.klass)) return type; break; default: break; } return NULL; } static gboolean compare_type_literals (MonoImage *image, int class_type, int type_type, MonoError *error) { error_init (error); /* _byval_arg.type can be zero if we're decoding a type that references a class been loading. * See mcs/test/gtest-440. and #650936. * FIXME This better be moved to the metadata verifier as it can catch more cases. */ if (!class_type) return TRUE; /* NET 1.1 assemblies might encode string and object in a denormalized way. * See #675464. */ if (class_type == type_type) return TRUE; if (type_type == MONO_TYPE_CLASS) { if (class_type == MONO_TYPE_STRING || class_type == MONO_TYPE_OBJECT) return TRUE; //XXX stringify this argument mono_error_set_bad_image (error, image, "Expected reference type but got type kind %d", class_type); return FALSE; } g_assert (type_type == MONO_TYPE_VALUETYPE); switch (class_type) { case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_CLASS: return TRUE; default: //XXX stringify this argument mono_error_set_bad_image (error, image, "Expected value type but got type kind %d", class_type); return FALSE; } } static gboolean verify_var_type_and_container (MonoImage *image, int var_type, MonoGenericContainer *container, MonoError *error) { error_init (error); if (var_type == MONO_TYPE_MVAR) { if (!container->is_method) { //MVAR and a method container mono_error_set_bad_image (error, image, "MVAR parsed in a context without a method container"); return FALSE; } } else { if (!(!container->is_method || //VAR and class container (container->is_method && container->parent))) { //VAR and method container with parent mono_error_set_bad_image (error, image, "VAR parsed in a context without a class container"); return FALSE; } } return TRUE; } /* * do_mono_metadata_parse_type: * @type: MonoType to be filled in with the return value * @m: image context * @generic_context: generics_context * @transient: whenever to allocate data from the heap * @ptr: pointer to the encoded type * @rptr: pointer where the end of the encoded type is saved * * Internal routine used to "fill" the contents of @type from an * allocated pointer. This is done this way to avoid doing too * many mini-allocations (particularly for the MonoFieldType which * most of the time is just a MonoType, but sometimes might be augmented). * * This routine is used by mono_metadata_parse_type and * mono_metadata_parse_field_type * * This extracts a Type as specified in Partition II (22.2.12) * * Returns: FALSE if the type could not be loaded */ static gboolean do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { error_init (error); type->type = (MonoTypeEnum)mono_metadata_decode_value (ptr, &ptr); switch (type->type){ case MONO_TYPE_VOID: case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_TYPEDBYREF: break; case MONO_TYPE_VALUETYPE: case MONO_TYPE_CLASS: { guint32 token; MonoClass *klass; token = mono_metadata_parse_typedef_or_ref (m, ptr, &ptr); klass = mono_class_get_checked (m, token, error); type->data.klass = klass; if (!klass) return FALSE; if (!compare_type_literals (m, m_class_get_byval_arg (klass)->type, type->type, error)) return FALSE; break; } case MONO_TYPE_SZARRAY: { MonoType *etype = mono_metadata_parse_type_checked (m, container, 0, transient, ptr, &ptr, error); if (!etype) return FALSE; type->data.klass = mono_class_from_mono_type_internal (etype); if (transient) mono_metadata_free_type (etype); g_assert (type->data.klass); //This was previously a check for NULL, but mcfmt should never fail. It can return a borken MonoClass, but should return at least something. break; } case MONO_TYPE_PTR: { type->data.type = mono_metadata_parse_type_checked (m, container, 0, transient, ptr, &ptr, error); if (!type->data.type) return FALSE; break; } case MONO_TYPE_FNPTR: { type->data.method = mono_metadata_parse_method_signature_full (m, container, 0, ptr, &ptr, error); if (!type->data.method) return FALSE; break; } case MONO_TYPE_ARRAY: { type->data.array = mono_metadata_parse_array_internal (m, container, transient, ptr, &ptr, error); if (!type->data.array) return FALSE; break; } case MONO_TYPE_MVAR: case MONO_TYPE_VAR: { if (container && !verify_var_type_and_container (m, type->type, container, error)) return FALSE; type->data.generic_param = mono_metadata_parse_generic_param (m, container, type->type, ptr, &ptr, error); if (!type->data.generic_param) return FALSE; break; } case MONO_TYPE_GENERICINST: { if (!do_mono_metadata_parse_generic_class (type, m, container, ptr, &ptr, error)) return FALSE; break; } default: mono_error_set_bad_image (error, m, "type 0x%02x not handled in do_mono_metadata_parse_type on image %s", type->type, m->name); return FALSE; } if (rptr) *rptr = ptr; return TRUE; } /** * mono_metadata_free_type: * \param type type to free * * Free the memory allocated for type \p type which is allocated on the heap. */ void mono_metadata_free_type (MonoType *type) { /* Note: keep in sync with do_mono_metadata_parse_type and try_get_canonical_type which * allocate memory or try to avoid allocating memory. */ if (type >= builtin_types && type < builtin_types + G_N_ELEMENTS (builtin_types)) return; switch (type->type){ case MONO_TYPE_OBJECT: case MONO_TYPE_STRING: if (!type->data.klass) break; /* fall through */ case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: if (type == m_class_get_byval_arg (type->data.klass) || type == m_class_get_this_arg (type->data.klass)) return; break; case MONO_TYPE_PTR: mono_metadata_free_type (type->data.type); break; case MONO_TYPE_FNPTR: mono_metadata_free_method_signature (type->data.method); break; case MONO_TYPE_ARRAY: mono_metadata_free_array (type->data.array); break; default: break; } g_free (type); } #if 0 static void hex_dump (const char *buffer, int base, int count) { int show_header = 1; int i; if (count < 0){ count = -count; show_header = 0; } for (i = 0; i < count; i++){ if (show_header) if ((i % 16) == 0) printf ("\n0x%08x: ", (unsigned char) base + i); printf ("%02x ", (unsigned char) (buffer [i])); } fflush (stdout); } #endif /** * @ptr: Points to the beginning of the Section Data (25.3) */ static MonoExceptionClause* parse_section_data (MonoImage *m, int *num_clauses, const unsigned char *ptr, MonoError *error) { unsigned char sect_data_flags; int is_fat; guint32 sect_data_len; MonoExceptionClause* clauses = NULL; error_init (error); while (1) { /* align on 32-bit boundary */ ptr = dword_align (ptr); sect_data_flags = *ptr; ptr++; is_fat = sect_data_flags & METHOD_HEADER_SECTION_FAT_FORMAT; if (is_fat) { sect_data_len = (ptr [2] << 16) | (ptr [1] << 8) | ptr [0]; ptr += 3; } else { sect_data_len = ptr [0]; ++ptr; } if (sect_data_flags & METHOD_HEADER_SECTION_EHTABLE) { const unsigned char *p = dword_align (ptr); int i; *num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12; /* we could just store a pointer if we don't need to byteswap */ clauses = (MonoExceptionClause *)g_malloc0 (sizeof (MonoExceptionClause) * (*num_clauses)); for (i = 0; i < *num_clauses; ++i) { MonoExceptionClause *ec = &clauses [i]; guint32 tof_value; if (is_fat) { ec->flags = read32 (p); ec->try_offset = read32 (p + 4); ec->try_len = read32 (p + 8); ec->handler_offset = read32 (p + 12); ec->handler_len = read32 (p + 16); tof_value = read32 (p + 20); p += 24; } else { ec->flags = read16 (p); ec->try_offset = read16 (p + 2); ec->try_len = *(p + 4); ec->handler_offset = read16 (p + 5); ec->handler_len = *(p + 7); tof_value = read32 (p + 8); p += 12; } if (ec->flags == MONO_EXCEPTION_CLAUSE_FILTER) { ec->data.filter_offset = tof_value; } else if (ec->flags == MONO_EXCEPTION_CLAUSE_NONE) { ec->data.catch_class = NULL; if (tof_value) { ec->data.catch_class = mono_class_get_checked (m, tof_value, error); if (!is_ok (error)) { g_free (clauses); return NULL; } } } else { ec->data.catch_class = NULL; } /* g_print ("try %d: %x %04x-%04x %04x\n", i, ec->flags, ec->try_offset, ec->try_offset+ec->try_len, ec->try_len); */ } } if (sect_data_flags & METHOD_HEADER_SECTION_MORE_SECTS) ptr += sect_data_len - 4; /* LAMESPEC: it seems the size includes the header */ else return clauses; } } /* * mono_method_get_header_summary: * @method: The method to get the header. * @summary: Where to store the header * * * Returns: TRUE if the header was properly decoded. */ gboolean mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *summary) { int idx; guint32 rva; MonoImage* img; const char *ptr; unsigned char flags, format; guint16 fat_flags; /*Only the GMD has a pointer to the metadata.*/ while (method->is_inflated) method = ((MonoMethodInflated*)method)->declaring; summary->code = NULL; summary->code_size = 0; summary->max_stack = 0; summary->has_clauses = FALSE; summary->has_locals = FALSE; /*FIXME extract this into a MACRO and share it with mono_method_get_header*/ if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) return FALSE; if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) { MonoMethodHeader *header = ((MonoMethodWrapper *)method)->header; if (!header) return FALSE; summary->code = header->code; summary->code_size = header->code_size; summary->max_stack = header->max_stack; summary->has_clauses = header->num_clauses > 0; summary->has_locals = header->num_locals > 0; return TRUE; } idx = mono_metadata_token_index (method->token); img = m_class_get_image (method->klass); rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA); ptr = mono_image_rva_map (img, rva); if (!ptr) return FALSE; flags = *(const unsigned char *)ptr; format = flags & METHOD_HEADER_FORMAT_MASK; switch (format) { case METHOD_HEADER_TINY_FORMAT: ptr++; summary->max_stack = 8; summary->code = (unsigned char *) ptr; summary->code_size = flags >> 2; break; case METHOD_HEADER_FAT_FORMAT: fat_flags = read16 (ptr); ptr += 2; summary->max_stack = read16 (ptr); ptr += 2; summary->code_size = read32 (ptr); ptr += 4; summary->has_locals = !!read32 (ptr); ptr += 4; if (fat_flags & METHOD_HEADER_MORE_SECTS) summary->has_clauses = TRUE; summary->code = (unsigned char *) ptr; break; default: return FALSE; } return TRUE; } /* * mono_metadata_parse_mh_full: * @m: metadata context * @generic_context: generics context * @ptr: pointer to the method header. * * Decode the method header at @ptr, including pointer to the IL code, * info about local variables and optional exception tables. * This is a Mono runtime internal function. * * LOCKING: Acquires the loader lock. * * Returns: a transient MonoMethodHeader allocated from the heap. */ MonoMethodHeader * mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, const char *ptr, MonoError *error) { MonoMethodHeader *mh = NULL; unsigned char flags = *(const unsigned char *) ptr; unsigned char format = flags & METHOD_HEADER_FORMAT_MASK; guint16 fat_flags; guint32 local_var_sig_tok, max_stack, code_size, init_locals; const unsigned char *code; MonoExceptionClause* clauses = NULL; int num_clauses = 0; MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG]; guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE]; error_init (error); if (!ptr) { mono_error_set_bad_image (error, m, "Method header with null pointer"); return NULL; } switch (format) { case METHOD_HEADER_TINY_FORMAT: mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER); ptr++; mh->max_stack = 8; mh->is_transient = TRUE; local_var_sig_tok = 0; mh->code_size = flags >> 2; mh->code = (unsigned char*)ptr; return mh; case METHOD_HEADER_FAT_FORMAT: fat_flags = read16 (ptr); ptr += 2; max_stack = read16 (ptr); ptr += 2; code_size = read32 (ptr); ptr += 4; local_var_sig_tok = read32 (ptr); ptr += 4; if (fat_flags & METHOD_HEADER_INIT_LOCALS) init_locals = 1; else init_locals = 0; code = (unsigned char*)ptr; if (!(fat_flags & METHOD_HEADER_MORE_SECTS)) break; /* * There are more sections */ ptr = (char*)code + code_size; break; default: mono_error_set_bad_image (error, m, "Invalid method header format %d", format); return NULL; } if (local_var_sig_tok) { int idx = mono_metadata_token_index (local_var_sig_tok) - 1; if (mono_metadata_table_bounds_check (m, MONO_TABLE_STANDALONESIG, idx + 1)) { mono_error_set_bad_image (error, m, "Invalid method header local vars signature token 0x%08x", idx); goto fail; } mono_metadata_decode_row (t, idx, cols, MONO_STAND_ALONE_SIGNATURE_SIZE); } if (fat_flags & METHOD_HEADER_MORE_SECTS) { clauses = parse_section_data (m, &num_clauses, (const unsigned char*)ptr, error); goto_if_nok (error, fail); } if (local_var_sig_tok) { const char *locals_ptr; int len=0, i; locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]); mono_metadata_decode_blob_size (locals_ptr, &locals_ptr); if (*locals_ptr != 0x07) g_warning ("wrong signature for locals blob"); locals_ptr++; len = mono_metadata_decode_value (locals_ptr, &locals_ptr); mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + len * sizeof (MonoType*) + num_clauses * sizeof (MonoExceptionClause)); mh->num_locals = len; for (i = 0; i < len; ++i) { mh->locals [i] = mono_metadata_parse_type_internal (m, container, 0, TRUE, locals_ptr, &locals_ptr, error); goto_if_nok (error, fail); } } else { mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + num_clauses * sizeof (MonoExceptionClause)); } mh->code = code; mh->code_size = code_size; mh->max_stack = max_stack; mh->is_transient = TRUE; mh->init_locals = init_locals; if (clauses) { MonoExceptionClause* clausesp = (MonoExceptionClause*)&mh->locals [mh->num_locals]; memcpy (clausesp, clauses, num_clauses * sizeof (MonoExceptionClause)); g_free (clauses); mh->clauses = clausesp; mh->num_clauses = num_clauses; } return mh; fail: g_free (clauses); g_free (mh); return NULL; } /** * mono_metadata_parse_mh: * \param generic_context generics context * \param ptr pointer to the method header. * * Decode the method header at \p ptr, including pointer to the IL code, * info about local variables and optional exception tables. * * \returns a transient \c MonoMethodHeader allocated from the heap. */ MonoMethodHeader * mono_metadata_parse_mh (MonoImage *m, const char *ptr) { ERROR_DECL (error); MonoMethodHeader *header = mono_metadata_parse_mh_full (m, NULL, ptr, error); mono_error_cleanup (error); return header; } /** * mono_metadata_free_mh: * \param mh a method header * * Free the memory allocated for the method header. */ void mono_metadata_free_mh (MonoMethodHeader *mh) { int i; /* If it is not transient it means it's part of a wrapper method, * or a SRE-generated method, so the lifetime in that case is * dictated by the method's own lifetime */ if (mh && mh->is_transient) { for (i = 0; i < mh->num_locals; ++i) mono_metadata_free_type (mh->locals [i]); g_free (mh); } } /** * mono_method_header_get_code: * \param header a \c MonoMethodHeader pointer * \param code_size memory location for returning the code size * \param max_stack memory location for returning the max stack * * Method header accessor to retreive info about the IL code properties: * a pointer to the IL code itself, the size of the code and the max number * of stack slots used by the code. * * \returns pointer to the IL code represented by the method header. */ const unsigned char* mono_method_header_get_code (MonoMethodHeader *header, guint32* code_size, guint32* max_stack) { if (code_size) *code_size = header->code_size; if (max_stack) *max_stack = header->max_stack; return header->code; } /** * mono_method_header_get_locals: * \param header a \c MonoMethodHeader pointer * \param num_locals memory location for returning the number of local variables * \param init_locals memory location for returning the init_locals flag * * Method header accessor to retreive info about the local variables: * an array of local types, the number of locals and whether the locals * are supposed to be initialized to 0 on method entry * * \returns pointer to an array of types of the local variables */ MonoType** mono_method_header_get_locals (MonoMethodHeader *header, guint32* num_locals, gboolean *init_locals) { if (num_locals) *num_locals = header->num_locals; if (init_locals) *init_locals = header->init_locals; return header->locals; } /* * mono_method_header_get_num_clauses: * @header: a MonoMethodHeader pointer * * Method header accessor to retreive the number of exception clauses. * * Returns: the number of exception clauses present */ int mono_method_header_get_num_clauses (MonoMethodHeader *header) { return header->num_clauses; } /** * mono_method_header_get_clauses: * \param header a \c MonoMethodHeader pointer * \param method \c MonoMethod the header belongs to * \param iter pointer to a iterator * \param clause pointer to a \c MonoExceptionClause structure which will be filled with the info * * Get the info about the exception clauses in the method. Set \c *iter to NULL to * initiate the iteration, then call the method repeatedly until it returns FALSE. * At each iteration, the structure pointed to by clause if filled with the * exception clause information. * * \returns TRUE if clause was filled with info, FALSE if there are no more exception * clauses. */ int mono_method_header_get_clauses (MonoMethodHeader *header, MonoMethod *method, gpointer *iter, MonoExceptionClause *clause) { MonoExceptionClause *sc; /* later we'll be able to use this interface to parse the clause info on demand, * without allocating anything. */ if (!iter || !header->num_clauses) return FALSE; if (!*iter) { *iter = sc = header->clauses; *clause = *sc; return TRUE; } sc = (MonoExceptionClause *)*iter; sc++; if (sc < header->clauses + header->num_clauses) { *iter = sc; *clause = *sc; return TRUE; } return FALSE; } /** * mono_metadata_parse_field_type: * \param m metadata context to extract information from * \param ptr pointer to the field signature * \param rptr pointer updated to match the end of the decoded stream * * Parses the field signature, and returns the type information for it. * * \returns The \c MonoType that was extracted from \p ptr . */ MonoType * mono_metadata_parse_field_type (MonoImage *m, short field_flags, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoType * type = mono_metadata_parse_type_internal (m, NULL, field_flags, FALSE, ptr, rptr, error); mono_error_cleanup (error); return type; } /** * mono_metadata_parse_param: * \param m metadata context to extract information from * \param ptr pointer to the param signature * \param rptr pointer updated to match the end of the decoded stream * * Parses the param signature, and returns the type information for it. * * \returns The \c MonoType that was extracted from \p ptr . */ MonoType * mono_metadata_parse_param (MonoImage *m, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoType * type = mono_metadata_parse_type_internal (m, NULL, 0, FALSE, ptr, rptr, error); mono_error_cleanup (error); return type; } /** * mono_metadata_token_from_dor: * \param dor_token A \c TypeDefOrRef coded index * * \p dor_token is a \c TypeDefOrRef coded index: it contains either * a \c TypeDef, \c TypeRef or \c TypeSpec in the lower bits, and the upper * bits contain an index into the table. * * \returns an expanded token */ guint32 mono_metadata_token_from_dor (guint32 dor_index) { guint32 table, idx; table = dor_index & 0x03; idx = dor_index >> 2; switch (table){ case 0: /* TypeDef */ return MONO_TOKEN_TYPE_DEF | idx; case 1: /* TypeRef */ return MONO_TOKEN_TYPE_REF | idx; case 2: /* TypeSpec */ return MONO_TOKEN_TYPE_SPEC | idx; default: g_assert_not_reached (); } return 0; } /* * We use this to pass context information to the row locator */ typedef struct { int idx; /* The index that we are trying to locate */ int col_idx; /* The index in the row where idx may be stored */ MonoTableInfo *t; /* pointer to the table */ guint32 result; } locator_t; /* * How the row locator works. * * Table A * ___|___ * ___|___ Table B * ___|___------> _______ * ___|___ _______ * * A column in the rows of table A references an index in table B. * For example A may be the TYPEDEF table and B the METHODDEF table. * * Given an index in table B we want to get the row in table A * where the column n references our index in B. * * In the locator_t structure: * t is table A * col_idx is the column number * index is the index in table B * result will be the index in table A * * Examples: * Table A Table B column (in table A) * TYPEDEF METHODDEF MONO_TYPEDEF_METHOD_LIST * TYPEDEF FIELD MONO_TYPEDEF_FIELD_LIST * PROPERTYMAP PROPERTY MONO_PROPERTY_MAP_PROPERTY_LIST * INTERFIMPL TYPEDEF MONO_INTERFACEIMPL_CLASS * METHODSEM PROPERTY ASSOCIATION (encoded index) * * Note that we still don't support encoded indexes. * */ static int typedef_locator (const void *a, const void *b) { locator_t *loc = (locator_t *) a; const char *bb = (const char *) b; int typedef_index = (bb - loc->t->base) / loc->t->row_size; guint32 col, col_next; col = mono_metadata_decode_row_col (loc->t, typedef_index, loc->col_idx); if (loc->idx < col) return -1; /* * Need to check that the next row is valid. */ if (typedef_index + 1 < table_info_get_rows (loc->t)) { col_next = mono_metadata_decode_row_col (loc->t, typedef_index + 1, loc->col_idx); if (loc->idx >= col_next) return 1; if (col == col_next) return 1; } loc->result = typedef_index; return 0; } static int table_locator (const void *a, const void *b) { locator_t *loc = (locator_t *) a; const char *bb = (const char *) b; guint32 table_index = (bb - loc->t->base) / loc->t->row_size; guint32 col; col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx); if (loc->idx == col) { loc->result = table_index; return 0; } if (loc->idx < col) return -1; else return 1; } static int declsec_locator (const void *a, const void *b) { locator_t *loc = (locator_t *) a; const char *bb = (const char *) b; guint32 table_index = (bb - loc->t->base) / loc->t->row_size; guint32 col; col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx); if (loc->idx == col) { loc->result = table_index; return 0; } if (loc->idx < col) return -1; else return 1; } /** * search_ptr_table: * * Return the 1-based row index in TABLE, which must be one of the *Ptr tables, * which contains IDX. */ static guint32 search_ptr_table (MonoImage *image, int table, int idx) { MonoTableInfo *ptrdef = &image->tables [table]; int rows = table_info_get_rows (ptrdef); int i; /* Use a linear search to find our index in the table */ for (i = 0; i < rows; i ++) /* All the Ptr tables have the same structure */ if (mono_metadata_decode_row_col (ptrdef, i, 0) == idx) break; if (i < rows) return i + 1; else return idx; } /** * mono_metadata_typedef_from_field: * \param meta metadata context * \param index FieldDef token * * \returns the 1-based index into the \c TypeDef table of the type that * declared the field described by \p index, or 0 if not found. */ guint32 mono_metadata_typedef_from_field (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF]; locator_t loc; if (!tdef->base) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_TYPEDEF_FIELD_LIST; loc.t = tdef; if (meta->uncompressed_metadata) loc.idx = search_ptr_table (meta, MONO_TABLE_FIELD_POINTER, loc.idx); /* if it's not in the base image, look in the hot reload table */ gboolean added = (loc.idx > table_info_get_rows (&meta->tables [MONO_TABLE_FIELD])); if (added) { uint32_t res = mono_component_hot_reload()->field_parent (meta, loc.idx); return res; /* 0 if not found, otherwise 1-based */ } if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, typedef_locator)) return 0; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_typedef_from_method: * \param meta metadata context * \param index \c MethodDef token * \returns the 1-based index into the \c TypeDef table of the type that * declared the method described by \p index. 0 if not found. */ guint32 mono_metadata_typedef_from_method (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF]; locator_t loc; if (!tdef->base) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_TYPEDEF_METHOD_LIST; loc.t = tdef; if (meta->uncompressed_metadata) loc.idx = search_ptr_table (meta, MONO_TABLE_METHOD_POINTER, loc.idx); /* if it's not in the base image, look in the hot reload table */ gboolean added = (loc.idx > table_info_get_rows (&meta->tables [MONO_TABLE_METHOD])); if (added) { uint32_t res = mono_component_hot_reload ()->method_parent (meta, loc.idx); return res; /* 0 if not found, otherwise 1-based */ } if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, typedef_locator)) return 0; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_interfaces_from_typedef_full: * \param meta metadata context * \param index typedef token * \param interfaces Out parameter used to store the interface array * \param count Out parameter used to store the number of interfaces * \param heap_alloc_result if TRUE the result array will be \c g_malloc'd * \param context The generic context * \param error set on error * * The array of interfaces that the \p index typedef token implements is returned in * \p interfaces. The number of elements in the array is returned in \p count. * * \returns \c TRUE on success, \c FALSE on failure and sets \p error. */ gboolean mono_metadata_interfaces_from_typedef_full (MonoImage *meta, guint32 index, MonoClass ***interfaces, guint *count, gboolean heap_alloc_result, MonoGenericContext *context, MonoError *error) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_INTERFACEIMPL]; locator_t loc; guint32 start, pos; guint32 cols [MONO_INTERFACEIMPL_SIZE]; MonoClass **result; *interfaces = NULL; *count = 0; error_init (error); if (!tdef->base) return TRUE; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_INTERFACEIMPL_CLASS; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return TRUE; start = loc.result; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_INTERFACEIMPL_CLASS)) start--; else break; } pos = start; int rows = table_info_get_rows (tdef); while (pos < rows) { mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE); if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx) break; ++pos; } if (heap_alloc_result) result = g_new0 (MonoClass*, pos - start); else result = (MonoClass **)mono_image_alloc0 (meta, sizeof (MonoClass*) * (pos - start)); pos = start; while (pos < rows) { MonoClass *iface; mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE); if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx) break; iface = mono_class_get_and_inflate_typespec_checked ( meta, mono_metadata_token_from_dor (cols [MONO_INTERFACEIMPL_INTERFACE]), context, error); if (iface == NULL) return FALSE; result [pos - start] = iface; ++pos; } *count = pos - start; *interfaces = result; return TRUE; } /** * mono_metadata_interfaces_from_typedef: * \param meta metadata context * \param index typedef token * \param count Out parameter used to store the number of interfaces * * The array of interfaces that the \p index typedef token implements is returned in * \p interfaces. The number of elements in the array is returned in \p count. The returned * array is allocated with \c g_malloc and the caller must free it. * * LOCKING: Acquires the loader lock . * * \returns the interface array on success, NULL on failure. */ MonoClass** mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *count) { ERROR_DECL (error); MonoClass **interfaces = NULL; gboolean rv; rv = mono_metadata_interfaces_from_typedef_full (meta, index, &interfaces, count, TRUE, NULL, error); mono_error_assert_ok (error); if (rv) return interfaces; else return NULL; } /** * mono_metadata_nested_in_typedef: * \param meta metadata context * \param index typedef token * \returns the 1-based index into the TypeDef table of the type * where the type described by \p index is nested. * Returns 0 if \p index describes a non-nested type. */ guint32 mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS]; locator_t loc; if (!tdef->base && !meta->has_updates) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_NESTED_CLASS_NESTED; loc.t = tdef; gboolean found = tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator) != NULL; if (!found && !meta->has_updates) return 0; if (G_UNLIKELY (meta->has_updates)) { if (!found && !mono_metadata_update_metadata_linear_search (meta, tdef, &loc, table_locator)) return 0; } /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF; } /** * mono_metadata_nesting_typedef: * \param meta metadata context * \param index typedef token * \returns the 1-based index into the \c TypeDef table of the first type * that is nested inside the type described by \p index. The search starts at * \p start_index. Returns 0 if no such type is found. */ guint32 mono_metadata_nesting_typedef (MonoImage *meta, guint32 index, guint32 start_index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS]; guint32 start; guint32 class_index = mono_metadata_token_index (index); if (!tdef->base) return 0; start = start_index; /* FIXME: metadata-udpate */ int rows = table_info_get_rows (tdef); while (start <= rows) { if (class_index == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING)) break; else start++; } if (start > rows) return 0; else return start; } /** * mono_metadata_packing_from_typedef: * \param meta metadata context * \param index token representing a type * \returns the info stored in the \c ClassLayout table for the given typedef token * into the \p packing and \p size pointers. * Returns 0 if the info is not found. */ guint32 mono_metadata_packing_from_typedef (MonoImage *meta, guint32 index, guint32 *packing, guint32 *size) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CLASSLAYOUT]; locator_t loc; guint32 cols [MONO_CLASS_LAYOUT_SIZE]; if (!tdef->base) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_CLASS_LAYOUT_PARENT; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; mono_metadata_decode_row (tdef, loc.result, cols, MONO_CLASS_LAYOUT_SIZE); if (packing) *packing = cols [MONO_CLASS_LAYOUT_PACKING_SIZE]; if (size) *size = cols [MONO_CLASS_LAYOUT_CLASS_SIZE]; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_custom_attrs_from_index: * \param meta metadata context * \param index token representing the parent * \returns: the 1-based index into the \c CustomAttribute table of the first * attribute which belongs to the metadata object described by \p index. * Returns 0 if no such attribute is found. */ guint32 mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE]; locator_t loc; if (!tdef->base && !meta->has_updates) return 0; loc.idx = index; loc.col_idx = MONO_CUSTOM_ATTR_PARENT; loc.t = tdef; /* FIXME: Index translation */ gboolean found = tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator) != NULL; if (!found && !meta->has_updates) return 0; if (G_UNLIKELY (meta->has_updates)) { if (!found && !mono_metadata_update_metadata_linear_search (meta, tdef, &loc, table_locator)) return 0; } /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index)) loc.result --; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_declsec_from_index: * \param meta metadata context * \param index token representing the parent * \returns the 0-based index into the \c DeclarativeSecurity table of the first * attribute which belongs to the metadata object described by \p index. * Returns \c -1 if no such attribute is found. */ guint32 mono_metadata_declsec_from_index (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_DECLSECURITY]; locator_t loc; if (!tdef->base) return -1; loc.idx = index; loc.col_idx = MONO_DECL_SECURITY_PARENT; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, declsec_locator)) return -1; /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_DECL_SECURITY_PARENT) == index)) loc.result --; return loc.result; } /* * mono_metadata_localscope_from_methoddef: * @meta: metadata context * @index: methoddef index * * Returns: the 1-based index into the LocalScope table of the first * scope which belongs to the method described by @index. * Returns 0 if no such row is found. */ guint32 mono_metadata_localscope_from_methoddef (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_LOCALSCOPE]; locator_t loc; if (!tdef->base) return 0; loc.idx = index; loc.col_idx = MONO_LOCALSCOPE_METHOD; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_LOCALSCOPE_METHOD) == index)) loc.result --; return loc.result + 1; } #ifdef DEBUG static void mono_backtrace (int limit) { void *array[limit]; char **names; int i; backtrace (array, limit); names = backtrace_symbols (array, limit); for (i =0; i < limit; ++i) { g_print ("\t%s\n", names [i]); } g_free (names); } #endif static int i8_align; /* * mono_type_set_alignment: * * Set the alignment used by runtime to layout fields etc. of type TYPE to ALIGN. * This should only be used in AOT mode since the resulting layout will not match the * host abi layout. */ void mono_type_set_alignment (MonoTypeEnum type, int align) { /* Support only a few types whose alignment is abi dependent */ switch (type) { case MONO_TYPE_I8: i8_align = align; break; default: g_assert_not_reached (); break; } } /** * mono_type_size: * \param t the type to return the size of * \returns The number of bytes required to hold an instance of this * type in memory */ int mono_type_size (MonoType *t, int *align) { MonoTypeEnum simple_type; if (!t) { *align = 1; return 0; } if (m_type_is_byref (t)) { *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); } simple_type = t->type; again: switch (simple_type) { case MONO_TYPE_VOID: *align = 1; return 0; case MONO_TYPE_BOOLEAN: *align = MONO_ABI_ALIGNOF (gint8); return 1; case MONO_TYPE_I1: case MONO_TYPE_U1: *align = MONO_ABI_ALIGNOF (gint8); return 1; case MONO_TYPE_CHAR: case MONO_TYPE_I2: case MONO_TYPE_U2: *align = MONO_ABI_ALIGNOF (gint16); return 2; case MONO_TYPE_I4: case MONO_TYPE_U4: *align = MONO_ABI_ALIGNOF (gint32); return 4; case MONO_TYPE_R4: *align = MONO_ABI_ALIGNOF (float); return 4; case MONO_TYPE_I8: case MONO_TYPE_U8: *align = MONO_ABI_ALIGNOF (gint64); return 8; case MONO_TYPE_R8: *align = MONO_ABI_ALIGNOF (double); return 8; case MONO_TYPE_I: case MONO_TYPE_U: *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); case MONO_TYPE_VALUETYPE: { if (m_class_is_enumtype (t->data.klass)) return mono_type_size (mono_class_enum_basetype_internal (t->data.klass), align); else return mono_class_value_size (t->data.klass, (guint32*)align); } case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_ARRAY: *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); case MONO_TYPE_TYPEDBYREF: return mono_class_value_size (mono_defaults.typed_reference_class, (guint32*)align); case MONO_TYPE_GENERICINST: { MonoGenericClass *gclass = t->data.generic_class; MonoClass *container_class = gclass->container_class; // g_assert (!gclass->inst->is_open); if (m_class_is_valuetype (container_class)) { if (m_class_is_enumtype (container_class)) return mono_type_size (mono_class_enum_basetype_internal (container_class), align); else return mono_class_value_size (mono_class_from_mono_type_internal (t), (guint32*)align); } else { *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); } } case MONO_TYPE_VAR: case MONO_TYPE_MVAR: if (!t->data.generic_param->gshared_constraint || t->data.generic_param->gshared_constraint->type == MONO_TYPE_VALUETYPE) { *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); } else { /* The gparam can only match types given by gshared_constraint */ return mono_type_size (t->data.generic_param->gshared_constraint, align); goto again; } default: g_error ("mono_type_size: type 0x%02x unknown", t->type); } return 0; } /** * mono_type_stack_size: * \param t the type to return the size it uses on the stack * \returns The number of bytes required to hold an instance of this * type on the runtime stack */ int mono_type_stack_size (MonoType *t, int *align) { return mono_type_stack_size_internal (t, align, FALSE); } int mono_type_stack_size_internal (MonoType *t, int *align, gboolean allow_open) { int tmp; MonoTypeEnum simple_type; int stack_slot_size = TARGET_SIZEOF_VOID_P; int stack_slot_align = TARGET_SIZEOF_VOID_P; g_assert (t != NULL); if (!align) align = &tmp; if (m_type_is_byref (t)) { *align = stack_slot_align; return stack_slot_size; } simple_type = t->type; switch (simple_type) { case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_ARRAY: *align = stack_slot_align; return stack_slot_size; case MONO_TYPE_VAR: case MONO_TYPE_MVAR: g_assert (allow_open); if (!t->data.generic_param->gshared_constraint || t->data.generic_param->gshared_constraint->type == MONO_TYPE_VALUETYPE) { *align = stack_slot_align; return stack_slot_size; } else { /* The gparam can only match types given by gshared_constraint */ return mono_type_stack_size_internal (t->data.generic_param->gshared_constraint, align, allow_open); } case MONO_TYPE_TYPEDBYREF: *align = stack_slot_align; return stack_slot_size * 3; case MONO_TYPE_R4: *align = MONO_ABI_ALIGNOF (float); return sizeof (float); case MONO_TYPE_I8: case MONO_TYPE_U8: *align = MONO_ABI_ALIGNOF (gint64); return sizeof (gint64); case MONO_TYPE_R8: *align = MONO_ABI_ALIGNOF (double); return sizeof (double); case MONO_TYPE_VALUETYPE: { guint32 size; if (m_class_is_enumtype (t->data.klass)) return mono_type_stack_size_internal (mono_class_enum_basetype_internal (t->data.klass), align, allow_open); else { size = mono_class_value_size (t->data.klass, (guint32*)align); *align = *align + stack_slot_align - 1; *align &= ~(stack_slot_align - 1); size += stack_slot_size - 1; size &= ~(stack_slot_size - 1); return size; } } case MONO_TYPE_GENERICINST: { MonoGenericClass *gclass = t->data.generic_class; MonoClass *container_class = gclass->container_class; if (!allow_open) g_assert (!gclass->context.class_inst->is_open); if (m_class_is_valuetype (container_class)) { if (m_class_is_enumtype (container_class)) return mono_type_stack_size_internal (mono_class_enum_basetype_internal (container_class), align, allow_open); else { guint32 size = mono_class_value_size (mono_class_from_mono_type_internal (t), (guint32*)align); *align = *align + stack_slot_align - 1; *align &= ~(stack_slot_align - 1); size += stack_slot_size - 1; size &= ~(stack_slot_size - 1); return size; } } else { *align = stack_slot_align; return stack_slot_size; } } default: g_error ("type 0x%02x unknown", t->type); } return 0; } gboolean mono_type_generic_inst_is_valuetype (MonoType *type) { g_assert (type->type == MONO_TYPE_GENERICINST); return m_class_is_valuetype (type->data.generic_class->container_class); } /** * mono_metadata_generic_class_is_valuetype: */ gboolean mono_metadata_generic_class_is_valuetype (MonoGenericClass *gclass) { return m_class_is_valuetype (gclass->container_class); } static gboolean _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only) { MonoGenericInst *i1 = g1->context.class_inst; MonoGenericInst *i2 = g2->context.class_inst; if (g1->is_dynamic != g2->is_dynamic) return FALSE; if (!mono_metadata_class_equal (g1->container_class, g2->container_class, signature_only)) return FALSE; if (!mono_generic_inst_equal_full (i1, i2, signature_only)) return FALSE; return g1->is_tb_open == g2->is_tb_open; } static gboolean _mono_metadata_generic_class_container_equal (const MonoGenericClass *g1, MonoClass *c2, gboolean signature_only) { MonoGenericInst *i1 = g1->context.class_inst; MonoGenericInst *i2 = mono_class_get_generic_container (c2)->context.class_inst; if (!mono_metadata_class_equal (g1->container_class, c2, signature_only)) return FALSE; if (!mono_generic_inst_equal_full (i1, i2, signature_only)) return FALSE; return !g1->is_tb_open; } guint mono_metadata_generic_context_hash (const MonoGenericContext *context) { /* FIXME: check if this seed is good enough */ guint hash = 0xc01dfee7; if (context->class_inst) hash = ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (context->class_inst); if (context->method_inst) hash = ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (context->method_inst); return hash; } gboolean mono_metadata_generic_context_equal (const MonoGenericContext *g1, const MonoGenericContext *g2) { return g1->class_inst == g2->class_inst && g1->method_inst == g2->method_inst; } /* * mono_metadata_str_hash: * * This should be used instead of g_str_hash for computing hash codes visible * outside this module, since g_str_hash () is not guaranteed to be stable * (its not the same in eglib for example). */ guint mono_metadata_str_hash (gconstpointer v1) { /* Same as g_str_hash () in glib */ char *p = (char *) v1; guint hash = *p; while (*p++) { if (*p) hash = (hash << 5) - hash + *p; } return hash; } /** * mono_metadata_type_hash: * \param t1 a type * Computes a hash value for \p t1 to be used in \c GHashTable. * The returned hash is guaranteed to be the same across executions. */ guint mono_metadata_type_hash (MonoType *t1) { guint hash = t1->type; hash |= (m_type_is_byref (t1) ? 1 : 0) << 6; /* do not collide with t1->type values */ switch (t1->type) { case MONO_TYPE_VALUETYPE: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: { MonoClass *klass = t1->data.klass; /* * Dynamic classes must not be hashed on their type since it can change * during runtime. For example, if we hash a reference type that is * later made into a valuetype. * * This is specially problematic with generic instances since they are * inserted in a bunch of hash tables before been finished. */ if (image_is_dynamic (m_class_get_image (klass))) return ((m_type_is_byref (t1) ? 1 : 0) << 6) | mono_metadata_str_hash (m_class_get_name (klass)); return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (klass)); } case MONO_TYPE_PTR: return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type); case MONO_TYPE_ARRAY: return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass)); case MONO_TYPE_GENERICINST: return ((hash << 5) - hash) ^ mono_generic_class_hash (t1->data.generic_class); case MONO_TYPE_VAR: case MONO_TYPE_MVAR: return ((hash << 5) - hash) ^ mono_metadata_generic_param_hash (t1->data.generic_param); default: return hash; } } guint mono_metadata_generic_param_hash (MonoGenericParam *p) { guint hash; MonoGenericParamInfo *info; hash = (mono_generic_param_num (p) << 2); if (p->gshared_constraint) hash = ((hash << 5) - hash) ^ mono_metadata_type_hash (p->gshared_constraint); info = mono_generic_param_info (p); /* Can't hash on the owner klass/method, since those might not be set when this is called */ if (!p->owner->is_anonymous) hash = ((hash << 5) - hash) ^ info->token; return hash; } static gboolean mono_metadata_generic_param_equal_internal (MonoGenericParam *p1, MonoGenericParam *p2, gboolean signature_only) { if (p1 == p2) return TRUE; if (mono_generic_param_num (p1) != mono_generic_param_num (p2)) return FALSE; if (p1->gshared_constraint && p2->gshared_constraint) { if (!mono_metadata_type_equal (p1->gshared_constraint, p2->gshared_constraint)) return FALSE; } else { if (p1->gshared_constraint != p2->gshared_constraint) return FALSE; } /* * We have to compare the image as well because if we didn't, * the generic_inst_cache lookup wouldn't care about the image * of generic params, so what could happen is that a generic * inst with params from image A is put into the cache, then * image B gets that generic inst from the cache, image A is * unloaded, so the inst is deleted, but image B still retains * a pointer to it. */ if (mono_generic_param_owner (p1) == mono_generic_param_owner (p2)) return TRUE; /* * If `signature_only' is true, we're comparing two (method) signatures. * In this case, the owner of two type parameters doesn't need to match. */ return signature_only; } gboolean mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2) { return mono_metadata_generic_param_equal_internal (p1, p2, TRUE); } static gboolean mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only) { if (c1 == c2) return TRUE; if (mono_class_is_ginst (c1) && mono_class_is_ginst (c2)) return _mono_metadata_generic_class_equal (mono_class_get_generic_class (c1), mono_class_get_generic_class (c2), signature_only); if (mono_class_is_ginst (c1) && mono_class_is_gtd (c2)) return _mono_metadata_generic_class_container_equal (mono_class_get_generic_class (c1), c2, signature_only); if (mono_class_is_gtd (c1) && mono_class_is_ginst (c2)) return _mono_metadata_generic_class_container_equal (mono_class_get_generic_class (c2), c1, signature_only); MonoType *c1_type = m_class_get_byval_arg (c1); MonoType *c2_type = m_class_get_byval_arg (c2); if ((c1_type->type == MONO_TYPE_VAR) && (c2_type->type == MONO_TYPE_VAR)) return mono_metadata_generic_param_equal_internal ( c1_type->data.generic_param, c2_type->data.generic_param, signature_only); if ((c1_type->type == MONO_TYPE_MVAR) && (c2_type->type == MONO_TYPE_MVAR)) return mono_metadata_generic_param_equal_internal ( c1_type->data.generic_param, c2_type->data.generic_param, signature_only); if (signature_only && (c1_type->type == MONO_TYPE_SZARRAY) && (c2_type->type == MONO_TYPE_SZARRAY)) return mono_metadata_class_equal (c1_type->data.klass, c2_type->data.klass, signature_only); if (signature_only && (c1_type->type == MONO_TYPE_ARRAY) && (c2_type->type == MONO_TYPE_ARRAY)) return do_mono_metadata_type_equal (c1_type, c2_type, signature_only); return FALSE; } static gboolean mono_metadata_fnptr_equal (MonoMethodSignature *s1, MonoMethodSignature *s2, gboolean signature_only) { gpointer iter1 = 0, iter2 = 0; if (s1 == s2) return TRUE; if (s1->call_convention != s2->call_convention) return FALSE; if (s1->sentinelpos != s2->sentinelpos) return FALSE; if (s1->hasthis != s2->hasthis) return FALSE; if (s1->explicit_this != s2->explicit_this) return FALSE; if (! do_mono_metadata_type_equal (s1->ret, s2->ret, signature_only)) return FALSE; if (s1->param_count != s2->param_count) return FALSE; while (TRUE) { MonoType *t1 = mono_signature_get_params_internal (s1, &iter1); MonoType *t2 = mono_signature_get_params_internal (s2, &iter2); if (t1 == NULL || t2 == NULL) return (t1 == t2); if (! do_mono_metadata_type_equal (t1, t2, signature_only)) return FALSE; } } static gboolean mono_metadata_custom_modifiers_equal (MonoType *t1, MonoType *t2, gboolean signature_only) { // ECMA 335, 7.1.1: // The CLI itself shall treat required and optional modifiers in the same manner. // Two signatures that differ only by the addition of a custom modifier // (required or optional) shall not be considered to match. int count = mono_type_custom_modifier_count (t1); if (count != mono_type_custom_modifier_count (t2)) return FALSE; for (int i=0; i < count; i++) { // FIXME: propagate error to caller ERROR_DECL (error); gboolean cm1_required, cm2_required; MonoType *cm1_type = mono_type_get_custom_modifier (t1, i, &cm1_required, error); mono_error_assert_ok (error); MonoType *cm2_type = mono_type_get_custom_modifier (t2, i, &cm2_required, error); mono_error_assert_ok (error); if (cm1_required != cm2_required) return FALSE; if (!do_mono_metadata_type_equal (cm1_type, cm2_type, signature_only)) return FALSE; } return TRUE; } /* * mono_metadata_type_equal: * @t1: a type * @t2: another type * @signature_only: If true, treat ginsts as equal which are instantiated separately but have equal positional value * * Determine if @t1 and @t2 represent the same type. * Returns: #TRUE if @t1 and @t2 are equal. */ static gboolean do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only) { if (t1->type != t2->type || m_type_is_byref (t1) != m_type_is_byref (t2)) return FALSE; gboolean cmod_reject = FALSE; if (t1->has_cmods != t2->has_cmods) cmod_reject = TRUE; else if (t1->has_cmods && t2->has_cmods) { cmod_reject = !mono_metadata_custom_modifiers_equal (t1, t2, signature_only); } gboolean result = FALSE; switch (t1->type) { case MONO_TYPE_VOID: case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_STRING: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_OBJECT: case MONO_TYPE_TYPEDBYREF: result = TRUE; break; case MONO_TYPE_VALUETYPE: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: result = mono_metadata_class_equal (t1->data.klass, t2->data.klass, signature_only); break; case MONO_TYPE_PTR: result = do_mono_metadata_type_equal (t1->data.type, t2->data.type, signature_only); break; case MONO_TYPE_ARRAY: if (t1->data.array->rank != t2->data.array->rank) result = FALSE; else result = mono_metadata_class_equal (t1->data.array->eklass, t2->data.array->eklass, signature_only); break; case MONO_TYPE_GENERICINST: result = _mono_metadata_generic_class_equal ( t1->data.generic_class, t2->data.generic_class, signature_only); break; case MONO_TYPE_VAR: result = mono_metadata_generic_param_equal_internal ( t1->data.generic_param, t2->data.generic_param, signature_only); break; case MONO_TYPE_MVAR: result = mono_metadata_generic_param_equal_internal ( t1->data.generic_param, t2->data.generic_param, signature_only); break; case MONO_TYPE_FNPTR: result = mono_metadata_fnptr_equal (t1->data.method, t2->data.method, signature_only); break; default: g_error ("implement type compare for %0x!", t1->type); return FALSE; } return result && !cmod_reject; } /** * mono_metadata_type_equal: */ gboolean mono_metadata_type_equal (MonoType *t1, MonoType *t2) { return do_mono_metadata_type_equal (t1, t2, FALSE); } /** * mono_metadata_type_equal_full: * \param t1 a type * \param t2 another type * \param signature_only if signature only comparison should be made * * Determine if \p t1 and \p t2 are signature compatible if \p signature_only is TRUE, otherwise * behaves the same way as mono_metadata_type_equal. * The function mono_metadata_type_equal(a, b) is just a shortcut for mono_metadata_type_equal_full(a, b, FALSE). * \returns TRUE if \p t1 and \p t2 are equal taking \p signature_only into account. */ gboolean mono_metadata_type_equal_full (MonoType *t1, MonoType *t2, gboolean signature_only) { return do_mono_metadata_type_equal (t1, t2, signature_only); } enum { SIG_EQUIV_FLAG_NO_RET = 1, }; gboolean signature_equiv (MonoMethodSignature *sig1, MonoMethodSignature *sig2, int flags); /** * mono_metadata_signature_equal: * \param sig1 a signature * \param sig2 another signature * * Determine if \p sig1 and \p sig2 represent the same signature, with the * same number of arguments and the same types. * \returns TRUE if \p sig1 and \p sig2 are equal. */ gboolean mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2) { return signature_equiv (sig1, sig2, 0); } gboolean mono_metadata_signature_equal_no_ret (MonoMethodSignature *sig1, MonoMethodSignature *sig2) { return signature_equiv (sig1, sig2, SIG_EQUIV_FLAG_NO_RET); } gboolean signature_equiv (MonoMethodSignature *sig1, MonoMethodSignature *sig2, int equiv_flags) { int i; if (sig1->hasthis != sig2->hasthis || sig1->param_count != sig2->param_count) return FALSE; if (sig1->generic_param_count != sig2->generic_param_count) return FALSE; /* * We're just comparing the signatures of two methods here: * * If we have two generic methods `void Foo<U> (U u)' and `void Bar<V> (V v)', * U and V are equal here. * * That's what the `signature_only' argument of do_mono_metadata_type_equal() is for. */ for (i = 0; i < sig1->param_count; i++) { MonoType *p1 = sig1->params[i]; MonoType *p2 = sig2->params[i]; /* if (p1->attrs != p2->attrs) return FALSE; */ if (!do_mono_metadata_type_equal (p1, p2, TRUE)) return FALSE; } if ((equiv_flags & SIG_EQUIV_FLAG_NO_RET) != 0) return TRUE; if (!do_mono_metadata_type_equal (sig1->ret, sig2->ret, TRUE)) return FALSE; return TRUE; } MonoType * mono_type_get_custom_modifier (const MonoType *ty, uint8_t idx, gboolean *required, MonoError *error) { g_assert (ty->has_cmods); if (mono_type_is_aggregate_mods (ty)) { MonoAggregateModContainer *amods = mono_type_get_amods (ty); g_assert (idx < amods->count); MonoSingleCustomMod *cmod = &amods->modifiers [idx]; if (required) *required = !!cmod->required; return cmod->type; } else { MonoCustomModContainer *cmods = mono_type_get_cmods (ty); g_assert (idx < cmods->count); MonoCustomMod *cmod = &cmods->modifiers [idx]; if (required) *required = !!cmod->required; MonoImage *image = cmods->image; uint32_t token = cmod->token; return mono_type_get_checked (image, token, NULL, error); } } /** * mono_metadata_type_dup: * \param image image to alloc memory from * \param original type to duplicate * \returns copy of type allocated from the image's mempool (or from the heap, if \p image is null). */ MonoType * mono_metadata_type_dup (MonoImage *image, const MonoType *o) { return mono_metadata_type_dup_with_cmods (image, o, o); } static void deep_type_dup_fixup (MonoImage *image, MonoType *r, const MonoType *o); static uint8_t custom_modifier_copy (MonoAggregateModContainer *dest, uint8_t dest_offset, const MonoType *source) { if (mono_type_is_aggregate_mods (source)) { MonoAggregateModContainer *src_cmods = mono_type_get_amods (source); memcpy (&dest->modifiers [dest_offset], &src_cmods->modifiers[0], src_cmods->count * sizeof (MonoSingleCustomMod)); dest_offset += src_cmods->count; } else { MonoCustomModContainer *src_cmods = mono_type_get_cmods (source); for (int i = 0; i < src_cmods->count; i++) { ERROR_DECL (error); // XXX FIXME: AK - propagate the error to the caller. MonoSingleCustomMod *cmod = &dest->modifiers [dest_offset++]; cmod->type = mono_type_get_checked (src_cmods->image, src_cmods->modifiers [i].token, NULL, error); mono_error_assert_ok (error); cmod->required = src_cmods->modifiers [i].required; } } return dest_offset; } /* makes a dup of 'o' but also appends the custom modifiers from 'cmods_source' */ static MonoType * do_metadata_type_dup_append_cmods (MonoImage *image, const MonoType *o, const MonoType *cmods_source) { g_assert (o != cmods_source); g_assert (o->has_cmods); g_assert (cmods_source->has_cmods); if (!mono_type_is_aggregate_mods (o) && !mono_type_is_aggregate_mods (cmods_source) && mono_type_get_cmods (o)->image == mono_type_get_cmods (cmods_source)->image) { /* the uniform case: all the cmods are from the same image. */ MonoCustomModContainer *o_cmods = mono_type_get_cmods (o); MonoCustomModContainer *extra_cmods = mono_type_get_cmods (cmods_source); uint8_t total_cmods = o_cmods->count + extra_cmods->count; gboolean aggregate = FALSE; size_t sizeof_dup = mono_sizeof_type_with_mods (total_cmods, aggregate); MonoType *r = image ? (MonoType *)mono_image_alloc0 (image, sizeof_dup) : (MonoType *)g_malloc0 (sizeof_dup); mono_type_with_mods_init (r, total_cmods, aggregate); /* copy the original type o, not including its modifiers */ memcpy (r, o, mono_sizeof_type_with_mods (0, FALSE)); deep_type_dup_fixup (image, r, o); /* The modifier order matters to Roslyn, they expect the extra cmods to come first: * * Suppose we substitute 'int32 modopt(IsLong)' for 'T' in 'void Test * (T modopt(IsConst))'. Roslyn expects the result to be 'void Test * (int32 modopt(IsLong) modopt(IsConst))'. * * but! cmods are encoded in IL in reverse order, so 'int32 modopt(IsConst) modopt(IsLong)' is * encoded as `cmod_opt [typeref IsLong] cmod_opt [typeref IsConst] I4` * so in our array, extra_cmods (IsLong) come first, followed by o_cmods (IsConst) * * (Here 'o' is 'int32 modopt(IsLong)' and cmods_source is 'T modopt(IsConst)') */ /* append the modifiers from cmods_source and o */ MonoCustomModContainer *r_container = mono_type_get_cmods (r); uint8_t dest_offset = 0; r_container->image = extra_cmods->image; memcpy (&r_container->modifiers [dest_offset], &o_cmods->modifiers [0], o_cmods->count * sizeof (MonoCustomMod)); dest_offset += o_cmods->count; memcpy (&r_container->modifiers [dest_offset], &extra_cmods->modifiers [0], extra_cmods->count * sizeof (MonoCustomMod)); dest_offset += extra_cmods->count; g_assert (dest_offset == total_cmods); return r; } else { /* The aggregate case: either o_cmods or extra_cmods has aggregate cmods, or they're both simple but from different images. */ uint8_t total_cmods = 0; total_cmods += mono_type_custom_modifier_count (o); total_cmods += mono_type_custom_modifier_count (cmods_source); gboolean aggregate = TRUE; size_t sizeof_dup = mono_sizeof_type_with_mods (total_cmods, aggregate); /* FIXME: if image, and the images of the custom modifiers from * o and cmods_source are all different, we need an image * set... */ MonoType *r = image ? (MonoType *)mono_image_alloc0 (image, sizeof_dup) : (MonoType*)g_malloc0 (sizeof_dup); mono_type_with_mods_init (r, total_cmods, aggregate); memcpy (r, o, mono_sizeof_type_with_mods (0, FALSE)); deep_type_dup_fixup (image, r, o); /* Try not to blow up the stack. See comment on * MONO_MAX_EXPECTED_CMODS. Since here we're appending all the * mods together, it's possible we'll end up with more than the * maximum allowed. If that ever happens in practice, we * should redefine the bound and possibly make this function * fail dynamically instead of asserting. */ g_assert (total_cmods < MONO_MAX_EXPECTED_CMODS); size_t r_container_size = mono_sizeof_aggregate_modifiers (total_cmods); MonoAggregateModContainer *r_container_candidate = g_alloca (r_container_size); memset (r_container_candidate, 0, r_container_size); uint8_t dest_offset = 0; dest_offset = custom_modifier_copy (r_container_candidate, dest_offset, o); dest_offset = custom_modifier_copy (r_container_candidate, dest_offset, cmods_source); g_assert (dest_offset == total_cmods); r_container_candidate->count = total_cmods; mono_type_set_amods (r, mono_metadata_get_canonical_aggregate_modifiers (r_container_candidate)); return r; } } /** * Works the same way as mono_metadata_type_dup but pick cmods from @cmods_source */ MonoType * mono_metadata_type_dup_with_cmods (MonoImage *image, const MonoType *o, const MonoType *cmods_source) { if (o->has_cmods && o != cmods_source && cmods_source->has_cmods) { return do_metadata_type_dup_append_cmods (image, o, cmods_source); } MonoType *r = NULL; /* if we get here, either o and cmods_source alias, or else exactly one of them has cmods. */ uint8_t num_mods = MAX (mono_type_custom_modifier_count (o), mono_type_custom_modifier_count (cmods_source)); gboolean aggregate = mono_type_is_aggregate_mods (o) || mono_type_is_aggregate_mods (cmods_source); size_t sizeof_r = mono_sizeof_type_with_mods (num_mods, aggregate); r = image ? (MonoType *)mono_image_alloc0 (image, sizeof_r) : (MonoType *)g_malloc0 (sizeof_r); if (cmods_source->has_cmods) { /* FIXME: if it's aggregate what do we assert here? */ g_assert (!image || (!aggregate && image == mono_type_get_cmods (cmods_source)->image)); memcpy (r, cmods_source, mono_sizeof_type (cmods_source)); } memcpy (r, o, mono_sizeof_type (o)); /* reset custom mod count and aggregateness to be correct. */ mono_type_with_mods_init (r, num_mods, aggregate); if (aggregate) mono_type_set_amods (r, mono_type_is_aggregate_mods (o) ? mono_type_get_amods (o) : mono_type_get_amods (cmods_source)); deep_type_dup_fixup (image, r, o); return r; } static void deep_type_dup_fixup (MonoImage *image, MonoType *r, const MonoType *o) { if (o->type == MONO_TYPE_PTR) { r->data.type = mono_metadata_type_dup (image, o->data.type); } else if (o->type == MONO_TYPE_ARRAY) { r->data.array = mono_dup_array_type (image, o->data.array); } else if (o->type == MONO_TYPE_FNPTR) { /*FIXME the dup'ed signature is leaked mono_metadata_free_type*/ r->data.method = mono_metadata_signature_deep_dup (image, o->data.method); } } /** * mono_signature_hash: */ guint mono_signature_hash (MonoMethodSignature *sig) { guint i, res = sig->ret->type; for (i = 0; i < sig->param_count; i++) res = (res << 5) - res + mono_type_hash (sig->params[i]); return res; } /* * mono_metadata_encode_value: * @value: value to encode * @buf: buffer where to write the compressed representation * @endbuf: pointer updated to point at the end of the encoded output * * Encodes the value @value in the compressed representation used * in metadata and stores the result in @buf. @buf needs to be big * enough to hold the data (4 bytes). */ void mono_metadata_encode_value (guint32 value, char *buf, char **endbuf) { char *p = buf; if (value < 0x80) *p++ = value; else if (value < 0x4000) { p [0] = 0x80 | (value >> 8); p [1] = value & 0xff; p += 2; } else { p [0] = (value >> 24) | 0xc0; p [1] = (value >> 16) & 0xff; p [2] = (value >> 8) & 0xff; p [3] = value & 0xff; p += 4; } if (endbuf) *endbuf = p; } /** * mono_metadata_field_info: * \param meta the Image the field is defined in * \param index the index in the field table representing the field * \param offset a pointer to an integer where to store the offset that may have been specified for the field in a FieldLayout table * \param rva a pointer to the RVA of the field data in the image that may have been defined in a \c FieldRVA table * \param marshal_spec a pointer to the marshal spec that may have been defined for the field in a \c FieldMarshal table. * * Gather info for field \p index that may have been defined in the \c FieldLayout, * \c FieldRVA and \c FieldMarshal tables. * Either of \p offset, \p rva and \p marshal_spec can be NULL if you're not interested * in the data. */ void mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec) { mono_metadata_field_info_full (meta, index, offset, rva, marshal_spec, FALSE); } void mono_metadata_field_info_with_mempool (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec) { mono_metadata_field_info_full (meta, index, offset, rva, marshal_spec, TRUE); } static void mono_metadata_field_info_full (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec, gboolean alloc_from_image) { MonoTableInfo *tdef; locator_t loc; loc.idx = index + 1; if (meta->uncompressed_metadata) loc.idx = search_ptr_table (meta, MONO_TABLE_FIELD_POINTER, loc.idx); if (offset) { tdef = &meta->tables [MONO_TABLE_FIELDLAYOUT]; loc.col_idx = MONO_FIELD_LAYOUT_FIELD; loc.t = tdef; /* FIXME: metadata-update */ if (tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) { *offset = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_LAYOUT_OFFSET); } else { *offset = (guint32)-1; } } if (rva) { tdef = &meta->tables [MONO_TABLE_FIELDRVA]; loc.col_idx = MONO_FIELD_RVA_FIELD; loc.t = tdef; if (tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) { /* * LAMESPEC: There is no signature, no nothing, just the raw data. */ *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA); } else { *rva = 0; } } if (marshal_spec) { const char *p; if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) { *marshal_spec = mono_metadata_parse_marshal_spec_full (alloc_from_image ? meta : NULL, meta, p); } } } /** * mono_metadata_get_constant_index: * \param meta the Image the field is defined in * \param index the token that may have a row defined in the constants table * \param hint possible position for the row * * \p token must be a \c FieldDef, \c ParamDef or \c PropertyDef token. * * \returns the index into the \c Constants table or 0 if not found. */ guint32 mono_metadata_get_constant_index (MonoImage *meta, guint32 token, guint32 hint) { MonoTableInfo *tdef; locator_t loc; guint32 index = mono_metadata_token_index (token); tdef = &meta->tables [MONO_TABLE_CONSTANT]; index <<= MONO_HASCONSTANT_BITS; switch (mono_metadata_token_table (token)) { case MONO_TABLE_FIELD: index |= MONO_HASCONSTANT_FIEDDEF; break; case MONO_TABLE_PARAM: index |= MONO_HASCONSTANT_PARAM; break; case MONO_TABLE_PROPERTY: index |= MONO_HASCONSTANT_PROPERTY; break; default: g_warning ("Not a valid token for the constant table: 0x%08x", token); return 0; } loc.idx = index; loc.col_idx = MONO_CONSTANT_PARENT; loc.t = tdef; /* FIXME: metadata-update */ /* FIXME: Index translation */ if ((hint > 0) && (hint < table_info_get_rows (tdef)) && (mono_metadata_decode_row_col (tdef, hint - 1, MONO_CONSTANT_PARENT) == index)) return hint; if (tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) { return loc.result + 1; } return 0; } /** * mono_metadata_events_from_typedef: * \param meta metadata context * \param index 0-based index (in the \c TypeDef table) describing a type * \returns the 0-based index in the \c Event table for the events in the * type. The last event that belongs to the type (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint32 start, end; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_EVENTMAP]; *end_idx = 0; if (!tdef->base) return 0; loc.t = tdef; loc.col_idx = MONO_EVENT_MAP_PARENT; loc.idx = index + 1; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; start = mono_metadata_decode_row_col (tdef, loc.result, MONO_EVENT_MAP_EVENTLIST); if (loc.result + 1 < table_info_get_rows (tdef)) { end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_EVENT_MAP_EVENTLIST) - 1; } else { end = table_info_get_rows (&meta->tables [MONO_TABLE_EVENT]); } *end_idx = end; return start - 1; } /** * mono_metadata_methods_from_event: * \param meta metadata context * \param index 0-based index (in the \c Event table) describing a event * \returns the 0-based index in the \c MethodDef table for the methods in the * event. The last method that belongs to the event (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_methods_from_event (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint start, end; guint32 cols [MONO_METHOD_SEMA_SIZE]; MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS]; *end_idx = 0; if (!msemt->base) return 0; if (meta->uncompressed_metadata) index = search_ptr_table (meta, MONO_TABLE_EVENT_POINTER, index + 1) - 1; loc.t = msemt; loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION; loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT; /* Method association coded index */ /* FIXME: metadata-update */ if (!mono_binary_search (&loc, msemt->base, table_info_get_rows (msemt), msemt->row_size, table_locator)) return 0; start = loc.result; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION)) start--; else break; } end = start + 1; int rows = table_info_get_rows (msemt); while (end < rows) { mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE); if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx) break; ++end; } *end_idx = end; return start; } /** * mono_metadata_properties_from_typedef: * \param meta metadata context * \param index 0-based index (in the \c TypeDef table) describing a type * \returns the 0-based index in the \c Property table for the properties in the * type. The last property that belongs to the type (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint32 start, end; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_PROPERTYMAP]; *end_idx = 0; if (!tdef->base) return 0; loc.t = tdef; loc.col_idx = MONO_PROPERTY_MAP_PARENT; loc.idx = index + 1; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; start = mono_metadata_decode_row_col (tdef, loc.result, MONO_PROPERTY_MAP_PROPERTY_LIST); if (loc.result + 1 < table_info_get_rows (tdef)) { end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_PROPERTY_MAP_PROPERTY_LIST) - 1; } else { end = table_info_get_rows (&meta->tables [MONO_TABLE_PROPERTY]); } *end_idx = end; return start - 1; } /** * mono_metadata_methods_from_property: * \param meta metadata context * \param index 0-based index (in the \c PropertyDef table) describing a property * \returns the 0-based index in the \c MethodDef table for the methods in the * property. The last method that belongs to the property (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_methods_from_property (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint start, end; guint32 cols [MONO_METHOD_SEMA_SIZE]; MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS]; *end_idx = 0; if (!msemt->base) return 0; if (meta->uncompressed_metadata) index = search_ptr_table (meta, MONO_TABLE_PROPERTY_POINTER, index + 1) - 1; loc.t = msemt; loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION; loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY; /* Method association coded index */ /* FIXME: metadata-update */ if (!mono_binary_search (&loc, msemt->base, table_info_get_rows (msemt), msemt->row_size, table_locator)) return 0; start = loc.result; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION)) start--; else break; } end = start + 1; int rows = table_info_get_rows (msemt); while (end < rows) { mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE); if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx) break; ++end; } *end_idx = end; return start; } /** * mono_metadata_implmap_from_method: */ guint32 mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx) { locator_t loc; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_IMPLMAP]; if (!tdef->base) return 0; /* No index translation seems to be needed */ loc.t = tdef; loc.col_idx = MONO_IMPLMAP_MEMBER; loc.idx = ((method_idx + 1) << MONO_MEMBERFORWD_BITS) | MONO_MEMBERFORWD_METHODDEF; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; return loc.result + 1; } /** * mono_type_create_from_typespec: * \param image context where the image is created * \param type_spec typespec token * \deprecated use \c mono_type_create_from_typespec_checked that has proper error handling * * Creates a \c MonoType representing the \c TypeSpec indexed by the \p type_spec * token. */ MonoType * mono_type_create_from_typespec (MonoImage *image, guint32 type_spec) { ERROR_DECL (error); MonoType *type = mono_type_create_from_typespec_checked (image, type_spec, error); if (!type) g_error ("Could not create typespec %x due to %s", type_spec, mono_error_get_message (error)); return type; } MonoType * mono_type_create_from_typespec_checked (MonoImage *image, guint32 type_spec, MonoError *error) { guint32 idx = mono_metadata_token_index (type_spec); MonoTableInfo *t; guint32 cols [MONO_TYPESPEC_SIZE]; const char *ptr; MonoType *type, *type2; error_init (error); type = (MonoType *)mono_conc_hashtable_lookup (image->typespec_cache, GUINT_TO_POINTER (type_spec)); if (type) return type; t = &image->tables [MONO_TABLE_TYPESPEC]; mono_metadata_decode_row (t, idx-1, cols, MONO_TYPESPEC_SIZE); ptr = mono_metadata_blob_heap (image, cols [MONO_TYPESPEC_SIGNATURE]); mono_metadata_decode_value (ptr, &ptr); type = mono_metadata_parse_type_checked (image, NULL, 0, TRUE, ptr, &ptr, error); if (!type) return NULL; type2 = mono_metadata_type_dup (image, type); mono_metadata_free_type (type); mono_image_lock (image); /* We might leak some data in the image mempool if found */ type = (MonoType*)mono_conc_hashtable_insert (image->typespec_cache, GUINT_TO_POINTER (type_spec), type2); if (!type) type = type2; mono_image_unlock (image); return type; } static char* mono_image_strndup (MonoImage *image, const char *data, guint len) { char *res; if (!image) return g_strndup (data, len); res = (char *)mono_image_alloc (image, len + 1); memcpy (res, data, len); res [len] = 0; return res; } /** * mono_metadata_parse_marshal_spec: */ MonoMarshalSpec * mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr) { return mono_metadata_parse_marshal_spec_full (NULL, image, ptr); } /* * If IMAGE is non-null, memory will be allocated from its mempool, otherwise it will be allocated using malloc. * PARENT_IMAGE is the image containing the marshal spec. */ MonoMarshalSpec * mono_metadata_parse_marshal_spec_full (MonoImage *image, MonoImage *parent_image, const char *ptr) { MonoMarshalSpec *res; int len; const char *start = ptr; /* fixme: this is incomplete, but I cant find more infos in the specs */ if (image) res = (MonoMarshalSpec *)mono_image_alloc0 (image, sizeof (MonoMarshalSpec)); else res = g_new0 (MonoMarshalSpec, 1); len = mono_metadata_decode_value (ptr, &ptr); res->native = (MonoMarshalNative)*ptr++; if (res->native == MONO_NATIVE_LPARRAY) { res->data.array_data.param_num = -1; res->data.array_data.num_elem = -1; res->data.array_data.elem_mult = -1; if (ptr - start <= len) res->data.array_data.elem_type = (MonoMarshalNative)*ptr++; if (ptr - start <= len) res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr); if (ptr - start <= len) res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr); if (ptr - start <= len) { /* * LAMESPEC: Older spec versions say this parameter comes before * num_elem. Never spec versions don't talk about elem_mult at * all, but csc still emits it, and it is used to distinguish * between param_num being 0, and param_num being omitted. * So if (param_num == 0) && (num_elem > 0), then * elem_mult == 0 -> the array size is num_elem * elem_mult == 1 -> the array size is @param_num + num_elem */ res->data.array_data.elem_mult = mono_metadata_decode_value (ptr, &ptr); } } if (res->native == MONO_NATIVE_BYVALTSTR) { if (ptr - start <= len) res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr); } if (res->native == MONO_NATIVE_BYVALARRAY) { if (ptr - start <= len) res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr); } if (res->native == MONO_NATIVE_CUSTOM) { /* skip unused type guid */ len = mono_metadata_decode_value (ptr, &ptr); ptr += len; /* skip unused native type name */ len = mono_metadata_decode_value (ptr, &ptr); ptr += len; /* read custom marshaler type name */ len = mono_metadata_decode_value (ptr, &ptr); res->data.custom_data.custom_name = mono_image_strndup (image, ptr, len); ptr += len; /* read cookie string */ len = mono_metadata_decode_value (ptr, &ptr); res->data.custom_data.cookie = mono_image_strndup (image, ptr, len); res->data.custom_data.image = parent_image; } if (res->native == MONO_NATIVE_SAFEARRAY) { res->data.safearray_data.elem_type = (MonoMarshalVariant)0; res->data.safearray_data.num_elem = 0; if (ptr - start <= len) res->data.safearray_data.elem_type = (MonoMarshalVariant)*ptr++; if (ptr - start <= len) res->data.safearray_data.num_elem = *ptr++; } return res; } /** * mono_metadata_free_marshal_spec: */ void mono_metadata_free_marshal_spec (MonoMarshalSpec *spec) { if (!spec) return; if (spec->native == MONO_NATIVE_CUSTOM) { g_free (spec->data.custom_data.custom_name); g_free (spec->data.custom_data.cookie); } g_free (spec); } /** * mono_type_to_unmanaged: * The value pointed to by \p conv will contain the kind of marshalling required for this * particular type one of the \c MONO_MARSHAL_CONV_ enumeration values. * \returns A \c MonoMarshalNative enumeration value (<code>MONO_NATIVE_</code>) value * describing the underlying native reprensetation of the type. */ guint32 // FIXMEcxx MonoMarshalNative mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field, gboolean unicode, MonoMarshalConv *conv) { MonoMarshalConv dummy_conv; int t = type->type; if (!conv) conv = &dummy_conv; *conv = MONO_MARSHAL_CONV_NONE; if (m_type_is_byref (type)) return MONO_NATIVE_UINT; handle_enum: switch (t) { case MONO_TYPE_BOOLEAN: if (mspec) { switch (mspec->native) { case MONO_NATIVE_VARIANTBOOL: *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL; return MONO_NATIVE_VARIANTBOOL; case MONO_NATIVE_BOOLEAN: *conv = MONO_MARSHAL_CONV_BOOL_I4; return MONO_NATIVE_BOOLEAN; case MONO_NATIVE_I1: case MONO_NATIVE_U1: return mspec->native; default: g_error ("cant marshal bool to native type %02x", mspec->native); } } *conv = MONO_MARSHAL_CONV_BOOL_I4; return MONO_NATIVE_BOOLEAN; case MONO_TYPE_CHAR: if (mspec) { switch (mspec->native) { case MONO_NATIVE_U2: case MONO_NATIVE_U1: return mspec->native; default: g_error ("cant marshal char to native type %02x", mspec->native); } } return unicode ? MONO_NATIVE_U2 : MONO_NATIVE_U1; case MONO_TYPE_I1: return MONO_NATIVE_I1; case MONO_TYPE_U1: return MONO_NATIVE_U1; case MONO_TYPE_I2: return MONO_NATIVE_I2; case MONO_TYPE_U2: return MONO_NATIVE_U2; case MONO_TYPE_I4: return MONO_NATIVE_I4; case MONO_TYPE_U4: return MONO_NATIVE_U4; case MONO_TYPE_I8: return MONO_NATIVE_I8; case MONO_TYPE_U8: return MONO_NATIVE_U8; case MONO_TYPE_R4: return MONO_NATIVE_R4; case MONO_TYPE_R8: return MONO_NATIVE_R8; case MONO_TYPE_STRING: if (mspec) { switch (mspec->native) { case MONO_NATIVE_BSTR: *conv = MONO_MARSHAL_CONV_STR_BSTR; return MONO_NATIVE_BSTR; case MONO_NATIVE_LPSTR: *conv = MONO_MARSHAL_CONV_STR_LPSTR; return MONO_NATIVE_LPSTR; case MONO_NATIVE_LPWSTR: *conv = MONO_MARSHAL_CONV_STR_LPWSTR; return MONO_NATIVE_LPWSTR; case MONO_NATIVE_LPTSTR: *conv = MONO_MARSHAL_CONV_STR_LPTSTR; return MONO_NATIVE_LPTSTR; case MONO_NATIVE_ANSIBSTR: *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR; return MONO_NATIVE_ANSIBSTR; case MONO_NATIVE_TBSTR: *conv = MONO_MARSHAL_CONV_STR_TBSTR; return MONO_NATIVE_TBSTR; case MONO_NATIVE_UTF8STR: *conv = MONO_MARSHAL_CONV_STR_UTF8STR; return MONO_NATIVE_UTF8STR; case MONO_NATIVE_BYVALTSTR: if (unicode) *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR; else *conv = MONO_MARSHAL_CONV_STR_BYVALSTR; return MONO_NATIVE_BYVALTSTR; default: g_error ("Can not marshal string to native type '%02x': Invalid managed/unmanaged type combination (String fields must be paired with LPStr, LPWStr, BStr or ByValTStr).", mspec->native); } } if (unicode) { *conv = MONO_MARSHAL_CONV_STR_LPWSTR; return MONO_NATIVE_LPWSTR; } else { *conv = MONO_MARSHAL_CONV_STR_LPSTR; return MONO_NATIVE_LPSTR; } case MONO_TYPE_PTR: return MONO_NATIVE_UINT; case MONO_TYPE_VALUETYPE: /*FIXME*/ if (m_class_is_enumtype (type->data.klass)) { t = mono_class_enum_basetype_internal (type->data.klass)->type; goto handle_enum; } if (type->data.klass == mono_class_try_get_handleref_class ()){ *conv = MONO_MARSHAL_CONV_HANDLEREF; return MONO_NATIVE_INT; } return MONO_NATIVE_STRUCT; case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: if (mspec) { switch (mspec->native) { case MONO_NATIVE_BYVALARRAY: if ((m_class_get_element_class (type->data.klass) == mono_defaults.char_class) && !unicode) *conv = MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY; else *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY; return MONO_NATIVE_BYVALARRAY; case MONO_NATIVE_SAFEARRAY: *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY; return MONO_NATIVE_SAFEARRAY; case MONO_NATIVE_LPARRAY: *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY; return MONO_NATIVE_LPARRAY; default: g_error ("cant marshal array as native type %02x", mspec->native); } } *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY; return MONO_NATIVE_LPARRAY; case MONO_TYPE_I: return MONO_NATIVE_INT; case MONO_TYPE_U: return MONO_NATIVE_UINT; case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: { /* FIXME : we need to handle ArrayList and StringBuilder here, probably */ if (mspec) { switch (mspec->native) { case MONO_NATIVE_STRUCT: // [MarshalAs(UnmanagedType.Struct)] // object field; // // becomes a VARIANT // // [MarshalAs(UnmangedType.Struct)] // SomeClass field; // // becomes uses the CONV_OBJECT_STRUCT conversion if (t != MONO_TYPE_OBJECT) *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT; return MONO_NATIVE_STRUCT; case MONO_NATIVE_CUSTOM: return MONO_NATIVE_CUSTOM; case MONO_NATIVE_INTERFACE: *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE; return MONO_NATIVE_INTERFACE; case MONO_NATIVE_IDISPATCH: *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH; return MONO_NATIVE_IDISPATCH; case MONO_NATIVE_IUNKNOWN: *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN; return MONO_NATIVE_IUNKNOWN; case MONO_NATIVE_FUNC: if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class || type->data.klass == mono_defaults.delegate_class || m_class_get_parent (type->data.klass) == mono_defaults.multicastdelegate_class)) { *conv = MONO_MARSHAL_CONV_DEL_FTN; return MONO_NATIVE_FUNC; } /* Fall through */ default: g_error ("cant marshal object as native type %02x", mspec->native); } } if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class || type->data.klass == mono_defaults.delegate_class || m_class_get_parent (type->data.klass) == mono_defaults.multicastdelegate_class)) { *conv = MONO_MARSHAL_CONV_DEL_FTN; return MONO_NATIVE_FUNC; } if (mono_class_try_get_safehandle_class () && type->data.klass != NULL && mono_class_is_subclass_of_internal (type->data.klass, mono_class_try_get_safehandle_class (), FALSE)){ *conv = MONO_MARSHAL_CONV_SAFEHANDLE; return MONO_NATIVE_INT; } #ifndef DISABLE_COM if (t == MONO_TYPE_CLASS && mono_cominterop_is_interface (type->data.klass)){ *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE; return MONO_NATIVE_INTERFACE; } #endif *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT; return MONO_NATIVE_STRUCT; } case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC; case MONO_TYPE_GENERICINST: type = m_class_get_byval_arg (type->data.generic_class->container_class); t = type->type; goto handle_enum; case MONO_TYPE_TYPEDBYREF: default: g_error ("type 0x%02x not handled in marshal", t); } return MONO_NATIVE_MAX; } /** * mono_metadata_get_marshal_info: */ const char* mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field) { locator_t loc; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_FIELDMARSHAL]; if (!tdef->base) return NULL; loc.t = tdef; loc.col_idx = MONO_FIELD_MARSHAL_PARENT; loc.idx = ((idx + 1) << MONO_HAS_FIELD_MARSHAL_BITS) | (is_field? MONO_HAS_FIELD_MARSHAL_FIELDSREF: MONO_HAS_FIELD_MARSHAL_PARAMDEF); /* FIXME: metadata-update */ /* FIXME: Index translation */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return NULL; return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE)); } MonoMethod* mono_method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context, MonoError *error) { MonoMethod *result = NULL; guint32 idx = tok >> MONO_METHODDEFORREF_BITS; error_init (error); switch (tok & MONO_METHODDEFORREF_MASK) { case MONO_METHODDEFORREF_METHODDEF: result = mono_get_method_checked (m, MONO_TOKEN_METHOD_DEF | idx, NULL, context, error); break; case MONO_METHODDEFORREF_METHODREF: result = mono_get_method_checked (m, MONO_TOKEN_MEMBER_REF | idx, NULL, context, error); break; default: mono_error_set_bad_image (error, m, "Invalid MethodDefOfRef token %x", tok); } return result; } /* * mono_class_get_overrides_full: * * Compute the method overrides belonging to class @type_token in @overrides, and the number of overrides in @num_overrides. * */ void mono_class_get_overrides_full (MonoImage *image, guint32 type_token, MonoMethod ***overrides, gint32 *num_overrides, MonoGenericContext *generic_context, MonoError *error) { locator_t loc; MonoTableInfo *tdef = &image->tables [MONO_TABLE_METHODIMPL]; guint32 start, end; gint32 i, num; guint32 cols [MONO_METHODIMPL_SIZE]; MonoMethod **result; error_init (error); *overrides = NULL; if (num_overrides) *num_overrides = 0; if (!tdef->base) return; loc.t = tdef; loc.col_idx = MONO_METHODIMPL_CLASS; loc.idx = mono_metadata_token_index (type_token); /* FIXME metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return; start = loc.result; end = start + 1; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS)) start--; else break; } int rows = table_info_get_rows (tdef); while (end < rows) { if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS)) end++; else break; } num = end - start; result = g_new (MonoMethod*, num * 2); for (i = 0; i < num; ++i) { MonoMethod *method; mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE); method = mono_method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_DECLARATION], generic_context, error); if (!method) break; result [i * 2] = method; method = mono_method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_BODY], generic_context, error); if (!method) break; result [i * 2 + 1] = method; } if (!is_ok (error)) { g_free (result); *overrides = NULL; if (num_overrides) *num_overrides = 0; } else { *overrides = result; if (num_overrides) *num_overrides = num; } } /** * mono_guid_to_string: * * Converts a 16 byte Microsoft GUID to the standard string representation. */ char * mono_guid_to_string (const guint8 *guid) { return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", guid[3], guid[2], guid[1], guid[0], guid[5], guid[4], guid[7], guid[6], guid[8], guid[9], guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]); } /** * mono_guid_to_string_minimal: * * Converts a 16 byte Microsoft GUID to lower case no '-' representation.. */ char * mono_guid_to_string_minimal (const guint8 *guid) { return g_strdup_printf ("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", guid[3], guid[2], guid[1], guid[0], guid[5], guid[4], guid[7], guid[6], guid[8], guid[9], guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]); } static gboolean get_constraints (MonoImage *image, int owner, MonoClass ***constraints, MonoGenericContainer *container, MonoError *error) { MonoTableInfo *tdef = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT]; guint32 cols [MONO_GENPARCONSTRAINT_SIZE]; guint32 i, token, found; MonoClass *klass, **res; GSList *cons = NULL, *tmp; MonoGenericContext *context = &container->context; error_init (error); *constraints = NULL; found = 0; /* FIXME: metadata-update */ int rows = table_info_get_rows (tdef); for (i = 0; i < rows; ++i) { mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE); if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) { token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]); klass = mono_class_get_and_inflate_typespec_checked (image, token, context, error); if (!klass) { g_slist_free (cons); return FALSE; } cons = g_slist_append (cons, klass); ++found; } else { /* contiguous list finished */ if (found) break; } } if (!found) return TRUE; res = (MonoClass **)mono_image_alloc0 (image, sizeof (MonoClass*) * (found + 1)); for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) { res [i] = (MonoClass *)tmp->data; } g_slist_free (cons); *constraints = res; return TRUE; } /* * mono_metadata_get_generic_param_row: * * @image: * @token: TypeOrMethodDef token, owner for GenericParam * @owner: coded token, set on return * * Returns: 1-based row-id in the GenericParam table whose * owner is @token. 0 if not found. */ guint32 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner) { MonoTableInfo *tdef = &image->tables [MONO_TABLE_GENERICPARAM]; locator_t loc; g_assert (owner); if (!tdef->base) return 0; if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF) *owner = MONO_TYPEORMETHOD_TYPE; else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) *owner = MONO_TYPEORMETHOD_METHOD; else { g_error ("wrong token %x to get_generic_param_row", token); return 0; } *owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS; loc.idx = *owner; loc.col_idx = MONO_GENERICPARAM_OWNER; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_GENERICPARAM_OWNER) == loc.idx)) loc.result --; return loc.result + 1; } gboolean mono_metadata_has_generic_params (MonoImage *image, guint32 token) { guint32 owner; return mono_metadata_get_generic_param_row (image, token, &owner); } /* * Memory is allocated from IMAGE's mempool. */ gboolean mono_metadata_load_generic_param_constraints_checked (MonoImage *image, guint32 token, MonoGenericContainer *container, MonoError *error) { guint32 start_row, i, owner; error_init (error); if (! (start_row = mono_metadata_get_generic_param_row (image, token, &owner))) return TRUE; for (i = 0; i < container->type_argc; i++) { if (!get_constraints (image, start_row + i, &mono_generic_container_get_param_info (container, i)->constraints, container, error)) { return FALSE; } } return TRUE; } /* * mono_metadata_load_generic_params: * * Load the type parameters from the type or method definition @token. * * Use this method after parsing a type or method definition to figure out whether it's a generic * type / method. When parsing a method definition, @parent_container points to the generic container * of the current class, if any. * * Note: This method does not load the constraints: for typedefs, this has to be done after fully * creating the type. * * Returns: NULL if @token is not a generic type or method definition or the new generic container. * * LOCKING: Acquires the loader lock * */ MonoGenericContainer * mono_metadata_load_generic_params (MonoImage *image, guint32 token, MonoGenericContainer *parent_container, gpointer real_owner) { MonoTableInfo *tdef = &image->tables [MONO_TABLE_GENERICPARAM]; guint32 cols [MONO_GENERICPARAM_SIZE]; guint32 i, owner = 0, n; MonoGenericContainer *container; MonoGenericParamFull *params; MonoGenericContext *context; gboolean is_method = mono_metadata_token_table (token) == MONO_TABLE_METHOD; gboolean is_anonymous = real_owner == NULL; if (!(i = mono_metadata_get_generic_param_row (image, token, &owner))) return NULL; mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE); params = NULL; n = 0; container = (MonoGenericContainer *)mono_image_alloc0 (image, sizeof (MonoGenericContainer)); container->is_anonymous = is_anonymous; if (is_anonymous) { container->owner.image = image; } else { if (is_method) container->owner.method = (MonoMethod*)real_owner; else container->owner.klass = (MonoClass*)real_owner; } do { n++; params = (MonoGenericParamFull *)g_realloc (params, sizeof (MonoGenericParamFull) * n); memset (&params [n - 1], 0, sizeof (MonoGenericParamFull)); params [n - 1].owner = container; params [n - 1].num = cols [MONO_GENERICPARAM_NUMBER]; params [n - 1].info.token = i | MONO_TOKEN_GENERIC_PARAM; params [n - 1].info.flags = cols [MONO_GENERICPARAM_FLAGS]; params [n - 1].info.name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]); if (params [n - 1].num != n - 1) g_warning ("GenericParam table unsorted or hole in generic param sequence: token %d", i); /* FIXME: metadata-update */ if (++i > table_info_get_rows (tdef)) break; mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE); } while (cols [MONO_GENERICPARAM_OWNER] == owner); container->type_argc = n; container->type_params = (MonoGenericParamFull *)mono_image_alloc0 (image, sizeof (MonoGenericParamFull) * n); memcpy (container->type_params, params, sizeof (MonoGenericParamFull) * n); g_free (params); container->parent = parent_container; if (is_method) container->is_method = 1; g_assert (container->parent == NULL || container->is_method); context = &container->context; if (container->is_method) { context->class_inst = container->parent ? container->parent->context.class_inst : NULL; context->method_inst = mono_get_shared_generic_inst (container); } else { context->class_inst = mono_get_shared_generic_inst (container); } return container; } MonoGenericInst * mono_get_shared_generic_inst (MonoGenericContainer *container) { MonoType **type_argv; MonoType *helper; MonoGenericInst *nginst; int i; type_argv = g_new0 (MonoType *, container->type_argc); helper = g_new0 (MonoType, container->type_argc); for (i = 0; i < container->type_argc; i++) { MonoType *t = &helper [i]; t->type = container->is_method ? MONO_TYPE_MVAR : MONO_TYPE_VAR; t->data.generic_param = mono_generic_container_get_param (container, i); type_argv [i] = t; } nginst = mono_metadata_get_generic_inst (container->type_argc, type_argv); g_free (type_argv); g_free (helper); return nginst; } /** * mono_type_is_byref: * \param type the \c MonoType operated on * \returns TRUE if \p type represents a type passed by reference, * FALSE otherwise. */ mono_bool mono_type_is_byref (MonoType *type) { mono_bool result; MONO_ENTER_GC_UNSAFE; // FIXME slow result = m_type_is_byref (type); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_type_get_type: * \param type the \c MonoType operated on * \returns the IL type value for \p type. This is one of the \c MonoTypeEnum * enum members like \c MONO_TYPE_I4 or \c MONO_TYPE_STRING. */ int mono_type_get_type (MonoType *type) { return mono_type_get_type_internal (type); } /** * mono_type_get_signature: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_FNPTR . * \returns the \c MonoMethodSignature pointer that describes the signature * of the function pointer \p type represents. */ MonoMethodSignature* mono_type_get_signature (MonoType *type) { return mono_type_get_signature_internal (type); } /** * mono_type_get_class: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_CLASS or a * \c MONO_TYPE_VALUETYPE . For more general functionality, use \c mono_class_from_mono_type_internal, * instead. * \returns the \c MonoClass pointer that describes the class that \p type represents. */ MonoClass* mono_type_get_class (MonoType *type) { /* FIXME: review the runtime users before adding the assert here */ return mono_type_get_class_internal (type); } /** * mono_type_get_array_type: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_ARRAY . * \returns a \c MonoArrayType struct describing the array type that \p type * represents. The info includes details such as rank, array element type * and the sizes and bounds of multidimensional arrays. */ MonoArrayType* mono_type_get_array_type (MonoType *type) { return mono_type_get_array_type_internal (type); } /** * mono_type_get_ptr_type: * \pararm type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_PTR . * \returns the \c MonoType pointer that describes the type that \p type * represents a pointer to. */ MonoType* mono_type_get_ptr_type (MonoType *type) { g_assert (type->type == MONO_TYPE_PTR); return type->data.type; } /** * mono_type_get_modifiers: */ MonoClass* mono_type_get_modifiers (MonoType *type, gboolean *is_required, gpointer *iter) { /* FIXME: implement */ return NULL; } /** * mono_type_is_struct: * \param type the \c MonoType operated on * \returns TRUE if \p type is a struct, that is a \c ValueType but not an enum * or a basic type like \c System.Int32 . FALSE otherwise. */ mono_bool mono_type_is_struct (MonoType *type) { return (!m_type_is_byref (type) && ((type->type == MONO_TYPE_VALUETYPE && !m_class_is_enumtype (type->data.klass)) || (type->type == MONO_TYPE_TYPEDBYREF) || ((type->type == MONO_TYPE_GENERICINST) && mono_metadata_generic_class_is_valuetype (type->data.generic_class) && !m_class_is_enumtype (type->data.generic_class->container_class)))); } /** * mono_type_is_void: * \param type the \c MonoType operated on * \returns TRUE if \p type is \c System.Void . FALSE otherwise. */ mono_bool mono_type_is_void (MonoType *type) { return (type && (type->type == MONO_TYPE_VOID) && !m_type_is_byref (type)); } /** * mono_type_is_pointer: * \param type the \c MonoType operated on * \returns TRUE if \p type is a managed or unmanaged pointer type. FALSE otherwise. */ mono_bool mono_type_is_pointer (MonoType *type) { return (type && ((m_type_is_byref (type) || (type->type == MONO_TYPE_I) || type->type == MONO_TYPE_STRING) || (type->type == MONO_TYPE_SZARRAY) || (type->type == MONO_TYPE_CLASS) || (type->type == MONO_TYPE_U) || (type->type == MONO_TYPE_OBJECT) || (type->type == MONO_TYPE_ARRAY) || (type->type == MONO_TYPE_PTR) || (type->type == MONO_TYPE_FNPTR))); } /** * mono_type_is_reference: * \param type the \c MonoType operated on * \returns TRUE if \p type represents an object reference. FALSE otherwise. */ mono_bool mono_type_is_reference (MonoType *type) { /* NOTE: changing this function to return TRUE more often may have * consequences for generic sharing in the AOT compiler. In * particular, returning TRUE for generic parameters with a 'class' * constraint may cause crashes. */ return (type && (((type->type == MONO_TYPE_STRING) || (type->type == MONO_TYPE_SZARRAY) || (type->type == MONO_TYPE_CLASS) || (type->type == MONO_TYPE_OBJECT) || (type->type == MONO_TYPE_ARRAY)) || ((type->type == MONO_TYPE_GENERICINST) && !mono_metadata_generic_class_is_valuetype (type->data.generic_class)))); } mono_bool mono_type_is_generic_parameter (MonoType *type) { return !m_type_is_byref (type) && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR); } /** * mono_signature_get_return_type: * \param sig the method signature inspected * \returns the return type of the method signature \p sig */ MonoType* mono_signature_get_return_type (MonoMethodSignature *sig) { MonoType *result; MONO_ENTER_GC_UNSAFE; result = sig->ret; MONO_EXIT_GC_UNSAFE; return result; } /** * mono_signature_get_params: * \param sig the method signature inspected * \param iter pointer to an iterator * Iterates over the parameters for the method signature \p sig. * A \c void* pointer must be initialized to NULL to start the iteration * and its address is passed to this function repeteadly until it returns * NULL. * \returns the next parameter type of the method signature \p sig, * NULL when finished. */ MonoType* mono_signature_get_params (MonoMethodSignature *sig, gpointer *iter) { MonoType *result; MONO_ENTER_GC_UNSAFE; result = mono_signature_get_params_internal (sig, iter); MONO_EXIT_GC_UNSAFE; return result; } MonoType* mono_signature_get_params_internal (MonoMethodSignature *sig, gpointer *iter) { MonoType** type; if (!iter) return NULL; if (!*iter) { /* start from the first */ if (sig->param_count) { *iter = &sig->params [0]; return sig->params [0]; } else { /* no method */ return NULL; } } type = (MonoType **)*iter; type++; if (type < &sig->params [sig->param_count]) { *iter = type; return *type; } return NULL; } /** * mono_signature_get_param_count: * \param sig the method signature inspected * \returns the number of parameters in the method signature \p sig. */ guint32 mono_signature_get_param_count (MonoMethodSignature *sig) { return sig->param_count; } /** * mono_signature_get_call_conv: * \param sig the method signature inspected * \returns the call convention of the method signature \p sig. */ guint32 mono_signature_get_call_conv (MonoMethodSignature *sig) { return sig->call_convention; } /** * mono_signature_vararg_start: * \param sig the method signature inspected * \returns the number of the first vararg parameter in the * method signature \param sig. \c -1 if this is not a vararg signature. */ int mono_signature_vararg_start (MonoMethodSignature *sig) { return sig->sentinelpos; } /** * mono_signature_is_instance: * \param sig the method signature inspected * \returns TRUE if this the method signature \p sig has an implicit * first instance argument. FALSE otherwise. */ gboolean mono_signature_is_instance (MonoMethodSignature *sig) { return sig->hasthis; } /** * mono_signature_param_is_out * \param sig the method signature inspected * \param param_num the 0-based index of the inspected parameter * \returns TRUE if the parameter is an out parameter, FALSE * otherwise. */ mono_bool mono_signature_param_is_out (MonoMethodSignature *sig, int param_num) { g_assert (param_num >= 0 && param_num < sig->param_count); return (sig->params [param_num]->attrs & PARAM_ATTRIBUTE_OUT) != 0; } /** * mono_signature_explicit_this: * \param sig the method signature inspected * \returns TRUE if this the method signature \p sig has an explicit * instance argument. FALSE otherwise. */ gboolean mono_signature_explicit_this (MonoMethodSignature *sig) { return sig->explicit_this; } /* for use with allocated memory blocks (assumes alignment is to 8 bytes) */ guint mono_aligned_addr_hash (gconstpointer ptr) { /* Same hashing we use for objects */ return (GPOINTER_TO_UINT (ptr) >> 3) * 2654435761u; } /* * If @field belongs to an inflated generic class, return the corresponding field of the * generic type definition class. */ MonoClassField* mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassField *field) { MonoClass *gtd; int offset; if (!mono_class_is_ginst (m_field_get_parent (field))) return field; gtd = mono_class_get_generic_class (m_field_get_parent (field))->container_class; offset = field - m_class_get_fields (m_field_get_parent (field)); return m_class_get_fields (gtd) + offset; } /* * If @event belongs to an inflated generic class, return the corresponding event of the * generic type definition class. */ MonoEvent* mono_metadata_get_corresponding_event_from_generic_type_definition (MonoEvent *event) { MonoClass *gtd; int offset; if (!mono_class_is_ginst (event->parent)) return event; gtd = mono_class_get_generic_class (event->parent)->container_class; offset = event - mono_class_get_event_info (event->parent)->events; return mono_class_get_event_info (gtd)->events + offset; } /* * If @property belongs to an inflated generic class, return the corresponding property of the * generic type definition class. */ MonoProperty* mono_metadata_get_corresponding_property_from_generic_type_definition (MonoProperty *property) { MonoClassPropertyInfo *info; MonoClass *gtd; int offset; if (!mono_class_is_ginst (property->parent)) return property; info = mono_class_get_property_info (property->parent); gtd = mono_class_get_generic_class (property->parent)->container_class; offset = property - info->properties; return mono_class_get_property_info (gtd)->properties + offset; } MonoWrapperCaches* mono_method_get_wrapper_cache (MonoMethod *method) { if (method->is_inflated) { MonoMethodInflated *imethod = (MonoMethodInflated *)method; return &imethod->owner->wrapper_caches; } else { return &m_class_get_image (method->klass)->wrapper_caches; } } void mono_loader_set_strict_assembly_name_check (gboolean enabled) { check_assembly_names_strictly = enabled; } gboolean mono_loader_get_strict_assembly_name_check (void) { return check_assembly_names_strictly; } gboolean mono_type_is_aggregate_mods (const MonoType *t) { if (!t->has_cmods) return FALSE; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; return full->is_aggregate; } MonoCustomModContainer * mono_type_get_cmods (const MonoType *t) { if (!t->has_cmods) return NULL; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; g_assert (!full->is_aggregate); return &full->mods.cmods; } MonoAggregateModContainer * mono_type_get_amods (const MonoType *t) { if (!t->has_cmods) return NULL; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; g_assert (full->is_aggregate); return full->mods.amods; } size_t mono_sizeof_aggregate_modifiers (uint8_t num_mods) { size_t accum = 0; accum += offsetof (MonoAggregateModContainer, modifiers); accum += sizeof (MonoSingleCustomMod) * num_mods; return accum; } size_t mono_sizeof_type_with_mods (uint8_t num_mods, gboolean is_aggregate) { if (num_mods == 0) return sizeof (MonoType); size_t accum = 0; accum += offsetof (MonoTypeWithModifiers, mods); if (!is_aggregate) { accum += offsetof (struct _MonoCustomModContainer, modifiers); accum += sizeof (MonoCustomMod) * num_mods; } else { accum += offsetof (MonoAggregateModContainer, modifiers); accum += sizeof (MonoAggregateModContainer *); } return accum; } size_t mono_sizeof_type (const MonoType *ty) { if (ty->has_cmods) { if (!mono_type_is_aggregate_mods (ty)) { MonoCustomModContainer *cmods = mono_type_get_cmods (ty); return mono_sizeof_type_with_mods (cmods->count, FALSE); } else { MonoAggregateModContainer *amods = mono_type_get_amods (ty); return mono_sizeof_type_with_mods (amods->count, TRUE); } } else return sizeof (MonoType); } void mono_type_set_amods (MonoType *t, MonoAggregateModContainer *amods) { g_assert (t->has_cmods); MonoTypeWithModifiers *t_full = (MonoTypeWithModifiers*)t; g_assert (t_full->is_aggregate); g_assert (t_full->mods.amods == NULL); t_full->mods.amods = amods; } #ifndef DISABLE_COM static void mono_signature_append_class_name (GString *res, MonoClass *klass) { if (!klass) { g_string_append (res, "<UNKNOWN>"); return; } if (m_class_get_nested_in (klass)) { mono_signature_append_class_name (res, m_class_get_nested_in (klass)); g_string_append_c (res, '+'); } else if (*m_class_get_name_space (klass)) { g_string_append (res, m_class_get_name_space (klass)); g_string_append_c (res, '.'); } g_string_append (res, m_class_get_name (klass)); } static void mono_guid_signature_append_method (GString *res, MonoMethodSignature *sig); static void mono_guid_signature_append_type (GString *res, MonoType *type) { int i; switch (type->type) { case MONO_TYPE_VOID: g_string_append (res, "void"); break; case MONO_TYPE_BOOLEAN: g_string_append (res, "bool"); break; case MONO_TYPE_CHAR: g_string_append (res, "wchar"); break; case MONO_TYPE_I1: g_string_append (res, "int8"); break; case MONO_TYPE_U1: g_string_append (res, "unsigned int8"); break; case MONO_TYPE_I2: g_string_append (res, "int16"); break; case MONO_TYPE_U2: g_string_append (res, "unsigned int16"); break; case MONO_TYPE_I4: g_string_append (res, "int32"); break; case MONO_TYPE_U4: g_string_append (res, "unsigned int32"); break; case MONO_TYPE_I8: g_string_append (res, "int64"); break; case MONO_TYPE_U8: g_string_append (res, "unsigned int64"); break; case MONO_TYPE_R4: g_string_append (res, "float32"); break; case MONO_TYPE_R8: g_string_append (res, "float64"); break; case MONO_TYPE_U: g_string_append (res, "unsigned int"); break; case MONO_TYPE_I: g_string_append (res, "int"); break; case MONO_TYPE_OBJECT: g_string_append (res, "class System.Object"); break; case MONO_TYPE_STRING: g_string_append (res, "class System.String"); break; case MONO_TYPE_TYPEDBYREF: g_string_append (res, "refany"); break; case MONO_TYPE_VALUETYPE: g_string_append (res, "value class "); mono_signature_append_class_name (res, type->data.klass); break; case MONO_TYPE_CLASS: g_string_append (res, "class "); mono_signature_append_class_name (res, type->data.klass); break; case MONO_TYPE_SZARRAY: mono_guid_signature_append_type (res, m_class_get_byval_arg (type->data.klass)); g_string_append (res, "[]"); break; case MONO_TYPE_ARRAY: mono_guid_signature_append_type (res, m_class_get_byval_arg (type->data.array->eklass)); g_string_append_c (res, '['); if (type->data.array->rank == 0) g_string_append (res, "??"); for (i = 0; i < type->data.array->rank; ++i) { if (i > 0) g_string_append_c (res, ','); if (type->data.array->sizes[i] == 0 || type->data.array->lobounds[i] == 0) continue; g_string_append_printf (res, "%d", type->data.array->lobounds[i]); g_string_append (res, "..."); g_string_append_printf (res, "%d", type->data.array->lobounds[i] + type->data.array->sizes[i] + 1); } g_string_append_c (res, ']'); break; case MONO_TYPE_MVAR: case MONO_TYPE_VAR: if (type->data.generic_param) g_string_append_printf (res, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", mono_generic_param_num (type->data.generic_param)); else g_string_append (res, "<UNKNOWN>"); break; case MONO_TYPE_GENERICINST: { MonoGenericContext *context; mono_guid_signature_append_type (res, m_class_get_byval_arg (type->data.generic_class->container_class)); g_string_append (res, "<"); context = &type->data.generic_class->context; if (context->class_inst) { for (i = 0; i < context->class_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ","); mono_guid_signature_append_type (res, context->class_inst->type_argv [i]); } } else if (context->method_inst) { for (i = 0; i < context->method_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ","); mono_guid_signature_append_type (res, context->method_inst->type_argv [i]); } } g_string_append (res, ">"); break; } case MONO_TYPE_FNPTR: g_string_append (res, "fnptr "); mono_guid_signature_append_method (res, type->data.method); break; case MONO_TYPE_PTR: mono_guid_signature_append_type (res, type->data.type); g_string_append_c (res, '*'); break; default: break; } if (m_type_is_byref (type)) g_string_append_c (res, '&'); } static void mono_guid_signature_append_method (GString *res, MonoMethodSignature *sig) { int i, j; if (mono_signature_is_instance (sig)) g_string_append (res, "instance "); if (sig->generic_param_count) g_string_append (res, "generic "); switch (mono_signature_get_call_conv (sig)) { case MONO_CALL_DEFAULT: break; case MONO_CALL_C: g_string_append (res, "unmanaged cdecl "); break; case MONO_CALL_STDCALL: g_string_append (res, "unmanaged stdcall "); break; case MONO_CALL_THISCALL: g_string_append (res, "unmanaged thiscall "); break; case MONO_CALL_FASTCALL: g_string_append (res, "unmanaged fastcall "); break; case MONO_CALL_VARARG: g_string_append (res, "vararg "); break; default: break; } mono_guid_signature_append_type (res, mono_signature_get_return_type_internal(sig)); g_string_append_c (res, '('); for (i = 0, j = 0; i < sig->param_count && j < sig->param_count; ++i, ++j) { if (i > 0) g_string_append_c (res, ','); if (sig->params [j]->attrs & PARAM_ATTRIBUTE_IN) { /*.NET runtime "incorrectly" shifts the parameter signatures too...*/ g_string_append (res, "required_modifier System.Runtime.InteropServices.InAttribute"); if (++i == sig->param_count) break; g_string_append_c (res, ','); } mono_guid_signature_append_type (res, sig->params [j]); } g_string_append_c (res, ')'); } static void mono_generate_v3_guid_for_interface (MonoClass* klass, guint8* guid) { /* COM+ Runtime GUID {69f9cbc9-da05-11d1-9408-0000f8083460} */ static const guchar guid_name_space[] = {0x69,0xf9,0xcb,0xc9,0xda,0x05,0x11,0xd1,0x94,0x08,0x00,0x00,0xf8,0x08,0x34,0x60}; MonoMD5Context ctx; MonoMethod *method; gpointer iter = NULL; guchar byte; glong items_read, items_written; int i; mono_md5_init (&ctx); mono_md5_update (&ctx, guid_name_space, sizeof(guid_name_space)); GString *name = g_string_new (""); mono_signature_append_class_name (name, klass); gunichar2 *unicode_name = g_utf8_to_utf16 (name->str, name->len, &items_read, &items_written, NULL); mono_md5_update (&ctx, (guchar *)unicode_name, items_written * sizeof(gunichar2)); g_free (unicode_name); g_string_free (name, TRUE); while ((method = mono_class_get_methods(klass, &iter)) != NULL) { ERROR_DECL (error); if (!mono_cominterop_method_com_visible(method)) continue; MonoMethodSignature *sig = mono_method_signature_checked (method, error); mono_error_assert_ok (error); /*FIXME proper error handling*/ GString *res = g_string_new (""); mono_guid_signature_append_method (res, sig); mono_md5_update (&ctx, (guchar *)res->str, res->len); g_string_free (res, TRUE); for (i = 0; i < sig->param_count; ++i) { byte = sig->params [i]->attrs; mono_md5_update (&ctx, &byte, 1); } } byte = 0; if (mono_md5_ctx_byte_length (&ctx) & 1) mono_md5_update (&ctx, &byte, 1); mono_md5_final (&ctx, (guchar *)guid); guid[6] &= 0x0f; guid[6] |= 0x30; /* v3 (md5) */ guid[8] &= 0x3F; guid[8] |= 0x80; *(guint32 *)(guid + 0) = GUINT32_FROM_BE(*(guint32 *)(guid + 0)); *(guint16 *)(guid + 4) = GUINT16_FROM_BE(*(guint16 *)(guid + 4)); *(guint16 *)(guid + 6) = GUINT16_FROM_BE(*(guint16 *)(guid + 6)); } #endif static gint mono_unichar_xdigit_value (gunichar c) { if (c >= 0x30 && c <= 0x39) /*0-9*/ return (c - 0x30); if (c >= 0x41 && c <= 0x46) /*A-F*/ return (c - 0x37); if (c >= 0x61 && c <= 0x66) /*a-f*/ return (c - 0x57); return -1; } /** * mono_string_to_guid: * * Converts the standard string representation of a GUID * to a 16 byte Microsoft GUID. */ static void mono_string_to_guid (MonoString* string, guint8 *guid) { gunichar2 * chars = mono_string_chars_internal (string); int i = 0; static const guint8 indexes[16] = {7, 5, 3, 1, 12, 10, 17, 15, 20, 22, 25, 27, 29, 31, 33, 35}; for (i = 0; i < sizeof(indexes); i++) guid [i] = mono_unichar_xdigit_value (chars [indexes [i]]) + (mono_unichar_xdigit_value (chars [indexes [i] - 1]) << 4); } static GENERATE_GET_CLASS_WITH_CACHE (guid_attribute, "System.Runtime.InteropServices", "GuidAttribute") void mono_metadata_get_class_guid (MonoClass* klass, guint8* guid, MonoError *error) { MonoReflectionGuidAttribute *attr = NULL; MonoCustomAttrInfo *cinfo = mono_custom_attrs_from_class_checked (klass, error); if (!is_ok (error)) return; if (cinfo) { attr = (MonoReflectionGuidAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_get_guid_attribute_class (), error); if (!is_ok (error)) return; if (!cinfo->cached) mono_custom_attrs_free (cinfo); } memset(guid, 0, 16); if (attr) mono_string_to_guid (attr->guid, guid); #ifndef DISABLE_COM else if (mono_class_is_interface (klass)) mono_generate_v3_guid_for_interface (klass, guid); else g_warning ("Generated GUIDs only implemented for interfaces!"); #endif }
/** * \file * Routines for accessing the metadata * * Authors: * Miguel de Icaza ([email protected]) * Paolo Molaro ([email protected]) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glib.h> #include <mono/metadata/metadata.h> #include "tabledefs.h" #include "mono-endian.h" #include "cil-coff.h" #include <mono/metadata/tokentype.h> #include "class-internals.h" #include "metadata-internals.h" #include "reflection-internals.h" #include "metadata-update.h" #include <mono/metadata/class.h> #include "marshal.h" #include <mono/metadata/debug-helpers.h> #include "abi-details.h" #include "cominterop.h" #include "components.h" #include <mono/metadata/exception-internals.h> #include <mono/utils/mono-error-internals.h> #include <mono/utils/mono-memory-model.h> #include <mono/utils/mono-digest.h> #include <mono/utils/bsearch.h> #include <mono/utils/atomic.h> #include <mono/utils/unlocked.h> #include <mono/utils/mono-counters.h> /* Auxiliary structure used for caching inflated signatures */ typedef struct { MonoMethodSignature *sig; MonoGenericContext context; } MonoInflatedMethodSignature; static gboolean do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container, gboolean transient, const char *ptr, const char **rptr, MonoError *error); static gboolean do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only); static gboolean mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only); static gboolean mono_metadata_fnptr_equal (MonoMethodSignature *s1, MonoMethodSignature *s2, gboolean signature_only); static gboolean _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only); static void free_generic_inst (MonoGenericInst *ginst); static void free_generic_class (MonoGenericClass *ginst); static void free_inflated_signature (MonoInflatedMethodSignature *sig); static void free_aggregate_modifiers (MonoAggregateModContainer *amods); static void mono_metadata_field_info_full (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec, gboolean alloc_from_image); static MonoType* mono_signature_get_params_internal (MonoMethodSignature *sig, gpointer *iter); /* * This enumeration is used to describe the data types in the metadata * tables */ enum { MONO_MT_END, /* Sized elements */ MONO_MT_UINT32, MONO_MT_UINT16, MONO_MT_UINT8, /* Index into Blob heap */ MONO_MT_BLOB_IDX, /* Index into String heap */ MONO_MT_STRING_IDX, /* GUID index */ MONO_MT_GUID_IDX, /* Pointer into a table */ MONO_MT_TABLE_IDX, /* HasConstant:Parent pointer (Param, Field or Property) */ MONO_MT_CONST_IDX, /* HasCustomAttribute index. Indexes any table except CustomAttribute */ MONO_MT_HASCAT_IDX, /* CustomAttributeType encoded index */ MONO_MT_CAT_IDX, /* HasDeclSecurity index: TypeDef Method or Assembly */ MONO_MT_HASDEC_IDX, /* Implementation coded index: File, Export AssemblyRef */ MONO_MT_IMPL_IDX, /* HasFieldMarshal coded index: Field or Param table */ MONO_MT_HFM_IDX, /* MemberForwardedIndex: Field or Method */ MONO_MT_MF_IDX, /* TypeDefOrRef coded index: typedef, typeref, typespec */ MONO_MT_TDOR_IDX, /* MemberRefParent coded index: typeref, moduleref, method, memberref, typesepc, typedef */ MONO_MT_MRP_IDX, /* MethodDefOrRef coded index: Method or Member Ref table */ MONO_MT_MDOR_IDX, /* HasSemantic coded index: Event or Property */ MONO_MT_HS_IDX, /* ResolutionScope coded index: Module, ModuleRef, AssemblytRef, TypeRef */ MONO_MT_RS_IDX, /* CustomDebugInformation parent encoded index */ MONO_MT_HASCUSTDEBUG_IDX }; const static unsigned char TableSchemas [] = { #define ASSEMBLY_SCHEMA_OFFSET 0 MONO_MT_UINT32, /* "HashId" }, */ MONO_MT_UINT16, /* "Major" }, */ MONO_MT_UINT16, /* "Minor" }, */ MONO_MT_UINT16, /* "BuildNumber" }, */ MONO_MT_UINT16, /* "RevisionNumber" }, */ MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_BLOB_IDX, /* "PublicKey" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Culture" }, */ MONO_MT_END, #define ASSEMBLYOS_SCHEMA_OFFSET ASSEMBLY_SCHEMA_OFFSET + 10 MONO_MT_UINT32, /* "OSPlatformID" }, */ MONO_MT_UINT32, /* "OSMajor" }, */ MONO_MT_UINT32, /* "OSMinor" }, */ MONO_MT_END, #define ASSEMBLYPROC_SCHEMA_OFFSET ASSEMBLYOS_SCHEMA_OFFSET + 4 MONO_MT_UINT32, /* "Processor" }, */ MONO_MT_END, #define ASSEMBLYREF_SCHEMA_OFFSET ASSEMBLYPROC_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Major" }, */ MONO_MT_UINT16, /* "Minor" }, */ MONO_MT_UINT16, /* "Build" }, */ MONO_MT_UINT16, /* "Revision" }, */ MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_BLOB_IDX, /* "PublicKeyOrToken" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Culture" }, */ MONO_MT_BLOB_IDX, /* "HashValue" }, */ MONO_MT_END, #define ASSEMBLYREFOS_SCHEMA_OFFSET ASSEMBLYREF_SCHEMA_OFFSET + 10 MONO_MT_UINT32, /* "OSPlatformID" }, */ MONO_MT_UINT32, /* "OSMajorVersion" }, */ MONO_MT_UINT32, /* "OSMinorVersion" }, */ MONO_MT_TABLE_IDX, /* "AssemblyRef:AssemblyRef" }, */ MONO_MT_END, #define ASSEMBLYREFPROC_SCHEMA_OFFSET ASSEMBLYREFOS_SCHEMA_OFFSET + 5 MONO_MT_UINT32, /* "Processor" }, */ MONO_MT_TABLE_IDX, /* "AssemblyRef:AssemblyRef" }, */ MONO_MT_END, #define CLASS_LAYOUT_SCHEMA_OFFSET ASSEMBLYREFPROC_SCHEMA_OFFSET + 3 MONO_MT_UINT16, /* "PackingSize" }, */ MONO_MT_UINT32, /* "ClassSize" }, */ MONO_MT_TABLE_IDX, /* "Parent:TypeDef" }, */ MONO_MT_END, #define CONSTANT_SCHEMA_OFFSET CLASS_LAYOUT_SCHEMA_OFFSET + 4 MONO_MT_UINT8, /* "Type" }, */ MONO_MT_UINT8, /* "PaddingZero" }, */ MONO_MT_CONST_IDX, /* "Parent" }, */ MONO_MT_BLOB_IDX, /* "Value" }, */ MONO_MT_END, #define CUSTOM_ATTR_SCHEMA_OFFSET CONSTANT_SCHEMA_OFFSET + 5 MONO_MT_HASCAT_IDX, /* "Parent" }, */ MONO_MT_CAT_IDX, /* "Type" }, */ MONO_MT_BLOB_IDX, /* "Value" }, */ MONO_MT_END, #define DECL_SEC_SCHEMA_OFFSET CUSTOM_ATTR_SCHEMA_OFFSET + 4 MONO_MT_UINT16, /* "Action" }, */ MONO_MT_HASDEC_IDX, /* "Parent" }, */ MONO_MT_BLOB_IDX, /* "PermissionSet" }, */ MONO_MT_END, #define EVENTMAP_SCHEMA_OFFSET DECL_SEC_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Parent:TypeDef" }, */ MONO_MT_TABLE_IDX, /* "EventList:Event" }, */ MONO_MT_END, #define EVENT_SCHEMA_OFFSET EVENTMAP_SCHEMA_OFFSET + 3 MONO_MT_UINT16, /* "EventFlags#EventAttribute" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_TDOR_IDX, /* "EventType" }, TypeDef or TypeRef or TypeSpec */ MONO_MT_END, #define EVENT_POINTER_SCHEMA_OFFSET EVENT_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Event" }, */ MONO_MT_END, #define EXPORTED_TYPE_SCHEMA_OFFSET EVENT_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_TABLE_IDX, /* "TypeDefId" }, */ MONO_MT_STRING_IDX, /* "TypeName" }, */ MONO_MT_STRING_IDX, /* "TypeNameSpace" }, */ MONO_MT_IMPL_IDX, /* "Implementation" }, */ MONO_MT_END, #define FIELD_SCHEMA_OFFSET EXPORTED_TYPE_SCHEMA_OFFSET + 6 MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define FIELD_LAYOUT_SCHEMA_OFFSET FIELD_SCHEMA_OFFSET + 4 MONO_MT_UINT32, /* "Offset" }, */ MONO_MT_TABLE_IDX, /* "Field:Field" }, */ MONO_MT_END, #define FIELD_MARSHAL_SCHEMA_OFFSET FIELD_LAYOUT_SCHEMA_OFFSET + 3 MONO_MT_HFM_IDX, /* "Parent" }, */ MONO_MT_BLOB_IDX, /* "NativeType" }, */ MONO_MT_END, #define FIELD_RVA_SCHEMA_OFFSET FIELD_MARSHAL_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "RVA" }, */ MONO_MT_TABLE_IDX, /* "Field:Field" }, */ MONO_MT_END, #define ENCLOG_SCHEMA_OFFSET FIELD_RVA_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "Token" }, */ MONO_MT_UINT32, /* "FuncCode" }, */ MONO_MT_END, #define ENCMAP_SCHEMA_OFFSET ENCLOG_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "Token" }, */ MONO_MT_END, #define FIELD_POINTER_SCHEMA_OFFSET ENCMAP_SCHEMA_OFFSET + 2 MONO_MT_TABLE_IDX, /* "Field" }, */ MONO_MT_END, #define FILE_SCHEMA_OFFSET FIELD_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Value" }, */ MONO_MT_END, #define IMPLMAP_SCHEMA_OFFSET FILE_SCHEMA_OFFSET + 4 MONO_MT_UINT16, /* "MappingFlag" }, */ MONO_MT_MF_IDX, /* "MemberForwarded" }, */ MONO_MT_STRING_IDX, /* "ImportName" }, */ MONO_MT_TABLE_IDX, /* "ImportScope:ModuleRef" }, */ MONO_MT_END, #define IFACEMAP_SCHEMA_OFFSET IMPLMAP_SCHEMA_OFFSET + 5 MONO_MT_TABLE_IDX, /* "Class:TypeDef" }, */ MONO_MT_TDOR_IDX, /* "Interface=TypeDefOrRef" }, */ MONO_MT_END, #define MANIFEST_SCHEMA_OFFSET IFACEMAP_SCHEMA_OFFSET + 3 MONO_MT_UINT32, /* "Offset" }, */ MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_IMPL_IDX, /* "Implementation" }, */ MONO_MT_END, #define MEMBERREF_SCHEMA_OFFSET MANIFEST_SCHEMA_OFFSET + 5 MONO_MT_MRP_IDX, /* "Class" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define METHOD_SCHEMA_OFFSET MEMBERREF_SCHEMA_OFFSET + 4 MONO_MT_UINT32, /* "RVA" }, */ MONO_MT_UINT16, /* "ImplFlags#MethodImplAttributes" }, */ MONO_MT_UINT16, /* "Flags#MethodAttribute" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_TABLE_IDX, /* "ParamList:Param" }, */ MONO_MT_END, #define METHOD_IMPL_SCHEMA_OFFSET METHOD_SCHEMA_OFFSET + 7 MONO_MT_TABLE_IDX, /* "Class:TypeDef" }, */ MONO_MT_MDOR_IDX, /* "MethodBody" }, */ MONO_MT_MDOR_IDX, /* "MethodDeclaration" }, */ MONO_MT_END, #define METHOD_SEMA_SCHEMA_OFFSET METHOD_IMPL_SCHEMA_OFFSET + 4 MONO_MT_UINT16, /* "MethodSemantic" }, */ MONO_MT_TABLE_IDX, /* "Method:Method" }, */ MONO_MT_HS_IDX, /* "Association" }, */ MONO_MT_END, #define METHOD_POINTER_SCHEMA_OFFSET METHOD_SEMA_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Method" }, */ MONO_MT_END, #define MODULE_SCHEMA_OFFSET METHOD_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Generation" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_GUID_IDX, /* "MVID" }, */ MONO_MT_GUID_IDX, /* "EncID" }, */ MONO_MT_GUID_IDX, /* "EncBaseID" }, */ MONO_MT_END, #define MODULEREF_SCHEMA_OFFSET MODULE_SCHEMA_OFFSET + 6 MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_END, #define NESTED_CLASS_SCHEMA_OFFSET MODULEREF_SCHEMA_OFFSET + 2 MONO_MT_TABLE_IDX, /* "NestedClass:TypeDef" }, */ MONO_MT_TABLE_IDX, /* "EnclosingClass:TypeDef" }, */ MONO_MT_END, #define PARAM_SCHEMA_OFFSET NESTED_CLASS_SCHEMA_OFFSET + 3 MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_UINT16, /* "Sequence" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_END, #define PARAM_POINTER_SCHEMA_OFFSET PARAM_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Param" }, */ MONO_MT_END, #define PROPERTY_SCHEMA_OFFSET PARAM_POINTER_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_BLOB_IDX, /* "Type" }, */ MONO_MT_END, #define PROPERTY_POINTER_SCHEMA_OFFSET PROPERTY_SCHEMA_OFFSET + 4 MONO_MT_TABLE_IDX, /* "Property" }, */ MONO_MT_END, #define PROPERTY_MAP_SCHEMA_OFFSET PROPERTY_POINTER_SCHEMA_OFFSET + 2 MONO_MT_TABLE_IDX, /* "Parent:TypeDef" }, */ MONO_MT_TABLE_IDX, /* "PropertyList:Property" }, */ MONO_MT_END, #define STDALON_SIG_SCHEMA_OFFSET PROPERTY_MAP_SCHEMA_OFFSET + 3 MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define TYPEDEF_SCHEMA_OFFSET STDALON_SIG_SCHEMA_OFFSET + 2 MONO_MT_UINT32, /* "Flags" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Namespace" }, */ MONO_MT_TDOR_IDX, /* "Extends" }, */ MONO_MT_TABLE_IDX, /* "FieldList:Field" }, */ MONO_MT_TABLE_IDX, /* "MethodList:Method" }, */ MONO_MT_END, #define TYPEREF_SCHEMA_OFFSET TYPEDEF_SCHEMA_OFFSET + 7 MONO_MT_RS_IDX, /* "ResolutionScope=ResolutionScope" }, */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_STRING_IDX, /* "Namespace" }, */ MONO_MT_END, #define TYPESPEC_SCHEMA_OFFSET TYPEREF_SCHEMA_OFFSET + 4 MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define GENPARAM_SCHEMA_OFFSET TYPESPEC_SCHEMA_OFFSET + 2 MONO_MT_UINT16, /* "Number" }, */ MONO_MT_UINT16, /* "Flags" }, */ MONO_MT_TABLE_IDX, /* "Owner" }, TypeDef or MethodDef */ MONO_MT_STRING_IDX, /* "Name" }, */ MONO_MT_END, #define METHOD_SPEC_SCHEMA_OFFSET GENPARAM_SCHEMA_OFFSET + 5 MONO_MT_MDOR_IDX, /* "Method" }, */ MONO_MT_BLOB_IDX, /* "Signature" }, */ MONO_MT_END, #define GEN_CONSTRAINT_SCHEMA_OFFSET METHOD_SPEC_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* "GenericParam" }, */ MONO_MT_TDOR_IDX, /* "Constraint" }, */ MONO_MT_END, #define DOCUMENT_SCHEMA_OFFSET GEN_CONSTRAINT_SCHEMA_OFFSET + 3 MONO_MT_BLOB_IDX, /* Name */ MONO_MT_GUID_IDX, /* HashAlgorithm */ MONO_MT_BLOB_IDX, /* Hash */ MONO_MT_GUID_IDX, /* Language */ MONO_MT_END, #define METHODBODY_SCHEMA_OFFSET DOCUMENT_SCHEMA_OFFSET + 5 MONO_MT_TABLE_IDX, /* Document */ MONO_MT_BLOB_IDX, /* SequencePoints */ MONO_MT_END, #define LOCALSCOPE_SCHEMA_OFFSET METHODBODY_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* Method */ MONO_MT_TABLE_IDX, /* ImportScope */ MONO_MT_TABLE_IDX, /* VariableList */ MONO_MT_TABLE_IDX, /* ConstantList */ MONO_MT_UINT32, /* StartOffset */ MONO_MT_UINT32, /* Length */ MONO_MT_END, #define LOCALVARIABLE_SCHEMA_OFFSET LOCALSCOPE_SCHEMA_OFFSET + 7 MONO_MT_UINT16, /* Attributes */ MONO_MT_UINT16, /* Index */ MONO_MT_STRING_IDX, /* Name */ MONO_MT_END, #define LOCALCONSTANT_SCHEMA_OFFSET LOCALVARIABLE_SCHEMA_OFFSET + 4 MONO_MT_STRING_IDX, /* Name (String heap index) */ MONO_MT_BLOB_IDX, /* Signature (Blob heap index, LocalConstantSig blob) */ MONO_MT_END, #define IMPORTSCOPE_SCHEMA_OFFSET LOCALCONSTANT_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* Parent (ImportScope row id or nil) */ MONO_MT_BLOB_IDX, /* Imports (Blob index, encoding: Imports blob) */ MONO_MT_END, #define ASYNCMETHOD_SCHEMA_OFFSET IMPORTSCOPE_SCHEMA_OFFSET + 3 MONO_MT_TABLE_IDX, /* MoveNextMethod (MethodDef row id) */ MONO_MT_TABLE_IDX, /* KickoffMethod (MethodDef row id) */ MONO_MT_END, #define CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET ASYNCMETHOD_SCHEMA_OFFSET + 3 MONO_MT_HASCUSTDEBUG_IDX, /* Parent (HasCustomDebugInformation coded index) */ MONO_MT_GUID_IDX, /* Kind (Guid heap index) */ MONO_MT_BLOB_IDX, /* Value (Blob heap index) */ MONO_MT_END, #define NULL_SCHEMA_OFFSET CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET + 4 MONO_MT_END }; /* Must be the same order as MONO_TABLE_* */ const static unsigned char table_description [] = { MODULE_SCHEMA_OFFSET, TYPEREF_SCHEMA_OFFSET, TYPEDEF_SCHEMA_OFFSET, FIELD_POINTER_SCHEMA_OFFSET, FIELD_SCHEMA_OFFSET, METHOD_POINTER_SCHEMA_OFFSET, METHOD_SCHEMA_OFFSET, PARAM_POINTER_SCHEMA_OFFSET, PARAM_SCHEMA_OFFSET, IFACEMAP_SCHEMA_OFFSET, MEMBERREF_SCHEMA_OFFSET, /* 0xa */ CONSTANT_SCHEMA_OFFSET, CUSTOM_ATTR_SCHEMA_OFFSET, FIELD_MARSHAL_SCHEMA_OFFSET, DECL_SEC_SCHEMA_OFFSET, CLASS_LAYOUT_SCHEMA_OFFSET, FIELD_LAYOUT_SCHEMA_OFFSET, /* 0x10 */ STDALON_SIG_SCHEMA_OFFSET, EVENTMAP_SCHEMA_OFFSET, EVENT_POINTER_SCHEMA_OFFSET, EVENT_SCHEMA_OFFSET, PROPERTY_MAP_SCHEMA_OFFSET, PROPERTY_POINTER_SCHEMA_OFFSET, PROPERTY_SCHEMA_OFFSET, METHOD_SEMA_SCHEMA_OFFSET, METHOD_IMPL_SCHEMA_OFFSET, MODULEREF_SCHEMA_OFFSET, /* 0x1a */ TYPESPEC_SCHEMA_OFFSET, IMPLMAP_SCHEMA_OFFSET, FIELD_RVA_SCHEMA_OFFSET, ENCLOG_SCHEMA_OFFSET, ENCMAP_SCHEMA_OFFSET, ASSEMBLY_SCHEMA_OFFSET, /* 0x20 */ ASSEMBLYPROC_SCHEMA_OFFSET, ASSEMBLYOS_SCHEMA_OFFSET, ASSEMBLYREF_SCHEMA_OFFSET, ASSEMBLYREFPROC_SCHEMA_OFFSET, ASSEMBLYREFOS_SCHEMA_OFFSET, FILE_SCHEMA_OFFSET, EXPORTED_TYPE_SCHEMA_OFFSET, MANIFEST_SCHEMA_OFFSET, NESTED_CLASS_SCHEMA_OFFSET, GENPARAM_SCHEMA_OFFSET, /* 0x2a */ METHOD_SPEC_SCHEMA_OFFSET, GEN_CONSTRAINT_SCHEMA_OFFSET, NULL_SCHEMA_OFFSET, NULL_SCHEMA_OFFSET, NULL_SCHEMA_OFFSET, DOCUMENT_SCHEMA_OFFSET, /* 0x30 */ METHODBODY_SCHEMA_OFFSET, LOCALSCOPE_SCHEMA_OFFSET, LOCALVARIABLE_SCHEMA_OFFSET, LOCALCONSTANT_SCHEMA_OFFSET, IMPORTSCOPE_SCHEMA_OFFSET, ASYNCMETHOD_SCHEMA_OFFSET, CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET }; // This, instead of an array of pointers, to optimize away a pointer and a relocation per string. #define MSGSTRFIELD(line) MSGSTRFIELD1(line) #define MSGSTRFIELD1(line) str##line static const struct msgstr_t { #define TABLEDEF(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)]; #include "mono/cil/tables.def" #undef TABLEDEF } tablestr = { #define TABLEDEF(a,b) b, #include "mono/cil/tables.def" #undef TABLEDEF }; static const gint16 tableidx [] = { #define TABLEDEF(a,b) offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)), #include "mono/cil/tables.def" #undef TABLEDEF }; /* On legacy, if TRUE (but also see DISABLE_DESKTOP_LOADER #define), Mono will check * that the public key token, culture and version of a candidate assembly matches * the requested strong name. On netcore, it will check the culture and version. * If FALSE, as long as the name matches, the candidate will be allowed. */ static gboolean check_assembly_names_strictly = FALSE; // Amount initially reserved in each imageset's mempool. // FIXME: This number is arbitrary, a more practical number should be found #define INITIAL_IMAGE_SET_SIZE 1024 /** * mono_meta_table_name: * \param table table index * * Returns the name of the given ECMA metadata logical format table * as described in ECMA 335, Partition II, Section 22. * * \returns the name for the \p table index */ const char * mono_meta_table_name (int table) { if ((table < 0) || (table > MONO_TABLE_LAST)) return ""; return (const char*)&tablestr + tableidx [table]; } /* The guy who wrote the spec for this should not be allowed near a * computer again. If e is a coded token(see clause 23.1.7) that points into table ti out of n possible tables t0, .. tn-1, then it is stored as e << (log n) & tag{ t0, .. tn-1}[ ti] using 2 bytes if the maximum number of rows of tables t0, ..tn-1, is less than 2^16 - (log n), and using 4 bytes otherwise. The family of finite maps tag{ t0, ..tn-1} is defined below. Note that to decode a physical row, you need the inverse of this mapping. */ static int rtsize (MonoImage *meta, int sz, int bits) { if (G_UNLIKELY (meta->minimal_delta)) return 4; if (sz < (1 << bits)) return 2; else return 4; } static int idx_size (MonoImage *meta, int idx) { if (G_UNLIKELY (meta->minimal_delta)) return 4; if (meta->referenced_tables && (meta->referenced_tables & ((guint64)1 << idx))) return meta->referenced_table_rows [idx] < 65536 ? 2 : 4; else return table_info_get_rows (&meta->tables [idx]) < 65536 ? 2 : 4; } static int get_nrows (MonoImage *meta, int idx) { if (meta->referenced_tables && (meta->referenced_tables & ((guint64)1 << idx))) return meta->referenced_table_rows [idx]; else return table_info_get_rows (&meta->tables [idx]); } /* Reference: Partition II - 23.2.6 */ /** * mono_metadata_compute_size: * \param meta metadata context * \param tableindex metadata table number * \param result_bitfield pointer to \c guint32 where to store additional info * * \c mono_metadata_compute_size computes the length in bytes of a single * row in a metadata table. The size of each column is encoded in the * \p result_bitfield return value along with the number of columns in the table. * the resulting bitfield should be handed to the \c mono_metadata_table_size * and \c mono_metadata_table_count macros. * This is a Mono runtime internal only function. */ int mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bitfield) { guint32 bitfield = 0; int size = 0, field_size = 0; int i, n, code; int shift = 0; const unsigned char *description = TableSchemas + table_description [tableindex]; for (i = 0; (code = description [i]) != MONO_MT_END; i++){ switch (code){ case MONO_MT_UINT32: field_size = 4; break; case MONO_MT_UINT16: field_size = 2; break; case MONO_MT_UINT8: field_size = 1; break; case MONO_MT_BLOB_IDX: field_size = meta->idx_blob_wide ? 4 : 2; break; case MONO_MT_STRING_IDX: field_size = meta->idx_string_wide ? 4 : 2; break; case MONO_MT_GUID_IDX: field_size = meta->idx_guid_wide ? 4 : 2; break; case MONO_MT_TABLE_IDX: /* Uhm, a table index can point to other tables besides the current one * so, it's not correct to use the rowcount of the current table to * get the size for this column - lupus */ switch (tableindex) { case MONO_TABLE_ASSEMBLYREFOS: g_assert (i == 3); field_size = idx_size (meta, MONO_TABLE_ASSEMBLYREF); break; case MONO_TABLE_ASSEMBLYREFPROCESSOR: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_ASSEMBLYREF); break; case MONO_TABLE_CLASSLAYOUT: g_assert (i == 2); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_EVENTMAP: g_assert (i == 0 || i == 1); field_size = i ? idx_size (meta, MONO_TABLE_EVENT): idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_EVENT_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_EVENT); break; case MONO_TABLE_EXPORTEDTYPE: g_assert (i == 1); /* the index is in another metadata file, so it must be 4 */ field_size = 4; break; case MONO_TABLE_FIELDLAYOUT: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_FIELD); break; case MONO_TABLE_FIELDRVA: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_FIELD); break; case MONO_TABLE_FIELD_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_FIELD); break; case MONO_TABLE_IMPLMAP: g_assert (i == 3); field_size = idx_size (meta, MONO_TABLE_MODULEREF); break; case MONO_TABLE_INTERFACEIMPL: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_METHOD: g_assert (i == 5); field_size = idx_size (meta, MONO_TABLE_PARAM); break; case MONO_TABLE_METHODIMPL: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_METHODSEMANTICS: g_assert (i == 1); field_size = idx_size (meta, MONO_TABLE_METHOD); break; case MONO_TABLE_METHOD_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_METHOD); break; case MONO_TABLE_NESTEDCLASS: g_assert (i == 0 || i == 1); field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_PARAM_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_PARAM); break; case MONO_TABLE_PROPERTYMAP: g_assert (i == 0 || i == 1); field_size = i ? idx_size (meta, MONO_TABLE_PROPERTY): idx_size (meta, MONO_TABLE_TYPEDEF); break; case MONO_TABLE_PROPERTY_POINTER: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_PROPERTY); break; case MONO_TABLE_TYPEDEF: g_assert (i == 4 || i == 5); field_size = i == 4 ? idx_size (meta, MONO_TABLE_FIELD): idx_size (meta, MONO_TABLE_METHOD); break; case MONO_TABLE_GENERICPARAM: g_assert (i == 2); n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_TYPEDEF)); /*This is a coded token for 2 tables, so takes 1 bit */ field_size = rtsize (meta, n, 16 - MONO_TYPEORMETHOD_BITS); break; case MONO_TABLE_GENERICPARAMCONSTRAINT: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_GENERICPARAM); break; case MONO_TABLE_LOCALSCOPE: switch (i) { case 0: // FIXME: This table is in another file field_size = idx_size (meta, MONO_TABLE_METHOD); break; case 1: field_size = idx_size (meta, MONO_TABLE_IMPORTSCOPE); break; case 2: field_size = idx_size (meta, MONO_TABLE_LOCALVARIABLE); break; case 3: field_size = idx_size (meta, MONO_TABLE_LOCALCONSTANT); break; default: g_assert_not_reached (); break; } break; case MONO_TABLE_METHODBODY: g_assert (i == 0); field_size = idx_size (meta, MONO_TABLE_DOCUMENT); break; case MONO_TABLE_IMPORTSCOPE: g_assert(i == 0); field_size = idx_size (meta, MONO_TABLE_IMPORTSCOPE); break; case MONO_TABLE_STATEMACHINEMETHOD: g_assert(i == 0 || i == 1); field_size = idx_size(meta, MONO_TABLE_METHOD); break; default: g_error ("Can't handle MONO_MT_TABLE_IDX for table %d element %d", tableindex, i); } break; /* * HasConstant: ParamDef, FieldDef, Property */ case MONO_MT_CONST_IDX: n = MAX (get_nrows (meta, MONO_TABLE_PARAM), get_nrows (meta, MONO_TABLE_FIELD)); n = MAX (n, get_nrows (meta, MONO_TABLE_PROPERTY)); /* 2 bits to encode tag */ field_size = rtsize (meta, n, 16-2); break; /* * HasCustomAttribute: points to any table but * itself. */ case MONO_MT_HASCAT_IDX: /* * We believe that since the signature and * permission are indexing the Blob heap, * we should consider the blob size first */ /* I'm not a believer - lupus if (meta->idx_blob_wide){ field_size = 4; break; }*/ n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_FIELD)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEDEF)); n = MAX (n, get_nrows (meta, MONO_TABLE_PARAM)); n = MAX (n, get_nrows (meta, MONO_TABLE_INTERFACEIMPL)); n = MAX (n, get_nrows (meta, MONO_TABLE_MEMBERREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_MODULE)); n = MAX (n, get_nrows (meta, MONO_TABLE_DECLSECURITY)); n = MAX (n, get_nrows (meta, MONO_TABLE_PROPERTY)); n = MAX (n, get_nrows (meta, MONO_TABLE_EVENT)); n = MAX (n, get_nrows (meta, MONO_TABLE_STANDALONESIG)); n = MAX (n, get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLY)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_FILE)); n = MAX (n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE)); n = MAX (n, get_nrows (meta, MONO_TABLE_MANIFESTRESOURCE)); n = MAX (n, get_nrows (meta, MONO_TABLE_GENERICPARAM)); n = MAX (n, get_nrows (meta, MONO_TABLE_GENERICPARAMCONSTRAINT)); n = MAX (n, get_nrows (meta, MONO_TABLE_METHODSPEC)); /* 5 bits to encode */ field_size = rtsize (meta, n, 16-5); break; /* * HasCustomAttribute: points to any table but * itself. */ case MONO_MT_HASCUSTDEBUG_IDX: n = MAX(get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_FIELD)); n = MAX(n, get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_TYPEDEF)); n = MAX(n, get_nrows (meta, MONO_TABLE_PARAM)); n = MAX(n, get_nrows (meta, MONO_TABLE_INTERFACEIMPL)); n = MAX(n, get_nrows (meta, MONO_TABLE_MEMBERREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_MODULE)); n = MAX(n, get_nrows (meta, MONO_TABLE_DECLSECURITY)); n = MAX(n, get_nrows (meta, MONO_TABLE_PROPERTY)); n = MAX(n, get_nrows (meta, MONO_TABLE_EVENT)); n = MAX(n, get_nrows (meta, MONO_TABLE_STANDALONESIG)); n = MAX(n, get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_TYPESPEC)); n = MAX(n, get_nrows (meta, MONO_TABLE_ASSEMBLY)); n = MAX(n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX(n, get_nrows (meta, MONO_TABLE_FILE)); n = MAX(n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE)); n = MAX(n, get_nrows (meta, MONO_TABLE_MANIFESTRESOURCE)); n = MAX(n, get_nrows (meta, MONO_TABLE_GENERICPARAM)); n = MAX(n, get_nrows (meta, MONO_TABLE_GENERICPARAMCONSTRAINT)); n = MAX(n, get_nrows (meta, MONO_TABLE_METHODSPEC)); n = MAX(n, get_nrows (meta, MONO_TABLE_DOCUMENT)); n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALSCOPE)); n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALVARIABLE)); n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALCONSTANT)); n = MAX(n, get_nrows (meta, MONO_TABLE_IMPORTSCOPE)); /* 5 bits to encode */ field_size = rtsize(meta, n, 16 - 5); break; /* * CustomAttributeType: MethodDef, MemberRef. */ case MONO_MT_CAT_IDX: n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_MEMBERREF)); /* 3 bits to encode */ field_size = rtsize (meta, n, 16-3); break; /* * HasDeclSecurity: Typedef, MethodDef, Assembly */ case MONO_MT_HASDEC_IDX: n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF), get_nrows (meta, MONO_TABLE_METHOD)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLY)); /* 2 bits to encode */ field_size = rtsize (meta, n, 16-2); break; /* * Implementation: File, AssemblyRef, ExportedType */ case MONO_MT_IMPL_IDX: n = MAX (get_nrows (meta, MONO_TABLE_FILE), get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE)); /* 2 bits to encode tag */ field_size = rtsize (meta, n, 16-2); break; /* * HasFieldMarshall: FieldDef, ParamDef */ case MONO_MT_HFM_IDX: n = MAX (get_nrows (meta, MONO_TABLE_FIELD), get_nrows (meta, MONO_TABLE_PARAM)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * MemberForwarded: FieldDef, MethodDef */ case MONO_MT_MF_IDX: n = MAX (get_nrows (meta, MONO_TABLE_FIELD), get_nrows (meta, MONO_TABLE_METHOD)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * TypeDefOrRef: TypeDef, ParamDef, TypeSpec * LAMESPEC * It is TypeDef, _TypeRef_, TypeSpec, instead. */ case MONO_MT_TDOR_IDX: n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF), get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC)); /* 2 bits to encode */ field_size = rtsize (meta, n, 16-2); break; /* * MemberRefParent: TypeDef, TypeRef, MethodDef, ModuleRef, TypeSpec, MemberRef */ case MONO_MT_MRP_IDX: n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF), get_nrows (meta, MONO_TABLE_TYPEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_METHOD)); n = MAX (n, get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC)); /* 3 bits to encode */ field_size = rtsize (meta, n, 16 - 3); break; /* * MethodDefOrRef: MethodDef, MemberRef */ case MONO_MT_MDOR_IDX: n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_MEMBERREF)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * HasSemantics: Property, Event */ case MONO_MT_HS_IDX: n = MAX (get_nrows (meta, MONO_TABLE_PROPERTY), get_nrows (meta, MONO_TABLE_EVENT)); /* 1 bit used to encode tag */ field_size = rtsize (meta, n, 16-1); break; /* * ResolutionScope: Module, ModuleRef, AssemblyRef, TypeRef */ case MONO_MT_RS_IDX: n = MAX (get_nrows (meta, MONO_TABLE_MODULE), get_nrows (meta, MONO_TABLE_MODULEREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF)); n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEREF)); /* 2 bits used to encode tag (ECMA spec claims 3) */ field_size = rtsize (meta, n, 16 - 2); break; } /* * encode field size as follows (we just need to * distinguish them). * * 4 -> 3 * 2 -> 1 * 1 -> 0 */ bitfield |= (field_size-1) << shift; shift += 2; size += field_size; /*g_print ("table %02x field %d size %d\n", tableindex, i, field_size);*/ } *result_bitfield = (i << 24) | bitfield; return size; } /* returns true if given index is not in bounds with provided table/index pair */ gboolean mono_metadata_table_bounds_check_slow (MonoImage *image, int table_index, int token_index) { if (G_LIKELY (token_index <= table_info_get_rows (&image->tables [table_index]))) return FALSE; if (G_LIKELY (!image->has_updates)) return TRUE; return mono_metadata_update_table_bounds_check (image, table_index, token_index); } /** * mono_metadata_compute_table_bases: * \param meta metadata context to compute table values * * Computes the table bases for the metadata structure. * This is an internal function used by the image loader code. */ void mono_metadata_compute_table_bases (MonoImage *meta) { int i; const char *base = meta->tables_base; for (i = 0; i < MONO_TABLE_NUM; i++) { MonoTableInfo *table = &meta->tables [i]; if (table_info_get_rows (table) == 0) continue; table->row_size = mono_metadata_compute_size (meta, i, &table->size_bitfield); table->base = base; base += table_info_get_rows (table) * table->row_size; } } /** * mono_metadata_locate: * \param meta metadata context * \param table table code. * \param idx index of element to retrieve from \p table. * * \returns a pointer to the \p idx element in the metadata table * whose code is \p table. */ const char * mono_metadata_locate (MonoImage *meta, int table, int idx) { /* FIXME: metadata-update */ /* idx == 0 refers always to NULL */ g_return_val_if_fail (idx > 0 && idx <= table_info_get_rows (&meta->tables [table]), ""); /*FIXME shouldn't we return NULL here?*/ return meta->tables [table].base + (meta->tables [table].row_size * (idx - 1)); } /** * mono_metadata_locate_token: * \param meta metadata context * \param token metadata token * * \returns a pointer to the data in the metadata represented by the * token \p token . */ const char * mono_metadata_locate_token (MonoImage *meta, guint32 token) { return mono_metadata_locate (meta, token >> 24, token & 0xffffff); } static MonoStreamHeader * get_string_heap (MonoImage *image) { return &image->heap_strings; } static MonoStreamHeader * get_user_string_heap (MonoImage *image) { return &image->heap_us; } static MonoStreamHeader * get_blob_heap (MonoImage *image) { return &image->heap_blob; } static gboolean mono_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, guint32 orig_index, MonoImage **image_out, guint32 *index_out) { return mono_metadata_update_delta_heap_lookup (base_image, get_heap, orig_index, image_out, index_out); } /** * mono_metadata_string_heap: * \param meta metadata context * \param index index into the string heap. * \returns an in-memory pointer to the \p index in the string heap. */ const char * mono_metadata_string_heap (MonoImage *meta, guint32 index) { if (G_UNLIKELY (index >= meta->heap_strings.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_string_heap, index, &dmeta, &dindex); g_assertf (ok, "Could not find token=0x%08x in string heap of assembly=%s and its delta images", index, meta && meta->name ? meta->name : "unknown image"); meta = dmeta; index = dindex; } g_assertf (index < meta->heap_strings.size, " index = 0x%08x size = 0x%08x meta=%s ", index, meta->heap_strings.size, meta && meta->name ? meta->name : "unknown image" ); g_return_val_if_fail (index < meta->heap_strings.size, ""); return meta->heap_strings.data + index; } /** * mono_metadata_string_heap_checked: * \param meta metadata context * \param index index into the string heap. * \param error set on error * \returns an in-memory pointer to the \p index in the string heap. * On failure returns NULL and sets \p error. */ const char * mono_metadata_string_heap_checked (MonoImage *meta, guint32 index, MonoError *error) { if (mono_image_is_dynamic (meta)) { MonoDynamicImage* img = (MonoDynamicImage*) meta; const char *image_name = meta && meta->name ? meta->name : "unknown image"; if (G_UNLIKELY (!(index < img->sheap.index))) { mono_error_set_bad_image_by_name (error, image_name, "string heap index %ud out bounds %u: %s", index, img->sheap.index, image_name); return NULL; } return img->sheap.data + index; } if (G_UNLIKELY (index >= meta->heap_strings.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_string_heap, index, &dmeta, &dindex); if (G_UNLIKELY (!ok)) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "string heap index %ud out bounds %u: %s, also checked delta images", index, meta->heap_strings.size, image_name); return NULL; } meta = dmeta; index = dindex; } if (G_UNLIKELY (!(index < meta->heap_strings.size))) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "string heap index %ud out bounds %u: %s", index, meta->heap_strings.size, image_name); return NULL; } return meta->heap_strings.data + index; } /** * mono_metadata_user_string: * \param meta metadata context * \param index index into the user string heap. * \returns an in-memory pointer to the \p index in the user string heap (<code>#US</code>). */ const char * mono_metadata_user_string (MonoImage *meta, guint32 index) { if (G_UNLIKELY (index >= meta->heap_us.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_user_string_heap, index, &dmeta, &dindex); g_assertf (ok, "Could not find token=0x%08x in user string heap of assembly=%s and its delta images", index, meta && meta->name ? meta->name : "unknown image"); meta = dmeta; index = dindex; } g_assert (index < meta->heap_us.size); g_return_val_if_fail (index < meta->heap_us.size, ""); return meta->heap_us.data + index; } /** * mono_metadata_blob_heap: * \param meta metadata context * \param index index into the blob. * \returns an in-memory pointer to the \p index in the Blob heap. */ const char * mono_metadata_blob_heap (MonoImage *meta, guint32 index) { /* Some tools can produce assemblies with a size 0 Blob stream. If a * blob value is optional, if the index == 0 and heap_blob.size == 0 * assertion is hit, consider updating caller to use * mono_metadata_blob_heap_null_ok and handling a null return value. */ g_assert (!(index == 0 && meta->heap_blob.size == 0)); if (G_UNLIKELY (index >= meta->heap_blob.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_blob_heap, index, &dmeta, &dindex); g_assertf (ok, "Could not find token=0x%08x in blob heap of assembly=%s and its delta images", index, meta && meta->name ? meta->name : "unknown image"); meta = dmeta; index = dindex; } g_assert (index < meta->heap_blob.size); return meta->heap_blob.data + index; } /** * mono_metadata_blob_heap_null_ok: * \param meta metadata context * \param index index into the blob. * \return an in-memory pointer to the \p index in the Blob heap. * If the Blob heap is empty or missing and index is 0 returns NULL, instead of asserting. */ const char * mono_metadata_blob_heap_null_ok (MonoImage *meta, guint32 index) { if (G_UNLIKELY (index == 0 && meta->heap_blob.size == 0)) return NULL; else return mono_metadata_blob_heap (meta, index); } /** * mono_metadata_blob_heap_checked: * \param meta metadata context * \param index index into the blob. * \param error set on error * \returns an in-memory pointer to the \p index in the Blob heap. On failure sets \p error and returns NULL; * If the Blob heap is empty or missing and \p index is 0 returns NULL, without setting error. * */ const char * mono_metadata_blob_heap_checked (MonoImage *meta, guint32 index, MonoError *error) { if (mono_image_is_dynamic (meta)) { MonoDynamicImage* img = (MonoDynamicImage*) meta; const char *image_name = meta && meta->name ? meta->name : "unknown image"; if (G_UNLIKELY (!(index < img->blob.index))) { mono_error_set_bad_image_by_name (error, image_name, "blob heap index %u out of bounds %u: %s", index, img->blob.index, image_name); return NULL; } if (G_UNLIKELY (index == 0 && img->blob.alloc_size == 0)) return NULL; return img->blob.data + index; } if (G_UNLIKELY (index == 0 && meta->heap_blob.size == 0)) return NULL; if (G_UNLIKELY (index >= meta->heap_blob.size && meta->has_updates)) { MonoImage *dmeta; guint32 dindex; gboolean ok = mono_delta_heap_lookup (meta, &get_blob_heap, index, &dmeta, &dindex); if (G_UNLIKELY(!ok)) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "Could not find token=0x%08x in blob heap of assembly=%s and its delta images", index, image_name); return NULL; } meta = dmeta; index = dindex; } if (G_UNLIKELY (!(index < meta->heap_blob.size))) { const char *image_name = meta && meta->name ? meta->name : "unknown image"; mono_error_set_bad_image_by_name (error, image_name, "blob heap index %u out of bounds %u: %s", index, meta->heap_blob.size, image_name); return NULL; } return meta->heap_blob.data + index; } /** * mono_metadata_guid_heap: * \param meta metadata context * \param index index into the guid heap. * \returns an in-memory pointer to the \p index in the guid heap. */ const char * mono_metadata_guid_heap (MonoImage *meta, guint32 index) { /* EnC TODO: lookup in DeltaInfo:delta_image_last. Unlike the other heaps, the GUID heaps are always full in every delta, even in minimal delta images. */ --index; index *= 16; /* adjust for guid size and 1-based index */ g_return_val_if_fail (index < meta->heap_guid.size, ""); return meta->heap_guid.data + index; } static const unsigned char * dword_align (const unsigned char *ptr) { return (const unsigned char *) (((gsize) (ptr + 3)) & ~3); } static void mono_metadata_decode_row_slow (const MonoTableInfo *t, int idx, guint32 *res, int res_size); /** * mono_metadata_decode_row: * \param t table to extract information from. * \param idx index in table. * \param res array of \p res_size cols to store the results in * * This decompresses the metadata element \p idx in table \p t * into the \c guint32 \p res array that has \p res_size elements */ void mono_metadata_decode_row (const MonoTableInfo *t, int idx, guint32 *res, int res_size) { if (G_UNLIKELY (mono_metadata_has_updates ())) { mono_metadata_decode_row_slow (t, idx, res, res_size); } else { mono_metadata_decode_row_raw (t, idx, res, res_size); } } void mono_metadata_decode_row_slow (const MonoTableInfo *t, int idx, guint32 *res, int res_size) { mono_image_effective_table (&t, idx); mono_metadata_decode_row_raw (t, idx, res, res_size); } /** * same as mono_metadata_decode_row, but ignores potential delta images */ void mono_metadata_decode_row_raw (const MonoTableInfo *t, int idx, guint32 *res, int res_size) { guint32 bitfield = t->size_bitfield; int i, count = mono_metadata_table_count (bitfield); const char *data; g_assert (idx < table_info_get_rows (t)); g_assert (idx >= 0); data = t->base + idx * t->row_size; g_assert (res_size == count); for (i = 0; i < count; i++) { int n = mono_metadata_table_size (bitfield, i); switch (n){ case 1: res [i] = *data; break; case 2: res [i] = read16 (data); break; case 4: res [i] = read32 (data); break; default: g_assert_not_reached (); } data += n; } } /** * mono_metadata_decode_row_checked: * \param image the \c MonoImage the table belongs to * \param t table to extract information from. * \param idx index in the table. * \param res array of \p res_size cols to store the results in * \param error set on bounds error * * * This decompresses the metadata element \p idx in the table \p t * into the \c guint32 \p res array that has \p res_size elements. * * \returns TRUE if the read succeeded. Otherwise sets \p error and returns FALSE. */ gboolean mono_metadata_decode_row_checked (const MonoImage *image, const MonoTableInfo *t, int idx, guint32 *res, int res_size, MonoError *error) { const char *image_name = image && image->name ? image->name : "unknown image"; mono_image_effective_table (&t, idx); guint32 bitfield = t->size_bitfield; int i, count = mono_metadata_table_count (bitfield); if (G_UNLIKELY (! (idx < table_info_get_rows (t) && idx >= 0))) { mono_error_set_bad_image_by_name (error, image_name, "row index %d out of bounds: %d rows: %s", idx, table_info_get_rows (t), image_name); return FALSE; } const char *data = t->base + idx * t->row_size; if (G_UNLIKELY (res_size != count)) { mono_error_set_bad_image_by_name (error, image_name, "res_size %d != count %d: %s", res_size, count, image_name); return FALSE; } for (i = 0; i < count; i++) { int n = mono_metadata_table_size (bitfield, i); switch (n) { case 1: res [i] = *data; break; case 2: res [i] = read16 (data); break; case 4: res [i] = read32 (data); break; default: mono_error_set_bad_image_by_name (error, image_name, "unexpected table [%d] size %d: %s", i, n, image_name); return FALSE; } data += n; } return TRUE; } gboolean mono_metadata_decode_row_dynamic_checked (const MonoDynamicImage *image, const MonoDynamicTable *t, int idx, guint32 *res, int res_size, MonoError *error) { int i, count = t->columns; const char *image_name = image && image->image.name ? image->image.name : "unknown image"; if (G_UNLIKELY (! (idx < t->rows && idx >= 0))) { mono_error_set_bad_image_by_name (error, image_name, "row index %d out of bounds: %d rows: %s", idx, t->rows, image_name); return FALSE; } guint32 *data = t->values + (idx + 1) * count; if (G_UNLIKELY (res_size != count)) { mono_error_set_bad_image_by_name (error, image_name, "res_size %d != count %d: %s", res_size, count, image_name); return FALSE; } for (i = 0; i < count; i++) { res [i] = *data; data++; } return TRUE; } static guint32 mono_metadata_decode_row_col_raw (const MonoTableInfo *t, int idx, guint col); static guint32 mono_metadata_decode_row_col_slow (const MonoTableInfo *t, int idx, guint col); /** * mono_metadata_decode_row_col: * \param t table to extract information from. * \param idx index for row in table. * \param col column in the row. * * This function returns the value of column \p col from the \p idx * row in the table \p t . */ guint32 mono_metadata_decode_row_col (const MonoTableInfo *t, int idx, guint col) { if (G_UNLIKELY (mono_metadata_has_updates ())) { return mono_metadata_decode_row_col_slow (t, idx, col); } else { return mono_metadata_decode_row_col_raw (t, idx, col); } } guint32 mono_metadata_decode_row_col_slow (const MonoTableInfo *t, int idx, guint col) { mono_image_effective_table (&t, idx); return mono_metadata_decode_row_col_raw (t, idx, col); } /** * mono_metadata_decode_row_col_raw: * * Same as \c mono_metadata_decode_row_col but doesn't look for the effective * table on metadata updates. */ guint32 mono_metadata_decode_row_col_raw (const MonoTableInfo *t, int idx, guint col) { int i; const char *data; int n; guint32 bitfield = t->size_bitfield; g_assert (idx < table_info_get_rows (t)); g_assert (col < mono_metadata_table_count (bitfield)); data = t->base + idx * t->row_size; n = mono_metadata_table_size (bitfield, 0); for (i = 0; i < col; ++i) { data += n; n = mono_metadata_table_size (bitfield, i + 1); } switch (n) { case 1: return *data; case 2: return read16 (data); case 4: return read32 (data); default: g_assert_not_reached (); } return 0; } /** * mono_metadata_decode_blob_size: * \param ptr pointer to a blob object * \param rptr the new position of the pointer * * This decodes a compressed size as described by 24.2.4 (#US and #Blob a blob or user string object) * * \returns the size of the blob object */ guint32 mono_metadata_decode_blob_size (const char *xptr, const char **rptr) { const unsigned char *ptr = (const unsigned char *)xptr; guint32 size; if ((*ptr & 0x80) == 0){ size = ptr [0] & 0x7f; ptr++; } else if ((*ptr & 0x40) == 0){ size = ((ptr [0] & 0x3f) << 8) + ptr [1]; ptr += 2; } else { size = ((ptr [0] & 0x1f) << 24) + (ptr [1] << 16) + (ptr [2] << 8) + ptr [3]; ptr += 4; } if (rptr) *rptr = (char*)ptr; return size; } /** * mono_metadata_decode_value: * \param ptr pointer to decode from * \param rptr the new position of the pointer * * This routine decompresses 32-bit values as specified in the "Blob and * Signature" section (23.2) * * \returns the decoded value */ guint32 mono_metadata_decode_value (const char *_ptr, const char **rptr) { const unsigned char *ptr = (const unsigned char *) _ptr; unsigned char b = *ptr; guint32 len; if ((b & 0x80) == 0){ len = b; ++ptr; } else if ((b & 0x40) == 0){ len = ((b & 0x3f) << 8 | ptr [1]); ptr += 2; } else { len = ((b & 0x1f) << 24) | (ptr [1] << 16) | (ptr [2] << 8) | ptr [3]; ptr += 4; } if (rptr) *rptr = (char*)ptr; return len; } /** * mono_metadata_decode_signed_value: * \param ptr pointer to decode from * \param rptr the new position of the pointer * * This routine decompresses 32-bit signed values * (not specified in the spec) * * \returns the decoded value */ gint32 mono_metadata_decode_signed_value (const char *ptr, const char **rptr) { guint32 uval = mono_metadata_decode_value (ptr, rptr); gint32 ival = uval >> 1; if (!(uval & 1)) return ival; /* ival is a truncated 2's complement negative number. */ if (ival < 0x40) /* 6 bits = 7 bits for compressed representation (top bit is '0') - 1 sign bit */ return ival - 0x40; if (ival < 0x2000) /* 13 bits = 14 bits for compressed representation (top bits are '10') - 1 sign bit */ return ival - 0x2000; if (ival < 0x10000000) /* 28 bits = 29 bits for compressed representation (top bits are '110') - 1 sign bit */ return ival - 0x10000000; g_assert (ival < 0x20000000); g_warning ("compressed signed value appears to use 29 bits for compressed representation: %x (raw: %8x)", ival, uval); return ival - 0x20000000; } /** * mono_metadata_translate_token_index: * Translates the given 1-based index into the \c Method, \c Field, \c Event, or \c Param tables * using the \c *Ptr tables in uncompressed metadata, if they are available. * * FIXME: The caller is not forced to call this function, which is error-prone, since * forgetting to call it would only show up as a bug on uncompressed metadata. */ guint32 mono_metadata_translate_token_index (MonoImage *image, int table, guint32 idx) { if (!image->uncompressed_metadata) return idx; switch (table) { case MONO_TABLE_METHOD: if (table_info_get_rows (&image->tables [MONO_TABLE_METHOD_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD_POINTER], idx - 1, MONO_METHOD_POINTER_METHOD); else return idx; case MONO_TABLE_FIELD: if (table_info_get_rows (&image->tables [MONO_TABLE_FIELD_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_FIELD_POINTER], idx - 1, MONO_FIELD_POINTER_FIELD); else return idx; case MONO_TABLE_EVENT: if (table_info_get_rows (&image->tables [MONO_TABLE_EVENT_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_EVENT_POINTER], idx - 1, MONO_EVENT_POINTER_EVENT); else return idx; case MONO_TABLE_PROPERTY: if (table_info_get_rows (&image->tables [MONO_TABLE_PROPERTY_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_PROPERTY_POINTER], idx - 1, MONO_PROPERTY_POINTER_PROPERTY); else return idx; case MONO_TABLE_PARAM: if (table_info_get_rows (&image->tables [MONO_TABLE_PARAM_POINTER])) return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_PARAM_POINTER], idx - 1, MONO_PARAM_POINTER_PARAM); else return idx; default: return idx; } } /** * mono_metadata_decode_table_row: * * Same as \c mono_metadata_decode_row, but takes an \p image + \p table ID pair, and takes * uncompressed metadata into account, so it should be used to access the * \c Method, \c Field, \c Param and \c Event tables when the access is made from metadata, i.e. * \p idx is retrieved from a metadata table, like \c MONO_TYPEDEF_FIELD_LIST. */ void mono_metadata_decode_table_row (MonoImage *image, int table, int idx, guint32 *res, int res_size) { if (image->uncompressed_metadata) idx = mono_metadata_translate_token_index (image, table, idx + 1) - 1; mono_metadata_decode_row (&image->tables [table], idx, res, res_size); } /** * mono_metadata_decode_table_row_col: * * Same as \c mono_metadata_decode_row_col, but takes an \p image + \p table ID pair, and takes * uncompressed metadata into account, so it should be used to access the * \c Method, \c Field, \c Param and \c Event tables. */ guint32 mono_metadata_decode_table_row_col (MonoImage *image, int table, int idx, guint col) { if (image->uncompressed_metadata) idx = mono_metadata_translate_token_index (image, table, idx + 1) - 1; return mono_metadata_decode_row_col (&image->tables [table], idx, col); } /** * mono_metadata_parse_typedef_or_ref: * \param m a metadata context. * \param ptr a pointer to an encoded TypedefOrRef in \p m * \param rptr pointer updated to match the end of the decoded stream * \returns a token valid in the \p m metadata decoded from * the compressed representation. */ guint32 mono_metadata_parse_typedef_or_ref (MonoImage *m, const char *ptr, const char **rptr) { guint32 token; token = mono_metadata_decode_value (ptr, &ptr); if (rptr) *rptr = ptr; return mono_metadata_token_from_dor (token); } /** * mono_metadata_parse_custom_mod: * \param m a metadata context. * \param dest storage where the info about the custom modifier is stored (may be NULL) * \param ptr a pointer to (possibly) the start of a custom modifier list * \param rptr pointer updated to match the end of the decoded stream * * Checks if \p ptr points to a type custom modifier compressed representation. * * \returns TRUE if a custom modifier was found, FALSE if not. */ int mono_metadata_parse_custom_mod (MonoImage *m, MonoCustomMod *dest, const char *ptr, const char **rptr) { MonoCustomMod local; if ((*ptr == MONO_TYPE_CMOD_OPT) || (*ptr == MONO_TYPE_CMOD_REQD)) { if (!dest) dest = &local; dest->required = *ptr == MONO_TYPE_CMOD_REQD ? 1 : 0; dest->token = mono_metadata_parse_typedef_or_ref (m, ptr + 1, rptr); return TRUE; } return FALSE; } /* * mono_metadata_parse_array_internal: * @m: a metadata context. * @transient: whenever to allocate data from the heap * @ptr: a pointer to an encoded array description. * @rptr: pointer updated to match the end of the decoded stream * * Decodes the compressed array description found in the metadata @m at @ptr. * * Returns: a #MonoArrayType structure describing the array type * and dimensions. Memory is allocated from the heap or from the image mempool, depending * on the value of @transient. * * LOCKING: Acquires the loader lock */ static MonoArrayType * mono_metadata_parse_array_internal (MonoImage *m, MonoGenericContainer *container, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { int i; MonoArrayType *array; MonoType *etype; etype = mono_metadata_parse_type_checked (m, container, 0, FALSE, ptr, &ptr, error); //FIXME this doesn't respect @transient if (!etype) return NULL; array = transient ? (MonoArrayType *)g_malloc0 (sizeof (MonoArrayType)) : (MonoArrayType *)mono_image_alloc0 (m, sizeof (MonoArrayType)); array->eklass = mono_class_from_mono_type_internal (etype); array->rank = mono_metadata_decode_value (ptr, &ptr); array->numsizes = mono_metadata_decode_value (ptr, &ptr); if (array->numsizes) array->sizes = transient ? (int *)g_malloc0 (sizeof (int) * array->numsizes) : (int *)mono_image_alloc0 (m, sizeof (int) * array->numsizes); for (i = 0; i < array->numsizes; ++i) array->sizes [i] = mono_metadata_decode_value (ptr, &ptr); array->numlobounds = mono_metadata_decode_value (ptr, &ptr); if (array->numlobounds) array->lobounds = transient ? (int *)g_malloc0 (sizeof (int) * array->numlobounds) : (int *)mono_image_alloc0 (m, sizeof (int) * array->numlobounds); for (i = 0; i < array->numlobounds; ++i) array->lobounds [i] = mono_metadata_decode_signed_value (ptr, &ptr); if (rptr) *rptr = ptr; return array; } /** * mono_metadata_parse_array: */ MonoArrayType * mono_metadata_parse_array (MonoImage *m, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoArrayType *ret = mono_metadata_parse_array_internal (m, NULL, FALSE, ptr, rptr, error); mono_error_cleanup (error); return ret; } /** * mono_metadata_free_array: * \param array array description * * Frees the array description returned from \c mono_metadata_parse_array. */ void mono_metadata_free_array (MonoArrayType *array) { g_free (array->sizes); g_free (array->lobounds); g_free (array); } /* * need to add common field and param attributes combinations: * [out] param * public static * public static literal * private * private static * private static literal */ static const MonoType builtin_types[] = { /* data, attrs, type, nmods, byref, pinned */ {{NULL}, 0, MONO_TYPE_VOID, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_BOOLEAN, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_BOOLEAN, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_CHAR, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_CHAR, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I1, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I1, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U1, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U1, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I2, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I2, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U2, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U2, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I4, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I4, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U4, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U4, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_I8, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I8, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U8, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U8, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_R4, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_R4, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_R8, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_R8, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_STRING, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_STRING, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_OBJECT, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_OBJECT, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_TYPEDBYREF, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_I, 0, 1, 0}, {{NULL}, 0, MONO_TYPE_U, 0, 0, 0}, {{NULL}, 0, MONO_TYPE_U, 0, 1, 0}, }; static GHashTable *type_cache = NULL; static gint32 next_generic_inst_id = 0; static guint mono_generic_class_hash (gconstpointer data); /* * MonoTypes with modifies are never cached, so we never check or use that field. */ static guint mono_type_hash (gconstpointer data) { const MonoType *type = (const MonoType *) data; if (type->type == MONO_TYPE_GENERICINST) return mono_generic_class_hash (type->data.generic_class); else return type->type | ((m_type_is_byref (type) ? 1 : 0) << 8) | (type->attrs << 9); } static gint mono_type_equal (gconstpointer ka, gconstpointer kb) { const MonoType *a = (const MonoType *) ka; const MonoType *b = (const MonoType *) kb; if (a->type != b->type || m_type_is_byref (a) != m_type_is_byref (b) || a->attrs != b->attrs || a->pinned != b->pinned) return 0; /* need other checks */ return 1; } guint mono_metadata_generic_inst_hash (gconstpointer data) { const MonoGenericInst *ginst = (const MonoGenericInst *) data; guint hash = 0; int i; g_assert (ginst); g_assert (ginst->type_argv); for (i = 0; i < ginst->type_argc; ++i) { hash *= 13; g_assert (ginst->type_argv [i]); hash += mono_metadata_type_hash (ginst->type_argv [i]); } return hash ^ (ginst->is_open << 8); } static gboolean mono_generic_inst_equal_full (const MonoGenericInst *a, const MonoGenericInst *b, gboolean signature_only) { int i; // An optimization: if the ids of two insts are the same, we know they are the same inst and don't check contents. // Furthermore, because we perform early de-duping, if the ids differ, we know the contents differ. #ifndef MONO_SMALL_CONFIG // Optimization does not work in MONO_SMALL_CONFIG: There are no IDs if (a->id && b->id) { // "id 0" means "object has no id"-- de-duping hasn't been performed yet, must check contents. if (a->id == b->id) return TRUE; // In signature-comparison mode id equality implies object equality, but this is not true for inequality. // Two separate objects could have signature-equavalent contents. if (!signature_only) return FALSE; } #endif if (a->is_open != b->is_open || a->type_argc != b->type_argc) return FALSE; for (i = 0; i < a->type_argc; ++i) { if (!do_mono_metadata_type_equal (a->type_argv [i], b->type_argv [i], signature_only)) return FALSE; } return TRUE; } gboolean mono_metadata_generic_inst_equal (gconstpointer ka, gconstpointer kb) { const MonoGenericInst *a = (const MonoGenericInst *) ka; const MonoGenericInst *b = (const MonoGenericInst *) kb; return mono_generic_inst_equal_full (a, b, FALSE); } static guint mono_generic_class_hash (gconstpointer data) { const MonoGenericClass *gclass = (const MonoGenericClass *) data; guint hash = mono_metadata_type_hash (m_class_get_byval_arg (gclass->container_class)); hash *= 13; hash += gclass->is_tb_open; hash += mono_metadata_generic_context_hash (&gclass->context); return hash; } static gboolean mono_generic_class_equal (gconstpointer ka, gconstpointer kb) { const MonoGenericClass *a = (const MonoGenericClass *) ka; const MonoGenericClass *b = (const MonoGenericClass *) kb; return _mono_metadata_generic_class_equal (a, b, FALSE); } /** * mono_metadata_init: * * Initialize the global variables of this module. * This is a Mono runtime internal function. */ void mono_metadata_init (void) { int i; /* We guard against double initialization due to how pedump in verification mode works. Until runtime initialization is properly factored to work with what it needs we need workarounds like this. FIXME: https://bugzilla.xamarin.com/show_bug.cgi?id=58793 */ static gboolean inited; if (inited) return; inited = TRUE; type_cache = g_hash_table_new (mono_type_hash, mono_type_equal); for (i = 0; i < G_N_ELEMENTS (builtin_types); ++i) g_hash_table_insert (type_cache, (gpointer) &builtin_types [i], (gpointer) &builtin_types [i]); mono_metadata_update_init (); } /* * Make a pass over the metadata signature blob starting at \p tmp_ptr and count the custom modifiers. */ static int count_custom_modifiers (MonoImage *m, const char *tmp_ptr) { int count = 0; gboolean found = TRUE; while (found) { switch (*tmp_ptr) { case MONO_TYPE_PINNED: case MONO_TYPE_BYREF: ++tmp_ptr; break; case MONO_TYPE_CMOD_REQD: case MONO_TYPE_CMOD_OPT: count ++; mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr); break; default: found = FALSE; } } return count; } /* * Decode the (expected \p count, possibly 0) custom modifiers as well as the "byref" and "pinned" * markers from the metadata stream \p ptr and put them into \p cmods * * Sets \p rptr past the end of the parsed metadata. Sets \p pinned and \p byref if those modifiers * were present. */ static void decode_custom_modifiers (MonoImage *m, MonoCustomModContainer *cmods, int count, const char *ptr, const char **rptr, gboolean *pinned, gboolean *byref) { gboolean found = TRUE; /* cmods are encoded in reverse order from how we normally see them. * "int32 modopt (Foo) modopt (Bar)" is encoded as "cmod_opt [typedef_or_ref "Bar"] cmod_opt [typedef_or_ref "Foo"] I4" */ while (found) { switch (*ptr) { case MONO_TYPE_PINNED: *pinned = TRUE; ++ptr; break; case MONO_TYPE_BYREF: *byref = TRUE; ++ptr; break; case MONO_TYPE_CMOD_REQD: case MONO_TYPE_CMOD_OPT: g_assert (count > 0); mono_metadata_parse_custom_mod (m, &(cmods->modifiers [--count]), ptr, &ptr); break; default: found = FALSE; } } // either there were no cmods, or else we iterated through all of cmods backwards to populate it. g_assert (count == 0); *rptr = ptr; } /* * Allocate the memory necessary to hold a \c MonoType with \p count custom modifiers. * If \p transient is true, allocate from the heap, otherwise allocate from the mempool of image \p m */ static MonoType * alloc_type_with_cmods (MonoImage *m, gboolean transient, int count) { g_assert (count > 0); MonoType *type; size_t size = mono_sizeof_type_with_mods (count, FALSE); type = transient ? (MonoType *)g_malloc0 (size) : (MonoType *)mono_image_alloc0 (m, size); type->has_cmods = TRUE; MonoCustomModContainer *cmods = mono_type_get_cmods (type); cmods->count = count; cmods->image = m; return type; } /* * If \p transient is true, free \p type, otherwise no-op */ static void free_parsed_type (MonoType *type, gboolean transient) { if (transient) mono_metadata_free_type (type); } /* * Try to find a pre-allocated version of the given \p type. * Returns true and sets \p canonical_type if found, otherwise return false. * * For classes and valuetypes, this returns their embedded byval_arg or * this_arg types. For base types, it returns the global versions. */ static gboolean try_get_canonical_type (MonoType *type, MonoType **canonical_type) { /* Note: If the type has any attribtues or modifiers the function currently returns false, * although there's no fundamental reason we can't have cached copies in those instances (or * indeed cached arrays, pointers or some generic instances). However in that case there's * limited utility in returning a cached copy because the parsing code in * do_mono_metadata_parse_type could have allocated some mempool or heap memory already. * * This function should be kept closely in sync with mono_metadata_free_type so that it * doesn't try to free canonical MonoTypes (which might not even be heap allocated). */ g_assert (!type->has_cmods); if ((type->type == MONO_TYPE_CLASS || type->type == MONO_TYPE_VALUETYPE) && !type->pinned && !type->attrs) { MonoType *ret = m_type_is_byref (type) ? m_class_get_this_arg (type->data.klass) : m_class_get_byval_arg (type->data.klass); /* Consider the case: class Foo<T> { class Bar {} } class Test : Foo<Test>.Bar {} When Foo<Test> is being expanded, 'Test' isn't yet initialized. It's actually in a really pristine state: it doesn't even know whether 'Test' is a reference or a value type. We ensure that the MonoClass is in a state that we can canonicalize to: klass->_byval_arg.data.klass == klass klass->this_arg.data.klass == klass If we can't canonicalize 'type', it doesn't matter, since later users of 'type' will do it. LOCKING: even though we don't explicitly hold a lock, in the problematic case 'ret' is a field of a MonoClass which currently holds the loader lock. 'type' is local. */ if (ret->data.klass == type->data.klass) { *canonical_type = ret; return TRUE; } } /* Maybe it's one of the globaly-known basic types */ MonoType *cached; /* No need to use locking since nobody is modifying the hash table */ if ((cached = (MonoType *)g_hash_table_lookup (type_cache, type))) { *canonical_type = cached; return TRUE; } return FALSE; } /* * Fill in \p type (expecting \p cmod_count custom modifiers) by parsing it from the metadata stream pointed at by \p ptr. * * On success returns true and sets \p rptr past the parsed stream data. On failure return false and sets \p error. */ static gboolean do_mono_metadata_parse_type_with_cmods (MonoType *type, int cmod_count, MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { gboolean byref= FALSE; gboolean pinned = FALSE; error_init (error); /* Iterate again, but now parse pinned, byref and custom modifiers */ decode_custom_modifiers (m, mono_type_get_cmods (type), cmod_count, ptr, &ptr, &pinned, &byref); type->attrs = opt_attrs; type->byref__ = byref; type->pinned = pinned ? 1 : 0; if (!do_mono_metadata_parse_type (type, m, container, transient, ptr, &ptr, error)) return FALSE; if (rptr) *rptr = ptr; return TRUE; } /** * mono_metadata_parse_type: * \param m metadata context * \param mode kind of type that may be found at \p ptr * \param opt_attrs optional attributes to store in the returned type * \param ptr pointer to the type representation * \param rptr pointer updated to match the end of the decoded stream * \param transient whenever to allocate the result from the heap or from a mempool * * Decode a compressed type description found at \p ptr in \p m . * \p mode can be one of \c MONO_PARSE_MOD_TYPE, \c MONO_PARSE_PARAM, \c MONO_PARSE_RET, * \c MONO_PARSE_FIELD, \c MONO_PARSE_LOCAL, \c MONO_PARSE_TYPE. * This function can be used to decode type descriptions in method signatures, * field signatures, locals signatures etc. * * To parse a generic type, \c generic_container points to the current class'es * (the \c generic_container field in the <code>MonoClass</code>) or the current generic method's * (stored in <code>image->property_hash</code>) generic container. * When we encounter a \c MONO_TYPE_VAR or \c MONO_TYPE_MVAR, it's looked up in * this \c MonoGenericContainer. * * LOCKING: Acquires the loader lock. * * \returns a \c MonoType structure representing the decoded type. */ static MonoType* mono_metadata_parse_type_internal (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { MonoType *type; MonoType stype; int count = 0; // Number of mod arguments gboolean allocated = FALSE; error_init (error); /* * Q: What's going on with `stype` and `allocated`? A: A very common case is that we're * parsing "int" or "string" or "Dictionary<K,V>" non-transiently. In that case we don't * want to flood the mempool with millions of copies of MonoType 'int' (etc). So we parse * it into a stack variable and try_get_canonical_type, below. As long as the type is * normal, we will avoid having to make an extra copy in the mempool. */ /* * According to the spec, custom modifiers should come before the byref * flag, but the IL produced by ilasm from the following signature: * object modopt(...) & * starts with a byref flag, followed by the modifiers. (bug #49802) * Also, this type seems to be different from 'object & modopt(...)'. Maybe * it would be better to treat byref as real type constructor instead of * a modifier... * Also, pinned should come before anything else, but some MSV++ produced * assemblies violate this (#bug 61990). */ /* Count the modifiers first */ count = count_custom_modifiers (m, ptr); if (count) { // There are mods, so the MonoType will be of nonstandard size. allocated = TRUE; if (count > 64) { mono_error_set_bad_image (error, m, "Invalid type with more than 64 modifiers"); return NULL; } type = alloc_type_with_cmods (m, transient, count); } else { // The type is of standard size, so we can allocate it on the stack. type = &stype; memset (type, 0, MONO_SIZEOF_TYPE); } if (!do_mono_metadata_parse_type_with_cmods (type, count, m, container, opt_attrs, transient, ptr, rptr, error)) { if (allocated) free_parsed_type (type, transient); return NULL; } // Possibly we can return an already-allocated type instead of the one we decoded if (!allocated && !transient) { /* no need to free type here, because it is on the stack */ MonoType *ret_type = NULL; if (try_get_canonical_type (type, &ret_type)) return ret_type; } /* printf ("%x %x %c %s\n", type->attrs, type->num_mods, type->pinned ? 'p' : ' ', mono_type_full_name (type)); */ // Otherwise return the type we decoded if (!allocated) { // Type was allocated on the stack, so we need to copy it to safety type = transient ? (MonoType *)g_malloc (MONO_SIZEOF_TYPE) : (MonoType *)mono_image_alloc (m, MONO_SIZEOF_TYPE); memcpy (type, &stype, MONO_SIZEOF_TYPE); } g_assert (type != &stype); return type; } MonoType* mono_metadata_parse_type_checked (MonoImage *m, MonoGenericContainer *container, short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { return mono_metadata_parse_type_internal (m, container, opt_attrs, transient, ptr, rptr, error); } /* * LOCKING: Acquires the loader lock. */ MonoType* mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoType * type = mono_metadata_parse_type_internal (m, NULL, opt_attrs, FALSE, ptr, rptr, error); mono_error_cleanup (error); return type; } gboolean mono_metadata_method_has_param_attrs (MonoImage *m, int def) { MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM]; MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD]; guint lastp, i, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST); if (param_index == 0) return FALSE; /* FIXME: metadata-update */ if (def < table_info_get_rows (methodt)) lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST); else lastp = table_info_get_rows (&m->tables [MONO_TABLE_PARAM]) + 1; for (i = param_index; i < lastp; ++i) { guint32 flags = mono_metadata_decode_row_col (paramt, i - 1, MONO_PARAM_FLAGS); if (flags) return TRUE; } return FALSE; } /* * mono_metadata_get_param_attrs: * * @m The image to loader parameter attributes from * @def method def token (one based) * @param_count number of params to decode including the return value * * Return the parameter attributes for the method whose MethodDef index is DEF. The * returned memory needs to be freed by the caller. If all the param attributes are * 0, then NULL is returned. */ int* mono_metadata_get_param_attrs (MonoImage *m, int def, int param_count) { MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM]; MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD]; guint32 cols [MONO_PARAM_SIZE]; guint lastp, i, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST); int *pattrs = NULL; /* hot reload deltas may specify 0 for the param table index */ if (param_index == 0) return NULL; /* FIXME: metadata-update */ int rows = mono_metadata_table_num_rows (m, MONO_TABLE_METHOD); if (def < rows) lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST); else lastp = table_info_get_rows (paramt) + 1; for (i = param_index; i < lastp; ++i) { mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE); if (cols [MONO_PARAM_FLAGS]) { if (!pattrs) pattrs = g_new0 (int, param_count); /* at runtime we just ignore this kind of malformed file: * the verifier can signal the error to the user */ if (cols [MONO_PARAM_SEQUENCE] >= param_count) continue; pattrs [cols [MONO_PARAM_SEQUENCE]] = cols [MONO_PARAM_FLAGS]; } } return pattrs; } /** * mono_metadata_parse_signature: * \param image metadata context * \param token metadata token * * Decode a method signature stored in the \c StandAloneSig table * * \returns a \c MonoMethodSignature describing the signature. */ MonoMethodSignature* mono_metadata_parse_signature (MonoImage *image, guint32 token) { ERROR_DECL (error); MonoMethodSignature *ret; ret = mono_metadata_parse_signature_checked (image, token, error); mono_error_cleanup (error); return ret; } /* * mono_metadata_parse_signature_checked: * @image: metadata context * @token: metadata token * @error: set on error * * Decode a method signature stored in the STANDALONESIG table * * Returns: a MonoMethodSignature describing the signature. On failure * returns NULL and sets @error. */ MonoMethodSignature* mono_metadata_parse_signature_checked (MonoImage *image, guint32 token, MonoError *error) { error_init (error); MonoTableInfo *tables = image->tables; guint32 idx = mono_metadata_token_index (token); guint32 sig; const char *ptr; if (image_is_dynamic (image)) { return (MonoMethodSignature *)mono_lookup_dynamic_token (image, token, NULL, error); } g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG); sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0); ptr = mono_metadata_blob_heap (image, sig); mono_metadata_decode_blob_size (ptr, &ptr); return mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error); } /** * mono_metadata_signature_alloc: * \param image metadata context * \param nparams number of parameters in the signature * * Allocate a \c MonoMethodSignature structure with the specified number of params. * The return type and the params types need to be filled later. * This is a Mono runtime internal function. * * LOCKING: Assumes the loader lock is held. * * \returns the new \c MonoMethodSignature structure. */ MonoMethodSignature* mono_metadata_signature_alloc (MonoImage *m, guint32 nparams) { MonoMethodSignature *sig; sig = (MonoMethodSignature *)mono_image_alloc0 (m, MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)nparams) * sizeof (MonoType*)); sig->param_count = nparams; sig->sentinelpos = -1; return sig; } static MonoMethodSignature* mono_metadata_signature_dup_internal (MonoImage *image, MonoMemPool *mp, MonoMemoryManager *mem_manager, MonoMethodSignature *sig, size_t padding) { int sigsize, sig_header_size; MonoMethodSignature *ret; sigsize = sig_header_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *) + padding; if (sig->ret) sigsize += mono_sizeof_type (sig->ret); if (image) { ret = (MonoMethodSignature *)mono_image_alloc (image, sigsize); } else if (mp) { ret = (MonoMethodSignature *)mono_mempool_alloc (mp, sigsize); } else if (mem_manager) { ret = (MonoMethodSignature *)mono_mem_manager_alloc (mem_manager, sigsize); } else { ret = (MonoMethodSignature *)g_malloc (sigsize); } memcpy (ret, sig, sig_header_size - padding); // Copy return value because of ownership semantics. if (sig->ret) { // Danger! Do not alter padding use without changing the dup_add_this below intptr_t end_of_header = (intptr_t)( (char*)(ret) + sig_header_size); ret->ret = (MonoType *)end_of_header; memcpy (ret->ret, sig->ret, mono_sizeof_type (sig->ret)); } return ret; } /* * signature_dup_add_this: * * Make a copy of @sig, adding an explicit this argument. */ MonoMethodSignature* mono_metadata_signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass) { MonoMethodSignature *ret; ret = mono_metadata_signature_dup_internal (image, NULL, NULL, sig, sizeof (MonoType *)); ret->param_count = sig->param_count + 1; ret->hasthis = FALSE; for (int i = sig->param_count - 1; i >= 0; i --) ret->params [i + 1] = sig->params [i]; ret->params [0] = m_class_is_valuetype (klass) ? m_class_get_this_arg (klass) : m_class_get_byval_arg (klass); for (int i = sig->param_count - 1; i >= 0; i --) g_assert(ret->params [i + 1]->type == sig->params [i]->type && ret->params [i+1]->type != MONO_TYPE_END); g_assert (ret->ret->type == sig->ret->type && ret->ret->type != MONO_TYPE_END); return ret; } MonoMethodSignature* mono_metadata_signature_dup_full (MonoImage *image, MonoMethodSignature *sig) { MonoMethodSignature *ret = mono_metadata_signature_dup_internal (image, NULL, NULL, sig, 0); for (int i = 0 ; i < sig->param_count; i ++) g_assert (ret->params [i]->type == sig->params [i]->type); g_assert (ret->ret->type == sig->ret->type); return ret; } /*The mempool is accessed without synchronization*/ MonoMethodSignature* mono_metadata_signature_dup_mempool (MonoMemPool *mp, MonoMethodSignature *sig) { return mono_metadata_signature_dup_internal (NULL, mp, NULL, sig, 0); } MonoMethodSignature* mono_metadata_signature_dup_mem_manager (MonoMemoryManager *mem_manager, MonoMethodSignature *sig) { return mono_metadata_signature_dup_internal (NULL, NULL, mem_manager, sig, 0); } /** * mono_metadata_signature_dup: * \param sig method signature * * Duplicate an existing \c MonoMethodSignature so it can be modified. * This is a Mono runtime internal function. * * \returns the new \c MonoMethodSignature structure. */ MonoMethodSignature* mono_metadata_signature_dup (MonoMethodSignature *sig) { return mono_metadata_signature_dup_full (NULL, sig); } /* * mono_metadata_signature_size: * * Return the amount of memory allocated to SIG. */ guint32 mono_metadata_signature_size (MonoMethodSignature *sig) { return MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *); } /** * metadata_signature_set_modopt_call_conv: * * Reads the custom attributes from \p cmod_type and adds them to the signature \p sig. * * This follows the C# unmanaged function pointer encoding. * The modopts are from the System.Runtime.CompilerServices namespace and all have a name of the form CallConvXXX. * * The calling convention will be one of: * Cdecl, Thiscall, Stdcall, Fastcall * plus an optional SuppressGCTransition */ static void metadata_signature_set_modopt_call_conv (MonoMethodSignature *sig, MonoType *cmod_type, MonoError *error) { uint8_t count = mono_type_custom_modifier_count (cmod_type); if (count == 0) return; int base_callconv = sig->call_convention; gboolean suppress_gc_transition = sig->suppress_gc_transition; for (uint8_t i = 0; i < count; ++i) { gboolean req = FALSE; MonoType *cmod = mono_type_get_custom_modifier (cmod_type, i, &req, error); return_if_nok (error); /* callconv is a modopt, not a modreq */ if (req) continue; /* shouldn't be a valuetype, array, gparam, gtd, ginst etc */ if (cmod->type != MONO_TYPE_CLASS) continue; MonoClass *cmod_klass = mono_class_from_mono_type_internal (cmod); if (m_class_get_image (cmod_klass) != mono_defaults.corlib) continue; if (strcmp (m_class_get_name_space (cmod_klass), "System.Runtime.CompilerServices")) continue; const char *name = m_class_get_name (cmod_klass); if (strstr (name, "CallConv") != name) continue; name += strlen ("CallConv"); /* skip the prefix */ /* Check for the known base unmanaged calling conventions */ if (!strcmp (name, "Cdecl")) { base_callconv = MONO_CALL_C; continue; } else if (!strcmp (name, "Stdcall")) { base_callconv = MONO_CALL_STDCALL; continue; } else if (!strcmp (name, "Thiscall")) { base_callconv = MONO_CALL_THISCALL; continue; } else if (!strcmp (name, "Fastcall")) { base_callconv = MONO_CALL_FASTCALL; continue; } /* Check for known calling convention modifiers */ if (!strcmp (name, "SuppressGCTransition")) { suppress_gc_transition = TRUE; continue; } } sig->call_convention = base_callconv; sig->suppress_gc_transition = suppress_gc_transition; } /** * mono_metadata_parse_method_signature_full: * \param m metadata context * \param generic_container: generics container * \param def the \c MethodDef index or 0 for \c Ref signatures. * \param ptr pointer to the signature metadata representation * \param rptr pointer updated to match the end of the decoded stream * \param error set on error * * * Decode a method signature stored at \p ptr. * This is a Mono runtime internal function. * * LOCKING: Assumes the loader lock is held. * * \returns a \c MonoMethodSignature describing the signature. On error sets * \p error and returns \c NULL. */ MonoMethodSignature * mono_metadata_parse_method_signature_full (MonoImage *m, MonoGenericContainer *container, int def, const char *ptr, const char **rptr, MonoError *error) { MonoMethodSignature *method; int i, *pattrs = NULL; guint32 hasthis = 0, explicit_this = 0, call_convention, param_count; guint32 gen_param_count = 0; gboolean is_open = FALSE; error_init (error); if (*ptr & 0x10) gen_param_count = 1; if (*ptr & 0x20) hasthis = 1; if (*ptr & 0x40) explicit_this = 1; call_convention = *ptr & 0x0F; ptr++; if (gen_param_count) gen_param_count = mono_metadata_decode_value (ptr, &ptr); param_count = mono_metadata_decode_value (ptr, &ptr); if (def) pattrs = mono_metadata_get_param_attrs (m, def, param_count + 1); /*Must be + 1 since signature's param count doesn't account for the return value */ method = mono_metadata_signature_alloc (m, param_count); method->hasthis = hasthis; method->explicit_this = explicit_this; method->call_convention = call_convention; method->generic_param_count = gen_param_count; switch (method->call_convention) { case MONO_CALL_DEFAULT: case MONO_CALL_VARARG: method->pinvoke = 0; break; case MONO_CALL_C: case MONO_CALL_STDCALL: case MONO_CALL_THISCALL: case MONO_CALL_FASTCALL: case MONO_CALL_UNMANAGED_MD: method->pinvoke = 1; break; } if (call_convention != 0xa) { method->ret = mono_metadata_parse_type_checked (m, container, pattrs ? pattrs [0] : 0, FALSE, ptr, &ptr, error); if (!method->ret) { mono_metadata_free_method_signature (method); g_free (pattrs); return NULL; } is_open = mono_class_is_open_constructed_type (method->ret); if (G_UNLIKELY (method->ret->has_cmods && method->call_convention == MONO_CALL_UNMANAGED_MD)) { /* calling convention encoded in modopts */ metadata_signature_set_modopt_call_conv (method, method->ret, error); if (!is_ok (error)) { g_free (pattrs); return NULL; } } } for (i = 0; i < method->param_count; ++i) { if (*ptr == MONO_TYPE_SENTINEL) { if (method->call_convention != MONO_CALL_VARARG || def) { mono_error_set_bad_image (error, m, "Found sentinel for methoddef or no vararg"); g_free (pattrs); return NULL; } if (method->sentinelpos >= 0) { mono_error_set_bad_image (error, m, "Found sentinel twice in the same signature."); g_free (pattrs); return NULL; } method->sentinelpos = i; ptr++; } method->params [i] = mono_metadata_parse_type_checked (m, container, pattrs ? pattrs [i+1] : 0, FALSE, ptr, &ptr, error); if (!method->params [i]) { mono_metadata_free_method_signature (method); g_free (pattrs); return NULL; } if (!is_open) is_open = mono_class_is_open_constructed_type (method->params [i]); } /* The sentinel could be missing if the caller does not pass any additional arguments */ if (!def && method->call_convention == MONO_CALL_VARARG && method->sentinelpos < 0) method->sentinelpos = method->param_count; method->has_type_parameters = is_open; if (def && (method->call_convention == MONO_CALL_VARARG)) method->sentinelpos = method->param_count; g_free (pattrs); if (rptr) *rptr = ptr; /* * Add signature to a cache and increase ref count... */ return method; } /** * mono_metadata_parse_method_signature: * \param m metadata context * \param def the \c MethodDef index or 0 for \c Ref signatures. * \param ptr pointer to the signature metadata representation * \param rptr pointer updated to match the end of the decoded stream * * Decode a method signature stored at \p ptr. * This is a Mono runtime internal function. * * LOCKING: Assumes the loader lock is held. * * \returns a \c MonoMethodSignature describing the signature. */ MonoMethodSignature * mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr) { /* * This function MUST NOT be called by runtime code as it does error handling incorrectly. * Use mono_metadata_parse_method_signature_full instead. * It's ok to asser on failure as we no longer use it. */ ERROR_DECL (error); MonoMethodSignature *ret; ret = mono_metadata_parse_method_signature_full (m, NULL, def, ptr, rptr, error); mono_error_assert_ok (error); return ret; } /** * mono_metadata_free_method_signature: * \param sig signature to destroy * * Free the memory allocated in the signature \p sig. * This method needs to be robust and work also on partially-built * signatures, so it does extra checks. */ void mono_metadata_free_method_signature (MonoMethodSignature *sig) { /* Everything is allocated from mempools */ /* int i; if (sig->ret) mono_metadata_free_type (sig->ret); for (i = 0; i < sig->param_count; ++i) { if (sig->params [i]) mono_metadata_free_type (sig->params [i]); } */ } void mono_metadata_free_inflated_signature (MonoMethodSignature *sig) { int i; /* Allocated in inflate_generic_signature () */ if (sig->ret) mono_metadata_free_type (sig->ret); for (i = 0; i < sig->param_count; ++i) { if (sig->params [i]) mono_metadata_free_type (sig->params [i]); } g_free (sig); } static gboolean inflated_method_equal (gconstpointer a, gconstpointer b) { const MonoMethodInflated *ma = (const MonoMethodInflated *)a; const MonoMethodInflated *mb = (const MonoMethodInflated *)b; if (ma->declaring != mb->declaring) return FALSE; return mono_metadata_generic_context_equal (&ma->context, &mb->context); } static guint inflated_method_hash (gconstpointer a) { const MonoMethodInflated *ma = (const MonoMethodInflated *)a; return (mono_metadata_generic_context_hash (&ma->context) ^ mono_aligned_addr_hash (ma->declaring)); } static gboolean inflated_signature_equal (gconstpointer a, gconstpointer b) { const MonoInflatedMethodSignature *sig1 = (const MonoInflatedMethodSignature *)a; const MonoInflatedMethodSignature *sig2 = (const MonoInflatedMethodSignature *)b; /* sig->sig is assumed to be canonized */ if (sig1->sig != sig2->sig) return FALSE; /* The generic instances are canonized */ return mono_metadata_generic_context_equal (&sig1->context, &sig2->context); } static guint inflated_signature_hash (gconstpointer a) { const MonoInflatedMethodSignature *sig = (const MonoInflatedMethodSignature *)a; /* sig->sig is assumed to be canonized */ return mono_metadata_generic_context_hash (&sig->context) ^ mono_aligned_addr_hash (sig->sig); } /*static void dump_ginst (MonoGenericInst *ginst) { int i; char *name; g_print ("Ginst: <"); for (i = 0; i < ginst->type_argc; ++i) { if (i != 0) g_print (", "); name = mono_type_get_name (ginst->type_argv [i]); g_print ("%s", name); g_free (name); } g_print (">"); }*/ static gboolean aggregate_modifiers_equal (gconstpointer ka, gconstpointer kb) { MonoAggregateModContainer *amods1 = (MonoAggregateModContainer *)ka; MonoAggregateModContainer *amods2 = (MonoAggregateModContainer *)kb; if (amods1->count != amods2->count) return FALSE; for (int i = 0; i < amods1->count; ++i) { if (amods1->modifiers [i].required != amods2->modifiers [i].required) return FALSE; if (!mono_metadata_type_equal_full (amods1->modifiers [i].type, amods2->modifiers [i].type, TRUE)) return FALSE; } return TRUE; } static guint aggregate_modifiers_hash (gconstpointer a) { const MonoAggregateModContainer *amods = (const MonoAggregateModContainer *)a; guint hash = 0; for (int i = 0; i < amods->count; ++i) { // hash details borrowed from mono_metadata_generic_inst_hash hash *= 13; hash ^= (amods->modifiers [i].required << 8); hash += mono_metadata_type_hash (amods->modifiers [i].type); } return hash; } static gboolean type_in_image (MonoType *type, MonoImage *image); static gboolean aggregate_modifiers_in_image (MonoAggregateModContainer *amods, MonoImage *image); static gboolean signature_in_image (MonoMethodSignature *sig, MonoImage *image) { gpointer iter = NULL; MonoType *p; while ((p = mono_signature_get_params_internal (sig, &iter)) != NULL) if (type_in_image (p, image)) return TRUE; return type_in_image (mono_signature_get_return_type_internal (sig), image); } static gboolean ginst_in_image (MonoGenericInst *ginst, MonoImage *image) { int i; for (i = 0; i < ginst->type_argc; ++i) { if (type_in_image (ginst->type_argv [i], image)) return TRUE; } return FALSE; } static gboolean gclass_in_image (MonoGenericClass *gclass, MonoImage *image) { return m_class_get_image (gclass->container_class) == image || ginst_in_image (gclass->context.class_inst, image); } static gboolean type_in_image (MonoType *type, MonoImage *image) { retry: if (type->has_cmods && mono_type_is_aggregate_mods (type)) if (aggregate_modifiers_in_image (mono_type_get_amods (type), image)) return TRUE; switch (type->type) { case MONO_TYPE_GENERICINST: return gclass_in_image (type->data.generic_class, image); case MONO_TYPE_PTR: type = type->data.type; goto retry; case MONO_TYPE_SZARRAY: type = m_class_get_byval_arg (type->data.klass); goto retry; case MONO_TYPE_ARRAY: type = m_class_get_byval_arg (type->data.array->eklass); goto retry; case MONO_TYPE_FNPTR: return signature_in_image (type->data.method, image); case MONO_TYPE_VAR: case MONO_TYPE_MVAR: if (image == mono_get_image_for_generic_param (type->data.generic_param)) return TRUE; else if (type->data.generic_param->gshared_constraint) { type = type->data.generic_param->gshared_constraint; goto retry; } return FALSE; default: /* At this point, we should've avoided all potential allocations in mono_class_from_mono_type_internal () */ return image == m_class_get_image (mono_class_from_mono_type_internal (type)); } } gboolean mono_type_in_image (MonoType *type, MonoImage *image) { return type_in_image (type, image); } gboolean aggregate_modifiers_in_image (MonoAggregateModContainer *amods, MonoImage *image) { for (int i = 0; i < amods->count; i++) if (type_in_image (amods->modifiers [i].type, image)) return TRUE; return FALSE; } /* * Structure used by the collect_..._images functions to store the image list. */ typedef struct { MonoImage *image_buf [64]; MonoImage **images; int nimages, images_len; } CollectData; static void collect_data_init (CollectData *data) { data->images = data->image_buf; data->images_len = 64; data->nimages = 0; } static void collect_data_free (CollectData *data) { if (data->images != data->image_buf) g_free (data->images); } static void enlarge_data (CollectData *data) { int new_len = data->images_len < 16 ? 16 : data->images_len * 2; MonoImage **d = g_new (MonoImage *, new_len); // FIXME: test this g_assert_not_reached (); memcpy (d, data->images, data->images_len); if (data->images != data->image_buf) g_free (data->images); data->images = d; data->images_len = new_len; } static void add_image (MonoImage *image, CollectData *data) { int i; /* The arrays are small, so use a linear search instead of a hash table */ for (i = 0; i < data->nimages; ++i) if (data->images [i] == image) return; if (data->nimages == data->images_len) enlarge_data (data); data->images [data->nimages ++] = image; } static void collect_type_images (MonoType *type, CollectData *data); static void collect_ginst_images (MonoGenericInst *ginst, CollectData *data) { int i; for (i = 0; i < ginst->type_argc; ++i) { collect_type_images (ginst->type_argv [i], data); } } static void collect_gclass_images (MonoGenericClass *gclass, CollectData *data) { add_image (m_class_get_image (gclass->container_class), data); if (gclass->context.class_inst) collect_ginst_images (gclass->context.class_inst, data); } static void collect_signature_images (MonoMethodSignature *sig, CollectData *data) { gpointer iter = NULL; MonoType *p; collect_type_images (mono_signature_get_return_type_internal (sig), data); while ((p = mono_signature_get_params_internal (sig, &iter)) != NULL) collect_type_images (p, data); } static void collect_inflated_signature_images (MonoInflatedMethodSignature *sig, CollectData *data) { collect_signature_images (sig->sig, data); if (sig->context.class_inst) collect_ginst_images (sig->context.class_inst, data); if (sig->context.method_inst) collect_ginst_images (sig->context.method_inst, data); } static void collect_method_images (MonoMethodInflated *method, CollectData *data) { MonoMethod *m = method->declaring; add_image (m_class_get_image (method->declaring->klass), data); if (method->context.class_inst) collect_ginst_images (method->context.class_inst, data); if (method->context.method_inst) collect_ginst_images (method->context.method_inst, data); /* * Dynamic assemblies have no references, so the images they depend on can be unloaded before them. */ if (image_is_dynamic (m_class_get_image (m->klass))) collect_signature_images (mono_method_signature_internal (m), data); } static void collect_aggregate_modifiers_images (MonoAggregateModContainer *amods, CollectData *data) { for (int i = 0; i < amods->count; ++i) collect_type_images (amods->modifiers [i].type, data); } static void collect_type_images (MonoType *type, CollectData *data) { retry: if (G_UNLIKELY (type->has_cmods && mono_type_is_aggregate_mods (type))) { collect_aggregate_modifiers_images (mono_type_get_amods (type), data); } switch (type->type) { case MONO_TYPE_GENERICINST: collect_gclass_images (type->data.generic_class, data); break; case MONO_TYPE_PTR: type = type->data.type; goto retry; case MONO_TYPE_SZARRAY: type = m_class_get_byval_arg (type->data.klass); goto retry; case MONO_TYPE_ARRAY: type = m_class_get_byval_arg (type->data.array->eklass); goto retry; case MONO_TYPE_FNPTR: collect_signature_images (type->data.method, data); break; case MONO_TYPE_VAR: case MONO_TYPE_MVAR: { MonoImage *image = mono_get_image_for_generic_param (type->data.generic_param); add_image (image, data); type = type->data.generic_param->gshared_constraint; if (type) goto retry; break; } case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: add_image (m_class_get_image (mono_class_from_mono_type_internal (type)), data); break; default: add_image (mono_defaults.corlib, data); } } typedef struct { MonoImage *image; GSList *list; } CleanForImageUserData; static gboolean steal_gclass_in_image (gpointer key, gpointer value, gpointer data) { MonoGenericClass *gclass = (MonoGenericClass *)key; CleanForImageUserData *user_data = (CleanForImageUserData *)data; g_assert (gclass_in_image (gclass, user_data->image)); user_data->list = g_slist_prepend (user_data->list, gclass); return TRUE; } static gboolean steal_ginst_in_image (gpointer key, gpointer value, gpointer data) { MonoGenericInst *ginst = (MonoGenericInst *)key; CleanForImageUserData *user_data = (CleanForImageUserData *)data; // This doesn't work during corlib compilation //g_assert (ginst_in_image (ginst, user_data->image)); user_data->list = g_slist_prepend (user_data->list, ginst); return TRUE; } static gboolean steal_aggregate_modifiers_in_image (gpointer key, gpointer value, gpointer data) { MonoAggregateModContainer *amods = (MonoAggregateModContainer *)key; CleanForImageUserData *user_data = (CleanForImageUserData *)data; g_assert (aggregate_modifiers_in_image (amods, user_data->image)); user_data->list = g_slist_prepend (user_data->list, amods); return TRUE; } static gboolean inflated_method_in_image (gpointer key, gpointer value, gpointer data) { MonoImage *image = (MonoImage *)data; MonoMethodInflated *method = (MonoMethodInflated *)key; // FIXME: // https://bugzilla.novell.com/show_bug.cgi?id=458168 g_assert (m_class_get_image (method->declaring->klass) == image || (method->context.class_inst && ginst_in_image (method->context.class_inst, image)) || (method->context.method_inst && ginst_in_image (method->context.method_inst, image)) || (((MonoMethod*)method)->signature && signature_in_image (mono_method_signature_internal ((MonoMethod*)method), image))); return TRUE; } static gboolean inflated_signature_in_image (gpointer key, gpointer value, gpointer data) { MonoImage *image = (MonoImage *)data; MonoInflatedMethodSignature *sig = (MonoInflatedMethodSignature *)key; return signature_in_image (sig->sig, image) || (sig->context.class_inst && ginst_in_image (sig->context.class_inst, image)) || (sig->context.method_inst && ginst_in_image (sig->context.method_inst, image)); } static gboolean class_in_image (gpointer key, gpointer value, gpointer data) { MonoImage *image = (MonoImage *)data; MonoClass *klass = (MonoClass *)key; g_assert (type_in_image (m_class_get_byval_arg (klass), image)); return TRUE; } static void check_gmethod (gpointer key, gpointer value, gpointer data) { MonoMethodInflated *method = (MonoMethodInflated *)key; MonoImage *image = (MonoImage *)data; if (method->context.class_inst) g_assert (!ginst_in_image (method->context.class_inst, image)); if (method->context.method_inst) g_assert (!ginst_in_image (method->context.method_inst, image)); if (((MonoMethod*)method)->signature) g_assert (!signature_in_image (mono_method_signature_internal ((MonoMethod*)method), image)); } static void free_generic_inst (MonoGenericInst *ginst) { int i; /* The ginst itself is allocated from the image set mempool */ for (i = 0; i < ginst->type_argc; ++i) mono_metadata_free_type (ginst->type_argv [i]); } static void free_generic_class (MonoGenericClass *gclass) { /* The gclass itself is allocated from the image set mempool */ if (gclass->cached_class && m_class_get_interface_id (gclass->cached_class)) mono_unload_interface_id (gclass->cached_class); } static void free_inflated_signature (MonoInflatedMethodSignature *sig) { mono_metadata_free_inflated_signature (sig->sig); } static void free_aggregate_modifiers (MonoAggregateModContainer *amods) { for (int i = 0; i < amods->count; i++) mono_metadata_free_type (amods->modifiers [i].type); /* the container itself is allocated in the image set mempool */ } /* * mono_metadata_get_inflated_signature: * * Given an inflated signature and a generic context, return a canonical copy of the * signature. The returned signature might be equal to SIG or it might be a cached copy. */ MonoMethodSignature * mono_metadata_get_inflated_signature (MonoMethodSignature *sig, MonoGenericContext *context) { MonoInflatedMethodSignature helper; MonoInflatedMethodSignature *res; CollectData data; helper.sig = sig; helper.context.class_inst = context->class_inst; helper.context.method_inst = context->method_inst; collect_data_init (&data); collect_inflated_signature_images (&helper, &data); MonoMemoryManager *mm = mono_mem_manager_get_generic (data.images, data.nimages); collect_data_free (&data); mono_mem_manager_lock (mm); if (!mm->gsignature_cache) mm->gsignature_cache = g_hash_table_new_full (inflated_signature_hash, inflated_signature_equal, NULL, (GDestroyNotify)free_inflated_signature); res = (MonoInflatedMethodSignature *)g_hash_table_lookup (mm->gsignature_cache, &helper); if (!res) { res = mono_mem_manager_alloc0 (mm, sizeof (MonoInflatedMethodSignature)); res->sig = sig; res->context.class_inst = context->class_inst; res->context.method_inst = context->method_inst; g_hash_table_insert (mm->gsignature_cache, res, res); } mono_mem_manager_unlock (mm); return res->sig; } MonoMemoryManager * mono_metadata_get_mem_manager_for_type (MonoType *type) { MonoMemoryManager *mm; CollectData image_set_data; collect_data_init (&image_set_data); collect_type_images (type, &image_set_data); mm = mono_mem_manager_get_generic (image_set_data.images, image_set_data.nimages); collect_data_free (&image_set_data); return mm; } MonoMemoryManager * mono_metadata_get_mem_manager_for_class (MonoClass *klass) { return mono_metadata_get_mem_manager_for_type (m_class_get_byval_arg (klass)); } MonoMemoryManager * mono_metadata_get_mem_manager_for_method (MonoMethodInflated *method) { MonoMemoryManager *mm; CollectData image_set_data; collect_data_init (&image_set_data); collect_method_images (method, &image_set_data); mm = mono_mem_manager_get_generic (image_set_data.images, image_set_data.nimages); collect_data_free (&image_set_data); return mm; } static MonoMemoryManager * mono_metadata_get_mem_manager_for_aggregate_modifiers (MonoAggregateModContainer *amods) { MonoMemoryManager *mm; CollectData image_set_data; collect_data_init (&image_set_data); collect_aggregate_modifiers_images (amods, &image_set_data); mm = mono_mem_manager_get_generic (image_set_data.images, image_set_data.nimages); collect_data_free (&image_set_data); return mm; } static gboolean type_is_gtd (MonoType *type) { switch (type->type) { case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: return mono_class_is_gtd (type->data.klass); default: return FALSE; } } /* * mono_metadata_get_generic_inst: * * Given a list of types, return a MonoGenericInst that represents that list. * The returned MonoGenericInst has its own copy of the list of types. The list * passed in the argument can be freed, modified or disposed of. * */ MonoGenericInst * mono_metadata_get_generic_inst (int type_argc, MonoType **type_argv) { MonoGenericInst *ginst; gboolean is_open; int i; int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *); for (i = 0; i < type_argc; ++i) if (mono_class_is_open_constructed_type (type_argv [i])) break; is_open = (i < type_argc); ginst = (MonoGenericInst *)g_alloca (size); memset (ginst, 0, MONO_SIZEOF_GENERIC_INST); ginst->is_open = is_open; ginst->type_argc = type_argc; memcpy (ginst->type_argv, type_argv, type_argc * sizeof (MonoType *)); for (i = 0; i < type_argc; ++i) { MonoType *t = ginst->type_argv [i]; if (type_is_gtd (t)) { ginst->type_argv [i] = mono_class_gtd_get_canonical_inst (t->data.klass); } } return mono_metadata_get_canonical_generic_inst (ginst); } /** * mono_metadata_get_canonical_generic_inst: * \param candidate an arbitrary generic instantiation * * \returns the canonical generic instantiation that represents the given * candidate by identifying the image set for the candidate instantiation and * finding the instance in the image set or adding a copy of the given instance * to the image set. * * The returned MonoGenericInst has its own copy of the list of types. The list * passed in the argument can be freed, modified or disposed of. * */ MonoGenericInst * mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate) { CollectData data; int type_argc = candidate->type_argc; gboolean is_open = candidate->is_open; collect_data_init (&data); collect_ginst_images (candidate, &data); MonoMemoryManager *mm = mono_mem_manager_get_generic (data.images, data.nimages); collect_data_free (&data); mono_mem_manager_lock (mm); if (!mm->ginst_cache) mm->ginst_cache = g_hash_table_new_full (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal, NULL, (GDestroyNotify)free_generic_inst); MonoGenericInst *ginst = (MonoGenericInst *)g_hash_table_lookup (mm->ginst_cache, candidate); if (!ginst) { int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *); ginst = (MonoGenericInst *)mono_mem_manager_alloc0 (mm, size); #ifndef MONO_SMALL_CONFIG ginst->id = mono_atomic_inc_i32 (&next_generic_inst_id); #endif ginst->is_open = is_open; ginst->type_argc = type_argc; // FIXME: Dup into the mem manager for (int i = 0; i < type_argc; ++i) ginst->type_argv [i] = mono_metadata_type_dup (NULL, candidate->type_argv [i]); g_hash_table_insert (mm->ginst_cache, ginst, ginst); } mono_mem_manager_unlock (mm); return ginst; } MonoAggregateModContainer * mono_metadata_get_canonical_aggregate_modifiers (MonoAggregateModContainer *candidate) { g_assert (candidate->count > 0); MonoMemoryManager *mm = mono_metadata_get_mem_manager_for_aggregate_modifiers (candidate); mono_mem_manager_lock (mm); if (!mm->aggregate_modifiers_cache) mm->aggregate_modifiers_cache = g_hash_table_new_full (aggregate_modifiers_hash, aggregate_modifiers_equal, NULL, (GDestroyNotify)free_aggregate_modifiers); MonoAggregateModContainer *amods = (MonoAggregateModContainer *)g_hash_table_lookup (mm->aggregate_modifiers_cache, candidate); if (!amods) { size_t size = mono_sizeof_aggregate_modifiers (candidate->count); amods = (MonoAggregateModContainer *)mono_mem_manager_alloc0 (mm, size); amods->count = candidate->count; for (int i = 0; i < candidate->count; ++i) { amods->modifiers [i].required = candidate->modifiers [i].required; amods->modifiers [i].type = mono_metadata_type_dup (NULL, candidate->modifiers [i].type); } g_hash_table_insert (mm->aggregate_modifiers_cache, amods, amods); } mono_mem_manager_unlock (mm); return amods; } static gboolean mono_metadata_is_type_builder_generic_type_definition (MonoClass *container_class, MonoGenericInst *inst, gboolean is_dynamic) { MonoGenericContainer *container = mono_class_get_generic_container (container_class); if (!is_dynamic || m_class_was_typebuilder (container_class) || container->type_argc != inst->type_argc) return FALSE; return inst == container->context.class_inst; } /* * mono_metadata_lookup_generic_class: * * Returns a MonoGenericClass with the given properties. * */ MonoGenericClass * mono_metadata_lookup_generic_class (MonoClass *container_class, MonoGenericInst *inst, gboolean is_dynamic) { MonoGenericClass *gclass; MonoGenericClass helper; gboolean is_tb_open = mono_metadata_is_type_builder_generic_type_definition (container_class, inst, is_dynamic); CollectData data; g_assert (mono_class_get_generic_container (container_class)->type_argc == inst->type_argc); memset (&helper, 0, sizeof(helper)); // act like g_new0 helper.container_class = container_class; helper.context.class_inst = inst; helper.is_dynamic = is_dynamic; /* We use this in a hash lookup, which does not attempt to downcast the pointer */ helper.is_tb_open = is_tb_open; collect_data_init (&data); collect_gclass_images (&helper, &data); MonoMemoryManager *mm = mono_mem_manager_get_generic (data.images, data.nimages); collect_data_free (&data); if (!mm->gclass_cache) { mono_mem_manager_lock (mm); if (!mm->gclass_cache) { MonoConcurrentHashTable *cache = mono_conc_hashtable_new_full (mono_generic_class_hash, mono_generic_class_equal, NULL, (GDestroyNotify)free_generic_class); mono_memory_barrier (); mm->gclass_cache = cache; } mono_mem_manager_unlock (mm); } gclass = (MonoGenericClass *)mono_conc_hashtable_lookup (mm->gclass_cache, &helper); /* A tripwire just to keep us honest */ g_assert (!helper.cached_class); if (gclass) return gclass; mono_mem_manager_lock (mm); gclass = mono_mem_manager_alloc0 (mm, sizeof (MonoGenericClass)); if (is_dynamic) gclass->is_dynamic = 1; gclass->is_tb_open = is_tb_open; gclass->container_class = container_class; gclass->context.class_inst = inst; gclass->context.method_inst = NULL; gclass->owner = mm; if (inst == mono_class_get_generic_container (container_class)->context.class_inst && !is_tb_open) gclass->cached_class = container_class; MonoGenericClass *gclass2 = (MonoGenericClass*)mono_conc_hashtable_insert (mm->gclass_cache, gclass, gclass); if (!gclass2) gclass2 = gclass; // g_hash_table_insert (set->gclass_cache, gclass, gclass); mono_mem_manager_unlock (mm); return gclass2; } /* * mono_metadata_inflate_generic_inst: * * Instantiate the generic instance @ginst with the context @context. * Check @error for success. * */ MonoGenericInst * mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context, MonoError *error) { MonoType **type_argv; MonoGenericInst *nginst = NULL; int i, count = 0; error_init (error); if (!ginst->is_open) return ginst; type_argv = g_new0 (MonoType*, ginst->type_argc); for (i = 0; i < ginst->type_argc; i++) { type_argv [i] = mono_class_inflate_generic_type_checked (ginst->type_argv [i], context, error); if (!is_ok (error)) goto cleanup; ++count; } nginst = mono_metadata_get_generic_inst (ginst->type_argc, type_argv); cleanup: for (i = 0; i < count; i++) mono_metadata_free_type (type_argv [i]); g_free (type_argv); return nginst; } MonoGenericInst * mono_metadata_parse_generic_inst (MonoImage *m, MonoGenericContainer *container, int count, const char *ptr, const char **rptr, MonoError *error) { MonoType **type_argv; MonoGenericInst *ginst = NULL; int i, parse_count = 0; error_init (error); type_argv = g_new0 (MonoType*, count); for (i = 0; i < count; i++) { /* this can be a transient type, mono_metadata_get_generic_inst will allocate * a canonical one, if needed. */ MonoType *t = mono_metadata_parse_type_checked (m, container, 0, TRUE, ptr, &ptr, error); if (!t) goto cleanup; type_argv [i] = t; parse_count++; } if (rptr) *rptr = ptr; g_assert (parse_count == count); ginst = mono_metadata_get_generic_inst (count, type_argv); cleanup: for (i = 0; i < parse_count; i++) mono_metadata_free_type (type_argv [i]); g_free (type_argv); return ginst; } static gboolean do_mono_metadata_parse_generic_class (MonoType *type, MonoImage *m, MonoGenericContainer *container, const char *ptr, const char **rptr, MonoError *error) { MonoGenericInst *inst; MonoClass *gklass; MonoType *gtype; int count; error_init (error); // XXX how about transient? gtype = mono_metadata_parse_type_checked (m, NULL, 0, FALSE, ptr, &ptr, error); if (gtype == NULL) return FALSE; gklass = mono_class_from_mono_type_internal (gtype); if (!mono_class_is_gtd (gklass)) { mono_error_set_bad_image (error, m, "Generic instance with non-generic definition"); return FALSE; } count = mono_metadata_decode_value (ptr, &ptr); inst = mono_metadata_parse_generic_inst (m, container, count, ptr, &ptr, error); if (inst == NULL) return FALSE; if (rptr) *rptr = ptr; type->data.generic_class = mono_metadata_lookup_generic_class (gklass, inst, FALSE); return TRUE; } /* * select_container: * @gc: The generic container to normalize * @type: The kind of generic parameters the resulting generic-container should contain */ static MonoGenericContainer * select_container (MonoGenericContainer *gc, MonoTypeEnum type) { gboolean is_var = (type == MONO_TYPE_VAR); if (!gc) return NULL; g_assert (is_var || type == MONO_TYPE_MVAR); if (is_var) { if (gc->is_method || gc->parent) /* * The current MonoGenericContainer is a generic method -> its `parent' * points to the containing class'es container. */ return gc->parent; } return gc; } MonoGenericContainer * mono_get_anonymous_container_for_image (MonoImage *image, gboolean is_mvar) { MonoGenericContainer **container_pointer; if (is_mvar) container_pointer = &image->anonymous_generic_method_container; else container_pointer = &image->anonymous_generic_class_container; MonoGenericContainer *result = *container_pointer; // This container has never been created; make it now. if (!result) { // Note this is never deallocated anywhere-- it exists for the lifetime of the image it's allocated from result = (MonoGenericContainer *)mono_image_alloc0 (image, sizeof (MonoGenericContainer)); result->owner.image = image; result->is_anonymous = TRUE; result->is_method = is_mvar; // If another thread already made a container, use that and leak this new one. // (Technically it would currently be safe to just assign instead of CASing.) MonoGenericContainer *exchange = (MonoGenericContainer *)mono_atomic_cas_ptr ((volatile gpointer *)container_pointer, result, NULL); if (exchange) result = exchange; } return result; } #define FAST_GPARAM_CACHE_SIZE 16 static MonoGenericParam* lookup_anon_gparam (MonoImage *image, MonoGenericContainer *container, gint32 param_num, gboolean is_mvar) { if (param_num >= 0 && param_num < FAST_GPARAM_CACHE_SIZE) { MonoGenericParam *cache = is_mvar ? image->mvar_gparam_cache_fast : image->var_gparam_cache_fast; if (!cache) return NULL; return &cache[param_num]; } else { MonoGenericParam key; memset (&key, 0, sizeof (key)); key.owner = container; key.num = param_num; key.gshared_constraint = NULL; MonoConcurrentHashTable *cache = is_mvar ? image->mvar_gparam_cache : image->var_gparam_cache; if (!cache) return NULL; return (MonoGenericParam*)mono_conc_hashtable_lookup (cache, &key); } } static MonoGenericParam* publish_anon_gparam_fast (MonoImage *image, MonoGenericContainer *container, gint32 param_num) { g_assert (param_num >= 0 && param_num < FAST_GPARAM_CACHE_SIZE); MonoGenericParam **cache = container->is_method ? &image->mvar_gparam_cache_fast : &image->var_gparam_cache_fast; if (!*cache) { mono_image_lock (image); if (!*cache) { *cache = (MonoGenericParam*)mono_image_alloc0 (image, sizeof (MonoGenericParam) * FAST_GPARAM_CACHE_SIZE); for (gint32 i = 0; i < FAST_GPARAM_CACHE_SIZE; ++i) { MonoGenericParam *param = &(*cache)[i]; param->owner = container; param->num = i; } } mono_image_unlock (image); } return &(*cache)[param_num]; } /* * publish_anon_gparam_slow: * * Publish \p gparam anonymous generic parameter to the anon gparam cache for \p image. * * LOCKING: takes the image lock. */ static MonoGenericParam* publish_anon_gparam_slow (MonoImage *image, MonoGenericParam *gparam) { MonoConcurrentHashTable **cache = gparam->owner->is_method ? &image->mvar_gparam_cache : &image->var_gparam_cache; if (!*cache) { mono_image_lock (image); if (!*cache) { MonoConcurrentHashTable *ht = mono_conc_hashtable_new ((GHashFunc)mono_metadata_generic_param_hash, (GEqualFunc) mono_metadata_generic_param_equal); mono_atomic_store_release (cache, ht); } mono_image_unlock (image); } MonoGenericParam *other = (MonoGenericParam*)mono_conc_hashtable_insert (*cache, gparam, gparam); // If another thread published first return their param, otherwise return ours. return other ? other : gparam; } /** * mono_metadata_create_anon_gparam: * \param image the MonoImage that owns the anonymous generic parameter * \param param_num the parameter number * \param is_mvar TRUE if this is a method generic parameter, FALSE if it's a class generic parameter. * * Returns: a new, or exisisting \c MonoGenericParam for an anonymous generic parameter with the given properties. * * LOCKING: takes the image lock. */ MonoGenericParam* mono_metadata_create_anon_gparam (MonoImage *image, gint32 param_num, gboolean is_mvar) { MonoGenericContainer *container = mono_get_anonymous_container_for_image (image, is_mvar); MonoGenericParam *gparam = lookup_anon_gparam (image, container, param_num, is_mvar); if (gparam) return gparam; if (param_num >= 0 && param_num < FAST_GPARAM_CACHE_SIZE) { return publish_anon_gparam_fast (image, container, param_num); } else { // Create a candidate generic param and try to insert it in the cache. // If multiple threads both try to publish the same param, all but one // will leak, but that's okay. gparam = (MonoGenericParam*)mono_image_alloc0 (image, sizeof (MonoGenericParam)); gparam->owner = container; gparam->num = param_num; return publish_anon_gparam_slow (image, gparam); } } /* * mono_metadata_parse_generic_param: * @generic_container: Our MonoClass's or MonoMethod's MonoGenericContainer; * see mono_metadata_parse_type_checked() for details. * Internal routine to parse a generic type parameter. * LOCKING: Acquires the loader lock */ static MonoGenericParam * mono_metadata_parse_generic_param (MonoImage *m, MonoGenericContainer *generic_container, MonoTypeEnum type, const char *ptr, const char **rptr, MonoError *error) { int index = mono_metadata_decode_value (ptr, &ptr); if (rptr) *rptr = ptr; error_init (error); generic_container = select_container (generic_container, type); if (!generic_container) { gboolean is_mvar = FALSE; switch (type) { case MONO_TYPE_VAR: break; case MONO_TYPE_MVAR: is_mvar = TRUE; break; default: g_error ("Cerating generic param object with invalid MonoType"); // This is not a generic param } return mono_metadata_create_anon_gparam (m, index, is_mvar); } if (index >= generic_container->type_argc) { mono_error_set_bad_image (error, m, "Invalid generic %s parameter index %d, max index is %d", generic_container->is_method ? "method" : "type", index, generic_container->type_argc); return NULL; } //This can't return NULL return mono_generic_container_get_param (generic_container, index); } /* * mono_metadata_get_shared_type: * * Return a shared instance of TYPE, if available, NULL otherwise. * Shared MonoType instances help save memory. Their contents should not be modified * by the caller. They do not need to be freed as their lifetime is bound by either * the lifetime of the runtime (builtin types), or the lifetime of the MonoClass * instance they are embedded in. If they are freed, they should be freed using * mono_metadata_free_type () instead of g_free (). */ MonoType* mono_metadata_get_shared_type (MonoType *type) { MonoType *cached; /* No need to use locking since nobody is modifying the hash table */ if ((cached = (MonoType *)g_hash_table_lookup (type_cache, type))) return cached; switch (type->type){ case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: if (type == m_class_get_byval_arg (type->data.klass)) return type; if (type == m_class_get_this_arg (type->data.klass)) return type; break; default: break; } return NULL; } static gboolean compare_type_literals (MonoImage *image, int class_type, int type_type, MonoError *error) { error_init (error); /* _byval_arg.type can be zero if we're decoding a type that references a class been loading. * See mcs/test/gtest-440. and #650936. * FIXME This better be moved to the metadata verifier as it can catch more cases. */ if (!class_type) return TRUE; /* NET 1.1 assemblies might encode string and object in a denormalized way. * See #675464. */ if (class_type == type_type) return TRUE; if (type_type == MONO_TYPE_CLASS) { if (class_type == MONO_TYPE_STRING || class_type == MONO_TYPE_OBJECT) return TRUE; //XXX stringify this argument mono_error_set_bad_image (error, image, "Expected reference type but got type kind %d", class_type); return FALSE; } g_assert (type_type == MONO_TYPE_VALUETYPE); switch (class_type) { case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_CLASS: return TRUE; default: //XXX stringify this argument mono_error_set_bad_image (error, image, "Expected value type but got type kind %d", class_type); return FALSE; } } static gboolean verify_var_type_and_container (MonoImage *image, int var_type, MonoGenericContainer *container, MonoError *error) { error_init (error); if (var_type == MONO_TYPE_MVAR) { if (!container->is_method) { //MVAR and a method container mono_error_set_bad_image (error, image, "MVAR parsed in a context without a method container"); return FALSE; } } else { if (!(!container->is_method || //VAR and class container (container->is_method && container->parent))) { //VAR and method container with parent mono_error_set_bad_image (error, image, "VAR parsed in a context without a class container"); return FALSE; } } return TRUE; } /* * do_mono_metadata_parse_type: * @type: MonoType to be filled in with the return value * @m: image context * @generic_context: generics_context * @transient: whenever to allocate data from the heap * @ptr: pointer to the encoded type * @rptr: pointer where the end of the encoded type is saved * * Internal routine used to "fill" the contents of @type from an * allocated pointer. This is done this way to avoid doing too * many mini-allocations (particularly for the MonoFieldType which * most of the time is just a MonoType, but sometimes might be augmented). * * This routine is used by mono_metadata_parse_type and * mono_metadata_parse_field_type * * This extracts a Type as specified in Partition II (22.2.12) * * Returns: FALSE if the type could not be loaded */ static gboolean do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container, gboolean transient, const char *ptr, const char **rptr, MonoError *error) { error_init (error); type->type = (MonoTypeEnum)mono_metadata_decode_value (ptr, &ptr); switch (type->type){ case MONO_TYPE_VOID: case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_TYPEDBYREF: break; case MONO_TYPE_VALUETYPE: case MONO_TYPE_CLASS: { guint32 token; MonoClass *klass; token = mono_metadata_parse_typedef_or_ref (m, ptr, &ptr); klass = mono_class_get_checked (m, token, error); type->data.klass = klass; if (!klass) return FALSE; if (!compare_type_literals (m, m_class_get_byval_arg (klass)->type, type->type, error)) return FALSE; break; } case MONO_TYPE_SZARRAY: { MonoType *etype = mono_metadata_parse_type_checked (m, container, 0, transient, ptr, &ptr, error); if (!etype) return FALSE; type->data.klass = mono_class_from_mono_type_internal (etype); if (transient) mono_metadata_free_type (etype); g_assert (type->data.klass); //This was previously a check for NULL, but mcfmt should never fail. It can return a borken MonoClass, but should return at least something. break; } case MONO_TYPE_PTR: { type->data.type = mono_metadata_parse_type_checked (m, container, 0, transient, ptr, &ptr, error); if (!type->data.type) return FALSE; break; } case MONO_TYPE_FNPTR: { type->data.method = mono_metadata_parse_method_signature_full (m, container, 0, ptr, &ptr, error); if (!type->data.method) return FALSE; break; } case MONO_TYPE_ARRAY: { type->data.array = mono_metadata_parse_array_internal (m, container, transient, ptr, &ptr, error); if (!type->data.array) return FALSE; break; } case MONO_TYPE_MVAR: case MONO_TYPE_VAR: { if (container && !verify_var_type_and_container (m, type->type, container, error)) return FALSE; type->data.generic_param = mono_metadata_parse_generic_param (m, container, type->type, ptr, &ptr, error); if (!type->data.generic_param) return FALSE; break; } case MONO_TYPE_GENERICINST: { if (!do_mono_metadata_parse_generic_class (type, m, container, ptr, &ptr, error)) return FALSE; break; } default: mono_error_set_bad_image (error, m, "type 0x%02x not handled in do_mono_metadata_parse_type on image %s", type->type, m->name); return FALSE; } if (rptr) *rptr = ptr; return TRUE; } /** * mono_metadata_free_type: * \param type type to free * * Free the memory allocated for type \p type which is allocated on the heap. */ void mono_metadata_free_type (MonoType *type) { /* Note: keep in sync with do_mono_metadata_parse_type and try_get_canonical_type which * allocate memory or try to avoid allocating memory. */ if (type >= builtin_types && type < builtin_types + G_N_ELEMENTS (builtin_types)) return; switch (type->type){ case MONO_TYPE_OBJECT: case MONO_TYPE_STRING: if (!type->data.klass) break; /* fall through */ case MONO_TYPE_CLASS: case MONO_TYPE_VALUETYPE: if (type == m_class_get_byval_arg (type->data.klass) || type == m_class_get_this_arg (type->data.klass)) return; break; case MONO_TYPE_PTR: mono_metadata_free_type (type->data.type); break; case MONO_TYPE_FNPTR: mono_metadata_free_method_signature (type->data.method); break; case MONO_TYPE_ARRAY: mono_metadata_free_array (type->data.array); break; default: break; } g_free (type); } #if 0 static void hex_dump (const char *buffer, int base, int count) { int show_header = 1; int i; if (count < 0){ count = -count; show_header = 0; } for (i = 0; i < count; i++){ if (show_header) if ((i % 16) == 0) printf ("\n0x%08x: ", (unsigned char) base + i); printf ("%02x ", (unsigned char) (buffer [i])); } fflush (stdout); } #endif /** * @ptr: Points to the beginning of the Section Data (25.3) */ static MonoExceptionClause* parse_section_data (MonoImage *m, int *num_clauses, const unsigned char *ptr, MonoError *error) { unsigned char sect_data_flags; int is_fat; guint32 sect_data_len; MonoExceptionClause* clauses = NULL; error_init (error); while (1) { /* align on 32-bit boundary */ ptr = dword_align (ptr); sect_data_flags = *ptr; ptr++; is_fat = sect_data_flags & METHOD_HEADER_SECTION_FAT_FORMAT; if (is_fat) { sect_data_len = (ptr [2] << 16) | (ptr [1] << 8) | ptr [0]; ptr += 3; } else { sect_data_len = ptr [0]; ++ptr; } if (sect_data_flags & METHOD_HEADER_SECTION_EHTABLE) { const unsigned char *p = dword_align (ptr); int i; *num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12; /* we could just store a pointer if we don't need to byteswap */ clauses = (MonoExceptionClause *)g_malloc0 (sizeof (MonoExceptionClause) * (*num_clauses)); for (i = 0; i < *num_clauses; ++i) { MonoExceptionClause *ec = &clauses [i]; guint32 tof_value; if (is_fat) { ec->flags = read32 (p); ec->try_offset = read32 (p + 4); ec->try_len = read32 (p + 8); ec->handler_offset = read32 (p + 12); ec->handler_len = read32 (p + 16); tof_value = read32 (p + 20); p += 24; } else { ec->flags = read16 (p); ec->try_offset = read16 (p + 2); ec->try_len = *(p + 4); ec->handler_offset = read16 (p + 5); ec->handler_len = *(p + 7); tof_value = read32 (p + 8); p += 12; } if (ec->flags == MONO_EXCEPTION_CLAUSE_FILTER) { ec->data.filter_offset = tof_value; } else if (ec->flags == MONO_EXCEPTION_CLAUSE_NONE) { ec->data.catch_class = NULL; if (tof_value) { ec->data.catch_class = mono_class_get_checked (m, tof_value, error); if (!is_ok (error)) { g_free (clauses); return NULL; } } } else { ec->data.catch_class = NULL; } /* g_print ("try %d: %x %04x-%04x %04x\n", i, ec->flags, ec->try_offset, ec->try_offset+ec->try_len, ec->try_len); */ } } if (sect_data_flags & METHOD_HEADER_SECTION_MORE_SECTS) ptr += sect_data_len - 4; /* LAMESPEC: it seems the size includes the header */ else return clauses; } } /* * mono_method_get_header_summary: * @method: The method to get the header. * @summary: Where to store the header * * * Returns: TRUE if the header was properly decoded. */ gboolean mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *summary) { int idx; guint32 rva; MonoImage* img; const char *ptr; unsigned char flags, format; guint16 fat_flags; /*Only the GMD has a pointer to the metadata.*/ while (method->is_inflated) method = ((MonoMethodInflated*)method)->declaring; summary->code = NULL; summary->code_size = 0; summary->max_stack = 0; summary->has_clauses = FALSE; summary->has_locals = FALSE; /*FIXME extract this into a MACRO and share it with mono_method_get_header*/ if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) return FALSE; if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) { MonoMethodHeader *header = ((MonoMethodWrapper *)method)->header; if (!header) return FALSE; summary->code = header->code; summary->code_size = header->code_size; summary->max_stack = header->max_stack; summary->has_clauses = header->num_clauses > 0; summary->has_locals = header->num_locals > 0; return TRUE; } idx = mono_metadata_token_index (method->token); img = m_class_get_image (method->klass); rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA); ptr = mono_image_rva_map (img, rva); if (!ptr) return FALSE; flags = *(const unsigned char *)ptr; format = flags & METHOD_HEADER_FORMAT_MASK; switch (format) { case METHOD_HEADER_TINY_FORMAT: ptr++; summary->max_stack = 8; summary->code = (unsigned char *) ptr; summary->code_size = flags >> 2; break; case METHOD_HEADER_FAT_FORMAT: fat_flags = read16 (ptr); ptr += 2; summary->max_stack = read16 (ptr); ptr += 2; summary->code_size = read32 (ptr); ptr += 4; summary->has_locals = !!read32 (ptr); ptr += 4; if (fat_flags & METHOD_HEADER_MORE_SECTS) summary->has_clauses = TRUE; summary->code = (unsigned char *) ptr; break; default: return FALSE; } return TRUE; } /* * mono_metadata_parse_mh_full: * @m: metadata context * @generic_context: generics context * @ptr: pointer to the method header. * * Decode the method header at @ptr, including pointer to the IL code, * info about local variables and optional exception tables. * This is a Mono runtime internal function. * * LOCKING: Acquires the loader lock. * * Returns: a transient MonoMethodHeader allocated from the heap. */ MonoMethodHeader * mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, const char *ptr, MonoError *error) { MonoMethodHeader *mh = NULL; unsigned char flags = *(const unsigned char *) ptr; unsigned char format = flags & METHOD_HEADER_FORMAT_MASK; guint16 fat_flags; guint32 local_var_sig_tok, max_stack, code_size, init_locals; const unsigned char *code; MonoExceptionClause* clauses = NULL; int num_clauses = 0; MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG]; guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE]; error_init (error); if (!ptr) { mono_error_set_bad_image (error, m, "Method header with null pointer"); return NULL; } switch (format) { case METHOD_HEADER_TINY_FORMAT: mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER); ptr++; mh->max_stack = 8; mh->is_transient = TRUE; local_var_sig_tok = 0; mh->code_size = flags >> 2; mh->code = (unsigned char*)ptr; return mh; case METHOD_HEADER_FAT_FORMAT: fat_flags = read16 (ptr); ptr += 2; max_stack = read16 (ptr); ptr += 2; code_size = read32 (ptr); ptr += 4; local_var_sig_tok = read32 (ptr); ptr += 4; if (fat_flags & METHOD_HEADER_INIT_LOCALS) init_locals = 1; else init_locals = 0; code = (unsigned char*)ptr; if (!(fat_flags & METHOD_HEADER_MORE_SECTS)) break; /* * There are more sections */ ptr = (char*)code + code_size; break; default: mono_error_set_bad_image (error, m, "Invalid method header format %d", format); return NULL; } if (local_var_sig_tok) { int idx = mono_metadata_token_index (local_var_sig_tok) - 1; if (mono_metadata_table_bounds_check (m, MONO_TABLE_STANDALONESIG, idx + 1)) { mono_error_set_bad_image (error, m, "Invalid method header local vars signature token 0x%08x", idx); goto fail; } mono_metadata_decode_row (t, idx, cols, MONO_STAND_ALONE_SIGNATURE_SIZE); } if (fat_flags & METHOD_HEADER_MORE_SECTS) { clauses = parse_section_data (m, &num_clauses, (const unsigned char*)ptr, error); goto_if_nok (error, fail); } if (local_var_sig_tok) { const char *locals_ptr; int len=0, i; locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]); mono_metadata_decode_blob_size (locals_ptr, &locals_ptr); if (*locals_ptr != 0x07) g_warning ("wrong signature for locals blob"); locals_ptr++; len = mono_metadata_decode_value (locals_ptr, &locals_ptr); mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + len * sizeof (MonoType*) + num_clauses * sizeof (MonoExceptionClause)); mh->num_locals = len; for (i = 0; i < len; ++i) { mh->locals [i] = mono_metadata_parse_type_internal (m, container, 0, TRUE, locals_ptr, &locals_ptr, error); goto_if_nok (error, fail); } } else { mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + num_clauses * sizeof (MonoExceptionClause)); } mh->code = code; mh->code_size = code_size; mh->max_stack = max_stack; mh->is_transient = TRUE; mh->init_locals = init_locals; if (clauses) { MonoExceptionClause* clausesp = (MonoExceptionClause*)&mh->locals [mh->num_locals]; memcpy (clausesp, clauses, num_clauses * sizeof (MonoExceptionClause)); g_free (clauses); mh->clauses = clausesp; mh->num_clauses = num_clauses; } return mh; fail: g_free (clauses); g_free (mh); return NULL; } /** * mono_metadata_parse_mh: * \param generic_context generics context * \param ptr pointer to the method header. * * Decode the method header at \p ptr, including pointer to the IL code, * info about local variables and optional exception tables. * * \returns a transient \c MonoMethodHeader allocated from the heap. */ MonoMethodHeader * mono_metadata_parse_mh (MonoImage *m, const char *ptr) { ERROR_DECL (error); MonoMethodHeader *header = mono_metadata_parse_mh_full (m, NULL, ptr, error); mono_error_cleanup (error); return header; } /** * mono_metadata_free_mh: * \param mh a method header * * Free the memory allocated for the method header. */ void mono_metadata_free_mh (MonoMethodHeader *mh) { int i; /* If it is not transient it means it's part of a wrapper method, * or a SRE-generated method, so the lifetime in that case is * dictated by the method's own lifetime */ if (mh && mh->is_transient) { for (i = 0; i < mh->num_locals; ++i) mono_metadata_free_type (mh->locals [i]); g_free (mh); } } /** * mono_method_header_get_code: * \param header a \c MonoMethodHeader pointer * \param code_size memory location for returning the code size * \param max_stack memory location for returning the max stack * * Method header accessor to retreive info about the IL code properties: * a pointer to the IL code itself, the size of the code and the max number * of stack slots used by the code. * * \returns pointer to the IL code represented by the method header. */ const unsigned char* mono_method_header_get_code (MonoMethodHeader *header, guint32* code_size, guint32* max_stack) { if (code_size) *code_size = header->code_size; if (max_stack) *max_stack = header->max_stack; return header->code; } /** * mono_method_header_get_locals: * \param header a \c MonoMethodHeader pointer * \param num_locals memory location for returning the number of local variables * \param init_locals memory location for returning the init_locals flag * * Method header accessor to retreive info about the local variables: * an array of local types, the number of locals and whether the locals * are supposed to be initialized to 0 on method entry * * \returns pointer to an array of types of the local variables */ MonoType** mono_method_header_get_locals (MonoMethodHeader *header, guint32* num_locals, gboolean *init_locals) { if (num_locals) *num_locals = header->num_locals; if (init_locals) *init_locals = header->init_locals; return header->locals; } /* * mono_method_header_get_num_clauses: * @header: a MonoMethodHeader pointer * * Method header accessor to retreive the number of exception clauses. * * Returns: the number of exception clauses present */ int mono_method_header_get_num_clauses (MonoMethodHeader *header) { return header->num_clauses; } /** * mono_method_header_get_clauses: * \param header a \c MonoMethodHeader pointer * \param method \c MonoMethod the header belongs to * \param iter pointer to a iterator * \param clause pointer to a \c MonoExceptionClause structure which will be filled with the info * * Get the info about the exception clauses in the method. Set \c *iter to NULL to * initiate the iteration, then call the method repeatedly until it returns FALSE. * At each iteration, the structure pointed to by clause if filled with the * exception clause information. * * \returns TRUE if clause was filled with info, FALSE if there are no more exception * clauses. */ int mono_method_header_get_clauses (MonoMethodHeader *header, MonoMethod *method, gpointer *iter, MonoExceptionClause *clause) { MonoExceptionClause *sc; /* later we'll be able to use this interface to parse the clause info on demand, * without allocating anything. */ if (!iter || !header->num_clauses) return FALSE; if (!*iter) { *iter = sc = header->clauses; *clause = *sc; return TRUE; } sc = (MonoExceptionClause *)*iter; sc++; if (sc < header->clauses + header->num_clauses) { *iter = sc; *clause = *sc; return TRUE; } return FALSE; } /** * mono_metadata_parse_field_type: * \param m metadata context to extract information from * \param ptr pointer to the field signature * \param rptr pointer updated to match the end of the decoded stream * * Parses the field signature, and returns the type information for it. * * \returns The \c MonoType that was extracted from \p ptr . */ MonoType * mono_metadata_parse_field_type (MonoImage *m, short field_flags, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoType * type = mono_metadata_parse_type_internal (m, NULL, field_flags, FALSE, ptr, rptr, error); mono_error_cleanup (error); return type; } /** * mono_metadata_parse_param: * \param m metadata context to extract information from * \param ptr pointer to the param signature * \param rptr pointer updated to match the end of the decoded stream * * Parses the param signature, and returns the type information for it. * * \returns The \c MonoType that was extracted from \p ptr . */ MonoType * mono_metadata_parse_param (MonoImage *m, const char *ptr, const char **rptr) { ERROR_DECL (error); MonoType * type = mono_metadata_parse_type_internal (m, NULL, 0, FALSE, ptr, rptr, error); mono_error_cleanup (error); return type; } /** * mono_metadata_token_from_dor: * \param dor_token A \c TypeDefOrRef coded index * * \p dor_token is a \c TypeDefOrRef coded index: it contains either * a \c TypeDef, \c TypeRef or \c TypeSpec in the lower bits, and the upper * bits contain an index into the table. * * \returns an expanded token */ guint32 mono_metadata_token_from_dor (guint32 dor_index) { guint32 table, idx; table = dor_index & 0x03; idx = dor_index >> 2; switch (table){ case 0: /* TypeDef */ return MONO_TOKEN_TYPE_DEF | idx; case 1: /* TypeRef */ return MONO_TOKEN_TYPE_REF | idx; case 2: /* TypeSpec */ return MONO_TOKEN_TYPE_SPEC | idx; default: g_assert_not_reached (); } return 0; } /* * We use this to pass context information to the row locator */ typedef struct { int idx; /* The index that we are trying to locate */ int col_idx; /* The index in the row where idx may be stored */ MonoTableInfo *t; /* pointer to the table */ guint32 result; } locator_t; /* * How the row locator works. * * Table A * ___|___ * ___|___ Table B * ___|___------> _______ * ___|___ _______ * * A column in the rows of table A references an index in table B. * For example A may be the TYPEDEF table and B the METHODDEF table. * * Given an index in table B we want to get the row in table A * where the column n references our index in B. * * In the locator_t structure: * t is table A * col_idx is the column number * index is the index in table B * result will be the index in table A * * Examples: * Table A Table B column (in table A) * TYPEDEF METHODDEF MONO_TYPEDEF_METHOD_LIST * TYPEDEF FIELD MONO_TYPEDEF_FIELD_LIST * PROPERTYMAP PROPERTY MONO_PROPERTY_MAP_PROPERTY_LIST * INTERFIMPL TYPEDEF MONO_INTERFACEIMPL_CLASS * METHODSEM PROPERTY ASSOCIATION (encoded index) * * Note that we still don't support encoded indexes. * */ static int typedef_locator (const void *a, const void *b) { locator_t *loc = (locator_t *) a; const char *bb = (const char *) b; int typedef_index = (bb - loc->t->base) / loc->t->row_size; guint32 col, col_next; col = mono_metadata_decode_row_col (loc->t, typedef_index, loc->col_idx); if (loc->idx < col) return -1; /* * Need to check that the next row is valid. */ if (typedef_index + 1 < table_info_get_rows (loc->t)) { col_next = mono_metadata_decode_row_col (loc->t, typedef_index + 1, loc->col_idx); if (loc->idx >= col_next) return 1; if (col == col_next) return 1; } loc->result = typedef_index; return 0; } static int table_locator (const void *a, const void *b) { locator_t *loc = (locator_t *) a; const char *bb = (const char *) b; guint32 table_index = (bb - loc->t->base) / loc->t->row_size; guint32 col; col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx); if (loc->idx == col) { loc->result = table_index; return 0; } if (loc->idx < col) return -1; else return 1; } static int declsec_locator (const void *a, const void *b) { locator_t *loc = (locator_t *) a; const char *bb = (const char *) b; guint32 table_index = (bb - loc->t->base) / loc->t->row_size; guint32 col; col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx); if (loc->idx == col) { loc->result = table_index; return 0; } if (loc->idx < col) return -1; else return 1; } /** * search_ptr_table: * * Return the 1-based row index in TABLE, which must be one of the *Ptr tables, * which contains IDX. */ static guint32 search_ptr_table (MonoImage *image, int table, int idx) { MonoTableInfo *ptrdef = &image->tables [table]; int rows = table_info_get_rows (ptrdef); int i; /* Use a linear search to find our index in the table */ for (i = 0; i < rows; i ++) /* All the Ptr tables have the same structure */ if (mono_metadata_decode_row_col (ptrdef, i, 0) == idx) break; if (i < rows) return i + 1; else return idx; } /** * mono_metadata_typedef_from_field: * \param meta metadata context * \param index FieldDef token * * \returns the 1-based index into the \c TypeDef table of the type that * declared the field described by \p index, or 0 if not found. */ guint32 mono_metadata_typedef_from_field (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF]; locator_t loc; if (!tdef->base) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_TYPEDEF_FIELD_LIST; loc.t = tdef; if (meta->uncompressed_metadata) loc.idx = search_ptr_table (meta, MONO_TABLE_FIELD_POINTER, loc.idx); /* if it's not in the base image, look in the hot reload table */ gboolean added = (loc.idx > table_info_get_rows (&meta->tables [MONO_TABLE_FIELD])); if (added) { uint32_t res = mono_component_hot_reload()->field_parent (meta, loc.idx); return res; /* 0 if not found, otherwise 1-based */ } if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, typedef_locator)) return 0; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_typedef_from_method: * \param meta metadata context * \param index \c MethodDef token * \returns the 1-based index into the \c TypeDef table of the type that * declared the method described by \p index. 0 if not found. */ guint32 mono_metadata_typedef_from_method (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF]; locator_t loc; if (!tdef->base) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_TYPEDEF_METHOD_LIST; loc.t = tdef; if (meta->uncompressed_metadata) loc.idx = search_ptr_table (meta, MONO_TABLE_METHOD_POINTER, loc.idx); /* if it's not in the base image, look in the hot reload table */ gboolean added = (loc.idx > table_info_get_rows (&meta->tables [MONO_TABLE_METHOD])); if (added) { uint32_t res = mono_component_hot_reload ()->method_parent (meta, loc.idx); return res; /* 0 if not found, otherwise 1-based */ } if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, typedef_locator)) return 0; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_interfaces_from_typedef_full: * \param meta metadata context * \param index typedef token * \param interfaces Out parameter used to store the interface array * \param count Out parameter used to store the number of interfaces * \param heap_alloc_result if TRUE the result array will be \c g_malloc'd * \param context The generic context * \param error set on error * * The array of interfaces that the \p index typedef token implements is returned in * \p interfaces. The number of elements in the array is returned in \p count. * * \returns \c TRUE on success, \c FALSE on failure and sets \p error. */ gboolean mono_metadata_interfaces_from_typedef_full (MonoImage *meta, guint32 index, MonoClass ***interfaces, guint *count, gboolean heap_alloc_result, MonoGenericContext *context, MonoError *error) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_INTERFACEIMPL]; locator_t loc; guint32 start, pos; guint32 cols [MONO_INTERFACEIMPL_SIZE]; MonoClass **result; *interfaces = NULL; *count = 0; error_init (error); if (!tdef->base) return TRUE; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_INTERFACEIMPL_CLASS; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return TRUE; start = loc.result; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_INTERFACEIMPL_CLASS)) start--; else break; } pos = start; int rows = table_info_get_rows (tdef); while (pos < rows) { mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE); if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx) break; ++pos; } if (heap_alloc_result) result = g_new0 (MonoClass*, pos - start); else result = (MonoClass **)mono_image_alloc0 (meta, sizeof (MonoClass*) * (pos - start)); pos = start; while (pos < rows) { MonoClass *iface; mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE); if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx) break; iface = mono_class_get_and_inflate_typespec_checked ( meta, mono_metadata_token_from_dor (cols [MONO_INTERFACEIMPL_INTERFACE]), context, error); if (iface == NULL) return FALSE; result [pos - start] = iface; ++pos; } *count = pos - start; *interfaces = result; return TRUE; } /** * mono_metadata_interfaces_from_typedef: * \param meta metadata context * \param index typedef token * \param count Out parameter used to store the number of interfaces * * The array of interfaces that the \p index typedef token implements is returned in * \p interfaces. The number of elements in the array is returned in \p count. The returned * array is allocated with \c g_malloc and the caller must free it. * * LOCKING: Acquires the loader lock . * * \returns the interface array on success, NULL on failure. */ MonoClass** mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *count) { ERROR_DECL (error); MonoClass **interfaces = NULL; gboolean rv; rv = mono_metadata_interfaces_from_typedef_full (meta, index, &interfaces, count, TRUE, NULL, error); mono_error_assert_ok (error); if (rv) return interfaces; else return NULL; } /** * mono_metadata_nested_in_typedef: * \param meta metadata context * \param index typedef token * \returns the 1-based index into the TypeDef table of the type * where the type described by \p index is nested. * Returns 0 if \p index describes a non-nested type. */ guint32 mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS]; locator_t loc; if (!tdef->base && !meta->has_updates) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_NESTED_CLASS_NESTED; loc.t = tdef; gboolean found = tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator) != NULL; if (!found && !meta->has_updates) return 0; if (G_UNLIKELY (meta->has_updates)) { if (!found && !mono_metadata_update_metadata_linear_search (meta, tdef, &loc, table_locator)) return 0; } /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF; } /** * mono_metadata_nesting_typedef: * \param meta metadata context * \param index typedef token * \returns the 1-based index into the \c TypeDef table of the first type * that is nested inside the type described by \p index. The search starts at * \p start_index. Returns 0 if no such type is found. */ guint32 mono_metadata_nesting_typedef (MonoImage *meta, guint32 index, guint32 start_index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS]; guint32 start; guint32 class_index = mono_metadata_token_index (index); if (!tdef->base) return 0; start = start_index; /* FIXME: metadata-udpate */ int rows = table_info_get_rows (tdef); while (start <= rows) { if (class_index == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING)) break; else start++; } if (start > rows) return 0; else return start; } /** * mono_metadata_packing_from_typedef: * \param meta metadata context * \param index token representing a type * \returns the info stored in the \c ClassLayout table for the given typedef token * into the \p packing and \p size pointers. * Returns 0 if the info is not found. */ guint32 mono_metadata_packing_from_typedef (MonoImage *meta, guint32 index, guint32 *packing, guint32 *size) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CLASSLAYOUT]; locator_t loc; guint32 cols [MONO_CLASS_LAYOUT_SIZE]; if (!tdef->base) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_CLASS_LAYOUT_PARENT; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; mono_metadata_decode_row (tdef, loc.result, cols, MONO_CLASS_LAYOUT_SIZE); if (packing) *packing = cols [MONO_CLASS_LAYOUT_PACKING_SIZE]; if (size) *size = cols [MONO_CLASS_LAYOUT_CLASS_SIZE]; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_custom_attrs_from_index: * \param meta metadata context * \param index token representing the parent * \returns: the 1-based index into the \c CustomAttribute table of the first * attribute which belongs to the metadata object described by \p index. * Returns 0 if no such attribute is found. */ guint32 mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE]; locator_t loc; if (!tdef->base && !meta->has_updates) return 0; loc.idx = index; loc.col_idx = MONO_CUSTOM_ATTR_PARENT; loc.t = tdef; /* FIXME: Index translation */ gboolean found = tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator) != NULL; if (!found && !meta->has_updates) return 0; if (G_UNLIKELY (meta->has_updates)) { if (!found && !mono_metadata_update_metadata_linear_search (meta, tdef, &loc, table_locator)) return 0; } /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index)) loc.result --; /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return loc.result + 1; } /** * mono_metadata_declsec_from_index: * \param meta metadata context * \param index token representing the parent * \returns the 0-based index into the \c DeclarativeSecurity table of the first * attribute which belongs to the metadata object described by \p index. * Returns \c -1 if no such attribute is found. */ guint32 mono_metadata_declsec_from_index (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_DECLSECURITY]; locator_t loc; if (!tdef->base) return -1; loc.idx = index; loc.col_idx = MONO_DECL_SECURITY_PARENT; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, declsec_locator)) return -1; /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_DECL_SECURITY_PARENT) == index)) loc.result --; return loc.result; } /* * mono_metadata_localscope_from_methoddef: * @meta: metadata context * @index: methoddef index * * Returns: the 1-based index into the LocalScope table of the first * scope which belongs to the method described by @index. * Returns 0 if no such row is found. */ guint32 mono_metadata_localscope_from_methoddef (MonoImage *meta, guint32 index) { MonoTableInfo *tdef = &meta->tables [MONO_TABLE_LOCALSCOPE]; locator_t loc; if (!tdef->base) return 0; loc.idx = index; loc.col_idx = MONO_LOCALSCOPE_METHOD; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_LOCALSCOPE_METHOD) == index)) loc.result --; return loc.result + 1; } #ifdef DEBUG static void mono_backtrace (int limit) { void *array[limit]; char **names; int i; backtrace (array, limit); names = backtrace_symbols (array, limit); for (i =0; i < limit; ++i) { g_print ("\t%s\n", names [i]); } g_free (names); } #endif static int i8_align; /* * mono_type_set_alignment: * * Set the alignment used by runtime to layout fields etc. of type TYPE to ALIGN. * This should only be used in AOT mode since the resulting layout will not match the * host abi layout. */ void mono_type_set_alignment (MonoTypeEnum type, int align) { /* Support only a few types whose alignment is abi dependent */ switch (type) { case MONO_TYPE_I8: i8_align = align; break; default: g_assert_not_reached (); break; } } /** * mono_type_size: * \param t the type to return the size of * \returns The number of bytes required to hold an instance of this * type in memory */ int mono_type_size (MonoType *t, int *align) { MonoTypeEnum simple_type; if (!t) { *align = 1; return 0; } if (m_type_is_byref (t)) { *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); } simple_type = t->type; again: switch (simple_type) { case MONO_TYPE_VOID: *align = 1; return 0; case MONO_TYPE_BOOLEAN: *align = MONO_ABI_ALIGNOF (gint8); return 1; case MONO_TYPE_I1: case MONO_TYPE_U1: *align = MONO_ABI_ALIGNOF (gint8); return 1; case MONO_TYPE_CHAR: case MONO_TYPE_I2: case MONO_TYPE_U2: *align = MONO_ABI_ALIGNOF (gint16); return 2; case MONO_TYPE_I4: case MONO_TYPE_U4: *align = MONO_ABI_ALIGNOF (gint32); return 4; case MONO_TYPE_R4: *align = MONO_ABI_ALIGNOF (float); return 4; case MONO_TYPE_I8: case MONO_TYPE_U8: *align = MONO_ABI_ALIGNOF (gint64); return 8; case MONO_TYPE_R8: *align = MONO_ABI_ALIGNOF (double); return 8; case MONO_TYPE_I: case MONO_TYPE_U: *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); case MONO_TYPE_VALUETYPE: { if (m_class_is_enumtype (t->data.klass)) return mono_type_size (mono_class_enum_basetype_internal (t->data.klass), align); else return mono_class_value_size (t->data.klass, (guint32*)align); } case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_ARRAY: *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); case MONO_TYPE_TYPEDBYREF: return mono_class_value_size (mono_defaults.typed_reference_class, (guint32*)align); case MONO_TYPE_GENERICINST: { MonoGenericClass *gclass = t->data.generic_class; MonoClass *container_class = gclass->container_class; // g_assert (!gclass->inst->is_open); if (m_class_is_valuetype (container_class)) { if (m_class_is_enumtype (container_class)) return mono_type_size (mono_class_enum_basetype_internal (container_class), align); else return mono_class_value_size (mono_class_from_mono_type_internal (t), (guint32*)align); } else { *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); } } case MONO_TYPE_VAR: case MONO_TYPE_MVAR: if (!t->data.generic_param->gshared_constraint || t->data.generic_param->gshared_constraint->type == MONO_TYPE_VALUETYPE) { *align = MONO_ABI_ALIGNOF (gpointer); return MONO_ABI_SIZEOF (gpointer); } else { /* The gparam can only match types given by gshared_constraint */ return mono_type_size (t->data.generic_param->gshared_constraint, align); goto again; } default: g_error ("mono_type_size: type 0x%02x unknown", t->type); } return 0; } /** * mono_type_stack_size: * \param t the type to return the size it uses on the stack * \returns The number of bytes required to hold an instance of this * type on the runtime stack */ int mono_type_stack_size (MonoType *t, int *align) { return mono_type_stack_size_internal (t, align, FALSE); } int mono_type_stack_size_internal (MonoType *t, int *align, gboolean allow_open) { int tmp; MonoTypeEnum simple_type; int stack_slot_size = TARGET_SIZEOF_VOID_P; int stack_slot_align = TARGET_SIZEOF_VOID_P; g_assert (t != NULL); if (!align) align = &tmp; if (m_type_is_byref (t)) { *align = stack_slot_align; return stack_slot_size; } simple_type = t->type; switch (simple_type) { case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_STRING: case MONO_TYPE_OBJECT: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_ARRAY: *align = stack_slot_align; return stack_slot_size; case MONO_TYPE_VAR: case MONO_TYPE_MVAR: g_assert (allow_open); if (!t->data.generic_param->gshared_constraint || t->data.generic_param->gshared_constraint->type == MONO_TYPE_VALUETYPE) { *align = stack_slot_align; return stack_slot_size; } else { /* The gparam can only match types given by gshared_constraint */ return mono_type_stack_size_internal (t->data.generic_param->gshared_constraint, align, allow_open); } case MONO_TYPE_TYPEDBYREF: *align = stack_slot_align; return stack_slot_size * 3; case MONO_TYPE_R4: *align = MONO_ABI_ALIGNOF (float); return sizeof (float); case MONO_TYPE_I8: case MONO_TYPE_U8: *align = MONO_ABI_ALIGNOF (gint64); return sizeof (gint64); case MONO_TYPE_R8: *align = MONO_ABI_ALIGNOF (double); return sizeof (double); case MONO_TYPE_VALUETYPE: { guint32 size; if (m_class_is_enumtype (t->data.klass)) return mono_type_stack_size_internal (mono_class_enum_basetype_internal (t->data.klass), align, allow_open); else { size = mono_class_value_size (t->data.klass, (guint32*)align); *align = *align + stack_slot_align - 1; *align &= ~(stack_slot_align - 1); size += stack_slot_size - 1; size &= ~(stack_slot_size - 1); return size; } } case MONO_TYPE_GENERICINST: { MonoGenericClass *gclass = t->data.generic_class; MonoClass *container_class = gclass->container_class; if (!allow_open) g_assert (!gclass->context.class_inst->is_open); if (m_class_is_valuetype (container_class)) { if (m_class_is_enumtype (container_class)) return mono_type_stack_size_internal (mono_class_enum_basetype_internal (container_class), align, allow_open); else { guint32 size = mono_class_value_size (mono_class_from_mono_type_internal (t), (guint32*)align); *align = *align + stack_slot_align - 1; *align &= ~(stack_slot_align - 1); size += stack_slot_size - 1; size &= ~(stack_slot_size - 1); return size; } } else { *align = stack_slot_align; return stack_slot_size; } } default: g_error ("type 0x%02x unknown", t->type); } return 0; } gboolean mono_type_generic_inst_is_valuetype (MonoType *type) { g_assert (type->type == MONO_TYPE_GENERICINST); return m_class_is_valuetype (type->data.generic_class->container_class); } /** * mono_metadata_generic_class_is_valuetype: */ gboolean mono_metadata_generic_class_is_valuetype (MonoGenericClass *gclass) { return m_class_is_valuetype (gclass->container_class); } static gboolean _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only) { MonoGenericInst *i1 = g1->context.class_inst; MonoGenericInst *i2 = g2->context.class_inst; if (g1->is_dynamic != g2->is_dynamic) return FALSE; if (!mono_metadata_class_equal (g1->container_class, g2->container_class, signature_only)) return FALSE; if (!mono_generic_inst_equal_full (i1, i2, signature_only)) return FALSE; return g1->is_tb_open == g2->is_tb_open; } static gboolean _mono_metadata_generic_class_container_equal (const MonoGenericClass *g1, MonoClass *c2, gboolean signature_only) { MonoGenericInst *i1 = g1->context.class_inst; MonoGenericInst *i2 = mono_class_get_generic_container (c2)->context.class_inst; if (!mono_metadata_class_equal (g1->container_class, c2, signature_only)) return FALSE; if (!mono_generic_inst_equal_full (i1, i2, signature_only)) return FALSE; return !g1->is_tb_open; } guint mono_metadata_generic_context_hash (const MonoGenericContext *context) { /* FIXME: check if this seed is good enough */ guint hash = 0xc01dfee7; if (context->class_inst) hash = ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (context->class_inst); if (context->method_inst) hash = ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (context->method_inst); return hash; } gboolean mono_metadata_generic_context_equal (const MonoGenericContext *g1, const MonoGenericContext *g2) { return g1->class_inst == g2->class_inst && g1->method_inst == g2->method_inst; } /* * mono_metadata_str_hash: * * This should be used instead of g_str_hash for computing hash codes visible * outside this module, since g_str_hash () is not guaranteed to be stable * (its not the same in eglib for example). */ guint mono_metadata_str_hash (gconstpointer v1) { /* Same as g_str_hash () in glib */ char *p = (char *) v1; guint hash = *p; while (*p++) { if (*p) hash = (hash << 5) - hash + *p; } return hash; } /** * mono_metadata_type_hash: * \param t1 a type * Computes a hash value for \p t1 to be used in \c GHashTable. * The returned hash is guaranteed to be the same across executions. */ guint mono_metadata_type_hash (MonoType *t1) { guint hash = t1->type; hash |= (m_type_is_byref (t1) ? 1 : 0) << 6; /* do not collide with t1->type values */ switch (t1->type) { case MONO_TYPE_VALUETYPE: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: { MonoClass *klass = t1->data.klass; /* * Dynamic classes must not be hashed on their type since it can change * during runtime. For example, if we hash a reference type that is * later made into a valuetype. * * This is specially problematic with generic instances since they are * inserted in a bunch of hash tables before been finished. */ if (image_is_dynamic (m_class_get_image (klass))) return ((m_type_is_byref (t1) ? 1 : 0) << 6) | mono_metadata_str_hash (m_class_get_name (klass)); return ((hash << 5) - hash) ^ mono_metadata_str_hash (m_class_get_name (klass)); } case MONO_TYPE_PTR: return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type); case MONO_TYPE_ARRAY: return ((hash << 5) - hash) ^ mono_metadata_type_hash (m_class_get_byval_arg (t1->data.array->eklass)); case MONO_TYPE_GENERICINST: return ((hash << 5) - hash) ^ mono_generic_class_hash (t1->data.generic_class); case MONO_TYPE_VAR: case MONO_TYPE_MVAR: return ((hash << 5) - hash) ^ mono_metadata_generic_param_hash (t1->data.generic_param); default: return hash; } } guint mono_metadata_generic_param_hash (MonoGenericParam *p) { guint hash; MonoGenericParamInfo *info; hash = (mono_generic_param_num (p) << 2); if (p->gshared_constraint) hash = ((hash << 5) - hash) ^ mono_metadata_type_hash (p->gshared_constraint); info = mono_generic_param_info (p); /* Can't hash on the owner klass/method, since those might not be set when this is called */ if (!p->owner->is_anonymous) hash = ((hash << 5) - hash) ^ info->token; return hash; } static gboolean mono_metadata_generic_param_equal_internal (MonoGenericParam *p1, MonoGenericParam *p2, gboolean signature_only) { if (p1 == p2) return TRUE; if (mono_generic_param_num (p1) != mono_generic_param_num (p2)) return FALSE; if (p1->gshared_constraint && p2->gshared_constraint) { if (!mono_metadata_type_equal (p1->gshared_constraint, p2->gshared_constraint)) return FALSE; } else { if (p1->gshared_constraint != p2->gshared_constraint) return FALSE; } /* * We have to compare the image as well because if we didn't, * the generic_inst_cache lookup wouldn't care about the image * of generic params, so what could happen is that a generic * inst with params from image A is put into the cache, then * image B gets that generic inst from the cache, image A is * unloaded, so the inst is deleted, but image B still retains * a pointer to it. */ if (mono_generic_param_owner (p1) == mono_generic_param_owner (p2)) return TRUE; /* * If `signature_only' is true, we're comparing two (method) signatures. * In this case, the owner of two type parameters doesn't need to match. */ return signature_only; } gboolean mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2) { return mono_metadata_generic_param_equal_internal (p1, p2, TRUE); } static gboolean mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only) { if (c1 == c2) return TRUE; if (mono_class_is_ginst (c1) && mono_class_is_ginst (c2)) return _mono_metadata_generic_class_equal (mono_class_get_generic_class (c1), mono_class_get_generic_class (c2), signature_only); if (mono_class_is_ginst (c1) && mono_class_is_gtd (c2)) return _mono_metadata_generic_class_container_equal (mono_class_get_generic_class (c1), c2, signature_only); if (mono_class_is_gtd (c1) && mono_class_is_ginst (c2)) return _mono_metadata_generic_class_container_equal (mono_class_get_generic_class (c2), c1, signature_only); MonoType *c1_type = m_class_get_byval_arg (c1); MonoType *c2_type = m_class_get_byval_arg (c2); if ((c1_type->type == MONO_TYPE_VAR) && (c2_type->type == MONO_TYPE_VAR)) return mono_metadata_generic_param_equal_internal ( c1_type->data.generic_param, c2_type->data.generic_param, signature_only); if ((c1_type->type == MONO_TYPE_MVAR) && (c2_type->type == MONO_TYPE_MVAR)) return mono_metadata_generic_param_equal_internal ( c1_type->data.generic_param, c2_type->data.generic_param, signature_only); if (signature_only && (c1_type->type == MONO_TYPE_SZARRAY) && (c2_type->type == MONO_TYPE_SZARRAY)) return mono_metadata_class_equal (c1_type->data.klass, c2_type->data.klass, signature_only); if (signature_only && (c1_type->type == MONO_TYPE_ARRAY) && (c2_type->type == MONO_TYPE_ARRAY)) return do_mono_metadata_type_equal (c1_type, c2_type, signature_only); return FALSE; } static gboolean mono_metadata_fnptr_equal (MonoMethodSignature *s1, MonoMethodSignature *s2, gboolean signature_only) { gpointer iter1 = 0, iter2 = 0; if (s1 == s2) return TRUE; if (s1->call_convention != s2->call_convention) return FALSE; if (s1->sentinelpos != s2->sentinelpos) return FALSE; if (s1->hasthis != s2->hasthis) return FALSE; if (s1->explicit_this != s2->explicit_this) return FALSE; if (! do_mono_metadata_type_equal (s1->ret, s2->ret, signature_only)) return FALSE; if (s1->param_count != s2->param_count) return FALSE; while (TRUE) { MonoType *t1 = mono_signature_get_params_internal (s1, &iter1); MonoType *t2 = mono_signature_get_params_internal (s2, &iter2); if (t1 == NULL || t2 == NULL) return (t1 == t2); if (! do_mono_metadata_type_equal (t1, t2, signature_only)) return FALSE; } } static gboolean mono_metadata_custom_modifiers_equal (MonoType *t1, MonoType *t2, gboolean signature_only) { // ECMA 335, 7.1.1: // The CLI itself shall treat required and optional modifiers in the same manner. // Two signatures that differ only by the addition of a custom modifier // (required or optional) shall not be considered to match. int count = mono_type_custom_modifier_count (t1); if (count != mono_type_custom_modifier_count (t2)) return FALSE; for (int i=0; i < count; i++) { // FIXME: propagate error to caller ERROR_DECL (error); gboolean cm1_required, cm2_required; MonoType *cm1_type = mono_type_get_custom_modifier (t1, i, &cm1_required, error); mono_error_assert_ok (error); MonoType *cm2_type = mono_type_get_custom_modifier (t2, i, &cm2_required, error); mono_error_assert_ok (error); if (cm1_required != cm2_required) return FALSE; if (!do_mono_metadata_type_equal (cm1_type, cm2_type, signature_only)) return FALSE; } return TRUE; } /* * mono_metadata_type_equal: * @t1: a type * @t2: another type * @signature_only: If true, treat ginsts as equal which are instantiated separately but have equal positional value * * Determine if @t1 and @t2 represent the same type. * Returns: #TRUE if @t1 and @t2 are equal. */ static gboolean do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only) { if (t1->type != t2->type || m_type_is_byref (t1) != m_type_is_byref (t2)) return FALSE; gboolean cmod_reject = FALSE; if (t1->has_cmods != t2->has_cmods) cmod_reject = TRUE; else if (t1->has_cmods && t2->has_cmods) { cmod_reject = !mono_metadata_custom_modifiers_equal (t1, t2, signature_only); } gboolean result = FALSE; switch (t1->type) { case MONO_TYPE_VOID: case MONO_TYPE_BOOLEAN: case MONO_TYPE_CHAR: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I8: case MONO_TYPE_U8: case MONO_TYPE_R4: case MONO_TYPE_R8: case MONO_TYPE_STRING: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_OBJECT: case MONO_TYPE_TYPEDBYREF: result = TRUE; break; case MONO_TYPE_VALUETYPE: case MONO_TYPE_CLASS: case MONO_TYPE_SZARRAY: result = mono_metadata_class_equal (t1->data.klass, t2->data.klass, signature_only); break; case MONO_TYPE_PTR: result = do_mono_metadata_type_equal (t1->data.type, t2->data.type, signature_only); break; case MONO_TYPE_ARRAY: if (t1->data.array->rank != t2->data.array->rank) result = FALSE; else result = mono_metadata_class_equal (t1->data.array->eklass, t2->data.array->eklass, signature_only); break; case MONO_TYPE_GENERICINST: result = _mono_metadata_generic_class_equal ( t1->data.generic_class, t2->data.generic_class, signature_only); break; case MONO_TYPE_VAR: result = mono_metadata_generic_param_equal_internal ( t1->data.generic_param, t2->data.generic_param, signature_only); break; case MONO_TYPE_MVAR: result = mono_metadata_generic_param_equal_internal ( t1->data.generic_param, t2->data.generic_param, signature_only); break; case MONO_TYPE_FNPTR: result = mono_metadata_fnptr_equal (t1->data.method, t2->data.method, signature_only); break; default: g_error ("implement type compare for %0x!", t1->type); return FALSE; } return result && !cmod_reject; } /** * mono_metadata_type_equal: */ gboolean mono_metadata_type_equal (MonoType *t1, MonoType *t2) { return do_mono_metadata_type_equal (t1, t2, FALSE); } /** * mono_metadata_type_equal_full: * \param t1 a type * \param t2 another type * \param signature_only if signature only comparison should be made * * Determine if \p t1 and \p t2 are signature compatible if \p signature_only is TRUE, otherwise * behaves the same way as mono_metadata_type_equal. * The function mono_metadata_type_equal(a, b) is just a shortcut for mono_metadata_type_equal_full(a, b, FALSE). * \returns TRUE if \p t1 and \p t2 are equal taking \p signature_only into account. */ gboolean mono_metadata_type_equal_full (MonoType *t1, MonoType *t2, gboolean signature_only) { return do_mono_metadata_type_equal (t1, t2, signature_only); } enum { SIG_EQUIV_FLAG_NO_RET = 1, }; gboolean signature_equiv (MonoMethodSignature *sig1, MonoMethodSignature *sig2, int flags); /** * mono_metadata_signature_equal: * \param sig1 a signature * \param sig2 another signature * * Determine if \p sig1 and \p sig2 represent the same signature, with the * same number of arguments and the same types. * \returns TRUE if \p sig1 and \p sig2 are equal. */ gboolean mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2) { return signature_equiv (sig1, sig2, 0); } gboolean mono_metadata_signature_equal_no_ret (MonoMethodSignature *sig1, MonoMethodSignature *sig2) { return signature_equiv (sig1, sig2, SIG_EQUIV_FLAG_NO_RET); } gboolean signature_equiv (MonoMethodSignature *sig1, MonoMethodSignature *sig2, int equiv_flags) { int i; if (sig1->hasthis != sig2->hasthis || sig1->param_count != sig2->param_count) return FALSE; if (sig1->generic_param_count != sig2->generic_param_count) return FALSE; /* * We're just comparing the signatures of two methods here: * * If we have two generic methods `void Foo<U> (U u)' and `void Bar<V> (V v)', * U and V are equal here. * * That's what the `signature_only' argument of do_mono_metadata_type_equal() is for. */ for (i = 0; i < sig1->param_count; i++) { MonoType *p1 = sig1->params[i]; MonoType *p2 = sig2->params[i]; /* if (p1->attrs != p2->attrs) return FALSE; */ if (!do_mono_metadata_type_equal (p1, p2, TRUE)) return FALSE; } if ((equiv_flags & SIG_EQUIV_FLAG_NO_RET) != 0) return TRUE; if (!do_mono_metadata_type_equal (sig1->ret, sig2->ret, TRUE)) return FALSE; return TRUE; } MonoType * mono_type_get_custom_modifier (const MonoType *ty, uint8_t idx, gboolean *required, MonoError *error) { g_assert (ty->has_cmods); if (mono_type_is_aggregate_mods (ty)) { MonoAggregateModContainer *amods = mono_type_get_amods (ty); g_assert (idx < amods->count); MonoSingleCustomMod *cmod = &amods->modifiers [idx]; if (required) *required = !!cmod->required; return cmod->type; } else { MonoCustomModContainer *cmods = mono_type_get_cmods (ty); g_assert (idx < cmods->count); MonoCustomMod *cmod = &cmods->modifiers [idx]; if (required) *required = !!cmod->required; MonoImage *image = cmods->image; uint32_t token = cmod->token; return mono_type_get_checked (image, token, NULL, error); } } /** * mono_metadata_type_dup: * \param image image to alloc memory from * \param original type to duplicate * \returns copy of type allocated from the image's mempool (or from the heap, if \p image is null). */ MonoType * mono_metadata_type_dup (MonoImage *image, const MonoType *o) { return mono_metadata_type_dup_with_cmods (image, o, o); } static void deep_type_dup_fixup (MonoImage *image, MonoType *r, const MonoType *o); static uint8_t custom_modifier_copy (MonoAggregateModContainer *dest, uint8_t dest_offset, const MonoType *source) { if (mono_type_is_aggregate_mods (source)) { MonoAggregateModContainer *src_cmods = mono_type_get_amods (source); memcpy (&dest->modifiers [dest_offset], &src_cmods->modifiers[0], src_cmods->count * sizeof (MonoSingleCustomMod)); dest_offset += src_cmods->count; } else { MonoCustomModContainer *src_cmods = mono_type_get_cmods (source); for (int i = 0; i < src_cmods->count; i++) { ERROR_DECL (error); // XXX FIXME: AK - propagate the error to the caller. MonoSingleCustomMod *cmod = &dest->modifiers [dest_offset++]; cmod->type = mono_type_get_checked (src_cmods->image, src_cmods->modifiers [i].token, NULL, error); mono_error_assert_ok (error); cmod->required = src_cmods->modifiers [i].required; } } return dest_offset; } /* makes a dup of 'o' but also appends the custom modifiers from 'cmods_source' */ static MonoType * do_metadata_type_dup_append_cmods (MonoImage *image, const MonoType *o, const MonoType *cmods_source) { g_assert (o != cmods_source); g_assert (o->has_cmods); g_assert (cmods_source->has_cmods); if (!mono_type_is_aggregate_mods (o) && !mono_type_is_aggregate_mods (cmods_source) && mono_type_get_cmods (o)->image == mono_type_get_cmods (cmods_source)->image) { /* the uniform case: all the cmods are from the same image. */ MonoCustomModContainer *o_cmods = mono_type_get_cmods (o); MonoCustomModContainer *extra_cmods = mono_type_get_cmods (cmods_source); uint8_t total_cmods = o_cmods->count + extra_cmods->count; gboolean aggregate = FALSE; size_t sizeof_dup = mono_sizeof_type_with_mods (total_cmods, aggregate); MonoType *r = image ? (MonoType *)mono_image_alloc0 (image, sizeof_dup) : (MonoType *)g_malloc0 (sizeof_dup); mono_type_with_mods_init (r, total_cmods, aggregate); /* copy the original type o, not including its modifiers */ memcpy (r, o, mono_sizeof_type_with_mods (0, FALSE)); deep_type_dup_fixup (image, r, o); /* The modifier order matters to Roslyn, they expect the extra cmods to come first: * * Suppose we substitute 'int32 modopt(IsLong)' for 'T' in 'void Test * (T modopt(IsConst))'. Roslyn expects the result to be 'void Test * (int32 modopt(IsLong) modopt(IsConst))'. * * but! cmods are encoded in IL in reverse order, so 'int32 modopt(IsConst) modopt(IsLong)' is * encoded as `cmod_opt [typeref IsLong] cmod_opt [typeref IsConst] I4` * so in our array, extra_cmods (IsLong) come first, followed by o_cmods (IsConst) * * (Here 'o' is 'int32 modopt(IsLong)' and cmods_source is 'T modopt(IsConst)') */ /* append the modifiers from cmods_source and o */ MonoCustomModContainer *r_container = mono_type_get_cmods (r); uint8_t dest_offset = 0; r_container->image = extra_cmods->image; memcpy (&r_container->modifiers [dest_offset], &o_cmods->modifiers [0], o_cmods->count * sizeof (MonoCustomMod)); dest_offset += o_cmods->count; memcpy (&r_container->modifiers [dest_offset], &extra_cmods->modifiers [0], extra_cmods->count * sizeof (MonoCustomMod)); dest_offset += extra_cmods->count; g_assert (dest_offset == total_cmods); return r; } else { /* The aggregate case: either o_cmods or extra_cmods has aggregate cmods, or they're both simple but from different images. */ uint8_t total_cmods = 0; total_cmods += mono_type_custom_modifier_count (o); total_cmods += mono_type_custom_modifier_count (cmods_source); gboolean aggregate = TRUE; size_t sizeof_dup = mono_sizeof_type_with_mods (total_cmods, aggregate); /* FIXME: if image, and the images of the custom modifiers from * o and cmods_source are all different, we need an image * set... */ MonoType *r = image ? (MonoType *)mono_image_alloc0 (image, sizeof_dup) : (MonoType*)g_malloc0 (sizeof_dup); mono_type_with_mods_init (r, total_cmods, aggregate); memcpy (r, o, mono_sizeof_type_with_mods (0, FALSE)); deep_type_dup_fixup (image, r, o); /* Try not to blow up the stack. See comment on * MONO_MAX_EXPECTED_CMODS. Since here we're appending all the * mods together, it's possible we'll end up with more than the * maximum allowed. If that ever happens in practice, we * should redefine the bound and possibly make this function * fail dynamically instead of asserting. */ g_assert (total_cmods < MONO_MAX_EXPECTED_CMODS); size_t r_container_size = mono_sizeof_aggregate_modifiers (total_cmods); MonoAggregateModContainer *r_container_candidate = g_alloca (r_container_size); memset (r_container_candidate, 0, r_container_size); uint8_t dest_offset = 0; dest_offset = custom_modifier_copy (r_container_candidate, dest_offset, o); dest_offset = custom_modifier_copy (r_container_candidate, dest_offset, cmods_source); g_assert (dest_offset == total_cmods); r_container_candidate->count = total_cmods; mono_type_set_amods (r, mono_metadata_get_canonical_aggregate_modifiers (r_container_candidate)); return r; } } /** * Works the same way as mono_metadata_type_dup but pick cmods from @cmods_source */ MonoType * mono_metadata_type_dup_with_cmods (MonoImage *image, const MonoType *o, const MonoType *cmods_source) { if (o->has_cmods && o != cmods_source && cmods_source->has_cmods) { return do_metadata_type_dup_append_cmods (image, o, cmods_source); } MonoType *r = NULL; /* if we get here, either o and cmods_source alias, or else exactly one of them has cmods. */ uint8_t num_mods = MAX (mono_type_custom_modifier_count (o), mono_type_custom_modifier_count (cmods_source)); gboolean aggregate = mono_type_is_aggregate_mods (o) || mono_type_is_aggregate_mods (cmods_source); size_t sizeof_r = mono_sizeof_type_with_mods (num_mods, aggregate); r = image ? (MonoType *)mono_image_alloc0 (image, sizeof_r) : (MonoType *)g_malloc0 (sizeof_r); if (cmods_source->has_cmods) { /* FIXME: if it's aggregate what do we assert here? */ g_assert (!image || (!aggregate && image == mono_type_get_cmods (cmods_source)->image)); memcpy (r, cmods_source, mono_sizeof_type (cmods_source)); } memcpy (r, o, mono_sizeof_type (o)); /* reset custom mod count and aggregateness to be correct. */ mono_type_with_mods_init (r, num_mods, aggregate); if (aggregate) mono_type_set_amods (r, mono_type_is_aggregate_mods (o) ? mono_type_get_amods (o) : mono_type_get_amods (cmods_source)); deep_type_dup_fixup (image, r, o); return r; } static void deep_type_dup_fixup (MonoImage *image, MonoType *r, const MonoType *o) { if (o->type == MONO_TYPE_PTR) { r->data.type = mono_metadata_type_dup (image, o->data.type); } else if (o->type == MONO_TYPE_ARRAY) { r->data.array = mono_dup_array_type (image, o->data.array); } else if (o->type == MONO_TYPE_FNPTR) { /*FIXME the dup'ed signature is leaked mono_metadata_free_type*/ r->data.method = mono_metadata_signature_deep_dup (image, o->data.method); } } /** * mono_signature_hash: */ guint mono_signature_hash (MonoMethodSignature *sig) { guint i, res = sig->ret->type; for (i = 0; i < sig->param_count; i++) res = (res << 5) - res + mono_type_hash (sig->params[i]); return res; } /* * mono_metadata_encode_value: * @value: value to encode * @buf: buffer where to write the compressed representation * @endbuf: pointer updated to point at the end of the encoded output * * Encodes the value @value in the compressed representation used * in metadata and stores the result in @buf. @buf needs to be big * enough to hold the data (4 bytes). */ void mono_metadata_encode_value (guint32 value, char *buf, char **endbuf) { char *p = buf; if (value < 0x80) *p++ = value; else if (value < 0x4000) { p [0] = 0x80 | (value >> 8); p [1] = value & 0xff; p += 2; } else { p [0] = (value >> 24) | 0xc0; p [1] = (value >> 16) & 0xff; p [2] = (value >> 8) & 0xff; p [3] = value & 0xff; p += 4; } if (endbuf) *endbuf = p; } /** * mono_metadata_field_info: * \param meta the Image the field is defined in * \param index the index in the field table representing the field * \param offset a pointer to an integer where to store the offset that may have been specified for the field in a FieldLayout table * \param rva a pointer to the RVA of the field data in the image that may have been defined in a \c FieldRVA table * \param marshal_spec a pointer to the marshal spec that may have been defined for the field in a \c FieldMarshal table. * * Gather info for field \p index that may have been defined in the \c FieldLayout, * \c FieldRVA and \c FieldMarshal tables. * Either of \p offset, \p rva and \p marshal_spec can be NULL if you're not interested * in the data. */ void mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec) { mono_metadata_field_info_full (meta, index, offset, rva, marshal_spec, FALSE); } void mono_metadata_field_info_with_mempool (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec) { mono_metadata_field_info_full (meta, index, offset, rva, marshal_spec, TRUE); } static void mono_metadata_field_info_full (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec, gboolean alloc_from_image) { MonoTableInfo *tdef; locator_t loc; loc.idx = index + 1; if (meta->uncompressed_metadata) loc.idx = search_ptr_table (meta, MONO_TABLE_FIELD_POINTER, loc.idx); if (offset) { tdef = &meta->tables [MONO_TABLE_FIELDLAYOUT]; loc.col_idx = MONO_FIELD_LAYOUT_FIELD; loc.t = tdef; /* FIXME: metadata-update */ if (tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) { *offset = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_LAYOUT_OFFSET); } else { *offset = (guint32)-1; } } if (rva) { tdef = &meta->tables [MONO_TABLE_FIELDRVA]; loc.col_idx = MONO_FIELD_RVA_FIELD; loc.t = tdef; if (tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) { /* * LAMESPEC: There is no signature, no nothing, just the raw data. */ *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA); } else { *rva = 0; } } if (marshal_spec) { const char *p; if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) { *marshal_spec = mono_metadata_parse_marshal_spec_full (alloc_from_image ? meta : NULL, meta, p); } } } /** * mono_metadata_get_constant_index: * \param meta the Image the field is defined in * \param index the token that may have a row defined in the constants table * \param hint possible position for the row * * \p token must be a \c FieldDef, \c ParamDef or \c PropertyDef token. * * \returns the index into the \c Constants table or 0 if not found. */ guint32 mono_metadata_get_constant_index (MonoImage *meta, guint32 token, guint32 hint) { MonoTableInfo *tdef; locator_t loc; guint32 index = mono_metadata_token_index (token); tdef = &meta->tables [MONO_TABLE_CONSTANT]; index <<= MONO_HASCONSTANT_BITS; switch (mono_metadata_token_table (token)) { case MONO_TABLE_FIELD: index |= MONO_HASCONSTANT_FIEDDEF; break; case MONO_TABLE_PARAM: index |= MONO_HASCONSTANT_PARAM; break; case MONO_TABLE_PROPERTY: index |= MONO_HASCONSTANT_PROPERTY; break; default: g_warning ("Not a valid token for the constant table: 0x%08x", token); return 0; } loc.idx = index; loc.col_idx = MONO_CONSTANT_PARENT; loc.t = tdef; /* FIXME: metadata-update */ /* FIXME: Index translation */ if ((hint > 0) && (hint < table_info_get_rows (tdef)) && (mono_metadata_decode_row_col (tdef, hint - 1, MONO_CONSTANT_PARENT) == index)) return hint; if (tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) { return loc.result + 1; } return 0; } /** * mono_metadata_events_from_typedef: * \param meta metadata context * \param index 0-based index (in the \c TypeDef table) describing a type * \returns the 0-based index in the \c Event table for the events in the * type. The last event that belongs to the type (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint32 start, end; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_EVENTMAP]; *end_idx = 0; if (!tdef->base) return 0; loc.t = tdef; loc.col_idx = MONO_EVENT_MAP_PARENT; loc.idx = index + 1; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; start = mono_metadata_decode_row_col (tdef, loc.result, MONO_EVENT_MAP_EVENTLIST); if (loc.result + 1 < table_info_get_rows (tdef)) { end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_EVENT_MAP_EVENTLIST) - 1; } else { end = table_info_get_rows (&meta->tables [MONO_TABLE_EVENT]); } *end_idx = end; return start - 1; } /** * mono_metadata_methods_from_event: * \param meta metadata context * \param index 0-based index (in the \c Event table) describing a event * \returns the 0-based index in the \c MethodDef table for the methods in the * event. The last method that belongs to the event (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_methods_from_event (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint start, end; guint32 cols [MONO_METHOD_SEMA_SIZE]; MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS]; *end_idx = 0; if (!msemt->base) return 0; if (meta->uncompressed_metadata) index = search_ptr_table (meta, MONO_TABLE_EVENT_POINTER, index + 1) - 1; loc.t = msemt; loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION; loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT; /* Method association coded index */ /* FIXME: metadata-update */ if (!mono_binary_search (&loc, msemt->base, table_info_get_rows (msemt), msemt->row_size, table_locator)) return 0; start = loc.result; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION)) start--; else break; } end = start + 1; int rows = table_info_get_rows (msemt); while (end < rows) { mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE); if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx) break; ++end; } *end_idx = end; return start; } /** * mono_metadata_properties_from_typedef: * \param meta metadata context * \param index 0-based index (in the \c TypeDef table) describing a type * \returns the 0-based index in the \c Property table for the properties in the * type. The last property that belongs to the type (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint32 start, end; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_PROPERTYMAP]; *end_idx = 0; if (!tdef->base) return 0; loc.t = tdef; loc.col_idx = MONO_PROPERTY_MAP_PARENT; loc.idx = index + 1; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; start = mono_metadata_decode_row_col (tdef, loc.result, MONO_PROPERTY_MAP_PROPERTY_LIST); if (loc.result + 1 < table_info_get_rows (tdef)) { end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_PROPERTY_MAP_PROPERTY_LIST) - 1; } else { end = table_info_get_rows (&meta->tables [MONO_TABLE_PROPERTY]); } *end_idx = end; return start - 1; } /** * mono_metadata_methods_from_property: * \param meta metadata context * \param index 0-based index (in the \c PropertyDef table) describing a property * \returns the 0-based index in the \c MethodDef table for the methods in the * property. The last method that belongs to the property (plus 1) is stored * in the \p end_idx pointer. */ guint32 mono_metadata_methods_from_property (MonoImage *meta, guint32 index, guint *end_idx) { locator_t loc; guint start, end; guint32 cols [MONO_METHOD_SEMA_SIZE]; MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS]; *end_idx = 0; if (!msemt->base) return 0; if (meta->uncompressed_metadata) index = search_ptr_table (meta, MONO_TABLE_PROPERTY_POINTER, index + 1) - 1; loc.t = msemt; loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION; loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY; /* Method association coded index */ /* FIXME: metadata-update */ if (!mono_binary_search (&loc, msemt->base, table_info_get_rows (msemt), msemt->row_size, table_locator)) return 0; start = loc.result; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION)) start--; else break; } end = start + 1; int rows = table_info_get_rows (msemt); while (end < rows) { mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE); if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx) break; ++end; } *end_idx = end; return start; } /** * mono_metadata_implmap_from_method: */ guint32 mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx) { locator_t loc; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_IMPLMAP]; if (!tdef->base) return 0; /* No index translation seems to be needed */ loc.t = tdef; loc.col_idx = MONO_IMPLMAP_MEMBER; loc.idx = ((method_idx + 1) << MONO_MEMBERFORWD_BITS) | MONO_MEMBERFORWD_METHODDEF; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; return loc.result + 1; } /** * mono_type_create_from_typespec: * \param image context where the image is created * \param type_spec typespec token * \deprecated use \c mono_type_create_from_typespec_checked that has proper error handling * * Creates a \c MonoType representing the \c TypeSpec indexed by the \p type_spec * token. */ MonoType * mono_type_create_from_typespec (MonoImage *image, guint32 type_spec) { ERROR_DECL (error); MonoType *type = mono_type_create_from_typespec_checked (image, type_spec, error); if (!type) g_error ("Could not create typespec %x due to %s", type_spec, mono_error_get_message (error)); return type; } MonoType * mono_type_create_from_typespec_checked (MonoImage *image, guint32 type_spec, MonoError *error) { guint32 idx = mono_metadata_token_index (type_spec); MonoTableInfo *t; guint32 cols [MONO_TYPESPEC_SIZE]; const char *ptr; MonoType *type, *type2; error_init (error); type = (MonoType *)mono_conc_hashtable_lookup (image->typespec_cache, GUINT_TO_POINTER (type_spec)); if (type) return type; t = &image->tables [MONO_TABLE_TYPESPEC]; mono_metadata_decode_row (t, idx-1, cols, MONO_TYPESPEC_SIZE); ptr = mono_metadata_blob_heap (image, cols [MONO_TYPESPEC_SIGNATURE]); mono_metadata_decode_value (ptr, &ptr); type = mono_metadata_parse_type_checked (image, NULL, 0, TRUE, ptr, &ptr, error); if (!type) return NULL; type2 = mono_metadata_type_dup (image, type); mono_metadata_free_type (type); mono_image_lock (image); /* We might leak some data in the image mempool if found */ type = (MonoType*)mono_conc_hashtable_insert (image->typespec_cache, GUINT_TO_POINTER (type_spec), type2); if (!type) type = type2; mono_image_unlock (image); return type; } static char* mono_image_strndup (MonoImage *image, const char *data, guint len) { char *res; if (!image) return g_strndup (data, len); res = (char *)mono_image_alloc (image, len + 1); memcpy (res, data, len); res [len] = 0; return res; } /** * mono_metadata_parse_marshal_spec: */ MonoMarshalSpec * mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr) { return mono_metadata_parse_marshal_spec_full (NULL, image, ptr); } /* * If IMAGE is non-null, memory will be allocated from its mempool, otherwise it will be allocated using malloc. * PARENT_IMAGE is the image containing the marshal spec. */ MonoMarshalSpec * mono_metadata_parse_marshal_spec_full (MonoImage *image, MonoImage *parent_image, const char *ptr) { MonoMarshalSpec *res; int len; const char *start = ptr; /* fixme: this is incomplete, but I cant find more infos in the specs */ if (image) res = (MonoMarshalSpec *)mono_image_alloc0 (image, sizeof (MonoMarshalSpec)); else res = g_new0 (MonoMarshalSpec, 1); len = mono_metadata_decode_value (ptr, &ptr); res->native = (MonoMarshalNative)*ptr++; if (res->native == MONO_NATIVE_LPARRAY) { res->data.array_data.param_num = -1; res->data.array_data.num_elem = -1; res->data.array_data.elem_mult = -1; if (ptr - start <= len) res->data.array_data.elem_type = (MonoMarshalNative)*ptr++; if (ptr - start <= len) res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr); if (ptr - start <= len) res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr); if (ptr - start <= len) { /* * LAMESPEC: Older spec versions say this parameter comes before * num_elem. Never spec versions don't talk about elem_mult at * all, but csc still emits it, and it is used to distinguish * between param_num being 0, and param_num being omitted. * So if (param_num == 0) && (num_elem > 0), then * elem_mult == 0 -> the array size is num_elem * elem_mult == 1 -> the array size is @param_num + num_elem */ res->data.array_data.elem_mult = mono_metadata_decode_value (ptr, &ptr); } } if (res->native == MONO_NATIVE_BYVALTSTR) { if (ptr - start <= len) res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr); } if (res->native == MONO_NATIVE_BYVALARRAY) { if (ptr - start <= len) res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr); } if (res->native == MONO_NATIVE_CUSTOM) { /* skip unused type guid */ len = mono_metadata_decode_value (ptr, &ptr); ptr += len; /* skip unused native type name */ len = mono_metadata_decode_value (ptr, &ptr); ptr += len; /* read custom marshaler type name */ len = mono_metadata_decode_value (ptr, &ptr); res->data.custom_data.custom_name = mono_image_strndup (image, ptr, len); ptr += len; /* read cookie string */ len = mono_metadata_decode_value (ptr, &ptr); res->data.custom_data.cookie = mono_image_strndup (image, ptr, len); res->data.custom_data.image = parent_image; } if (res->native == MONO_NATIVE_SAFEARRAY) { res->data.safearray_data.elem_type = (MonoMarshalVariant)0; res->data.safearray_data.num_elem = 0; if (ptr - start <= len) res->data.safearray_data.elem_type = (MonoMarshalVariant)*ptr++; if (ptr - start <= len) res->data.safearray_data.num_elem = *ptr++; } return res; } /** * mono_metadata_free_marshal_spec: */ void mono_metadata_free_marshal_spec (MonoMarshalSpec *spec) { if (!spec) return; if (spec->native == MONO_NATIVE_CUSTOM) { g_free (spec->data.custom_data.custom_name); g_free (spec->data.custom_data.cookie); } g_free (spec); } /** * mono_type_to_unmanaged: * The value pointed to by \p conv will contain the kind of marshalling required for this * particular type one of the \c MONO_MARSHAL_CONV_ enumeration values. * \returns A \c MonoMarshalNative enumeration value (<code>MONO_NATIVE_</code>) value * describing the underlying native reprensetation of the type. */ guint32 // FIXMEcxx MonoMarshalNative mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field, gboolean unicode, MonoMarshalConv *conv) { MonoMarshalConv dummy_conv; int t = type->type; if (!conv) conv = &dummy_conv; *conv = MONO_MARSHAL_CONV_NONE; if (m_type_is_byref (type)) return MONO_NATIVE_UINT; handle_enum: switch (t) { case MONO_TYPE_BOOLEAN: if (mspec) { switch (mspec->native) { case MONO_NATIVE_VARIANTBOOL: *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL; return MONO_NATIVE_VARIANTBOOL; case MONO_NATIVE_BOOLEAN: *conv = MONO_MARSHAL_CONV_BOOL_I4; return MONO_NATIVE_BOOLEAN; case MONO_NATIVE_I1: case MONO_NATIVE_U1: return mspec->native; default: g_error ("cant marshal bool to native type %02x", mspec->native); } } *conv = MONO_MARSHAL_CONV_BOOL_I4; return MONO_NATIVE_BOOLEAN; case MONO_TYPE_CHAR: if (mspec) { switch (mspec->native) { case MONO_NATIVE_U2: case MONO_NATIVE_U1: return mspec->native; default: g_error ("cant marshal char to native type %02x", mspec->native); } } return unicode ? MONO_NATIVE_U2 : MONO_NATIVE_U1; case MONO_TYPE_I1: return MONO_NATIVE_I1; case MONO_TYPE_U1: return MONO_NATIVE_U1; case MONO_TYPE_I2: return MONO_NATIVE_I2; case MONO_TYPE_U2: return MONO_NATIVE_U2; case MONO_TYPE_I4: return MONO_NATIVE_I4; case MONO_TYPE_U4: return MONO_NATIVE_U4; case MONO_TYPE_I8: return MONO_NATIVE_I8; case MONO_TYPE_U8: return MONO_NATIVE_U8; case MONO_TYPE_R4: return MONO_NATIVE_R4; case MONO_TYPE_R8: return MONO_NATIVE_R8; case MONO_TYPE_STRING: if (mspec) { switch (mspec->native) { case MONO_NATIVE_BSTR: *conv = MONO_MARSHAL_CONV_STR_BSTR; return MONO_NATIVE_BSTR; case MONO_NATIVE_LPSTR: *conv = MONO_MARSHAL_CONV_STR_LPSTR; return MONO_NATIVE_LPSTR; case MONO_NATIVE_LPWSTR: *conv = MONO_MARSHAL_CONV_STR_LPWSTR; return MONO_NATIVE_LPWSTR; case MONO_NATIVE_LPTSTR: *conv = MONO_MARSHAL_CONV_STR_LPTSTR; return MONO_NATIVE_LPTSTR; case MONO_NATIVE_ANSIBSTR: *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR; return MONO_NATIVE_ANSIBSTR; case MONO_NATIVE_TBSTR: *conv = MONO_MARSHAL_CONV_STR_TBSTR; return MONO_NATIVE_TBSTR; case MONO_NATIVE_UTF8STR: *conv = MONO_MARSHAL_CONV_STR_UTF8STR; return MONO_NATIVE_UTF8STR; case MONO_NATIVE_BYVALTSTR: if (unicode) *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR; else *conv = MONO_MARSHAL_CONV_STR_BYVALSTR; return MONO_NATIVE_BYVALTSTR; default: g_error ("Can not marshal string to native type '%02x': Invalid managed/unmanaged type combination (String fields must be paired with LPStr, LPWStr, BStr or ByValTStr).", mspec->native); } } if (unicode) { *conv = MONO_MARSHAL_CONV_STR_LPWSTR; return MONO_NATIVE_LPWSTR; } else { *conv = MONO_MARSHAL_CONV_STR_LPSTR; return MONO_NATIVE_LPSTR; } case MONO_TYPE_PTR: return MONO_NATIVE_UINT; case MONO_TYPE_VALUETYPE: /*FIXME*/ if (m_class_is_enumtype (type->data.klass)) { t = mono_class_enum_basetype_internal (type->data.klass)->type; goto handle_enum; } if (type->data.klass == mono_class_try_get_handleref_class ()){ *conv = MONO_MARSHAL_CONV_HANDLEREF; return MONO_NATIVE_INT; } return MONO_NATIVE_STRUCT; case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: if (mspec) { switch (mspec->native) { case MONO_NATIVE_BYVALARRAY: if ((m_class_get_element_class (type->data.klass) == mono_defaults.char_class) && !unicode) *conv = MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY; else *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY; return MONO_NATIVE_BYVALARRAY; case MONO_NATIVE_SAFEARRAY: *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY; return MONO_NATIVE_SAFEARRAY; case MONO_NATIVE_LPARRAY: *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY; return MONO_NATIVE_LPARRAY; default: g_error ("cant marshal array as native type %02x", mspec->native); } } *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY; return MONO_NATIVE_LPARRAY; case MONO_TYPE_I: return MONO_NATIVE_INT; case MONO_TYPE_U: return MONO_NATIVE_UINT; case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: { /* FIXME : we need to handle ArrayList and StringBuilder here, probably */ if (mspec) { switch (mspec->native) { case MONO_NATIVE_STRUCT: // [MarshalAs(UnmanagedType.Struct)] // object field; // // becomes a VARIANT // // [MarshalAs(UnmangedType.Struct)] // SomeClass field; // // becomes uses the CONV_OBJECT_STRUCT conversion if (t != MONO_TYPE_OBJECT) *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT; return MONO_NATIVE_STRUCT; case MONO_NATIVE_CUSTOM: return MONO_NATIVE_CUSTOM; case MONO_NATIVE_INTERFACE: *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE; return MONO_NATIVE_INTERFACE; case MONO_NATIVE_IDISPATCH: *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH; return MONO_NATIVE_IDISPATCH; case MONO_NATIVE_IUNKNOWN: *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN; return MONO_NATIVE_IUNKNOWN; case MONO_NATIVE_FUNC: if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class || type->data.klass == mono_defaults.delegate_class || m_class_get_parent (type->data.klass) == mono_defaults.multicastdelegate_class)) { *conv = MONO_MARSHAL_CONV_DEL_FTN; return MONO_NATIVE_FUNC; } /* Fall through */ default: g_error ("cant marshal object as native type %02x", mspec->native); } } if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class || type->data.klass == mono_defaults.delegate_class || m_class_get_parent (type->data.klass) == mono_defaults.multicastdelegate_class)) { *conv = MONO_MARSHAL_CONV_DEL_FTN; return MONO_NATIVE_FUNC; } if (mono_class_try_get_safehandle_class () && type->data.klass != NULL && mono_class_is_subclass_of_internal (type->data.klass, mono_class_try_get_safehandle_class (), FALSE)){ *conv = MONO_MARSHAL_CONV_SAFEHANDLE; return MONO_NATIVE_INT; } #ifndef DISABLE_COM if (t == MONO_TYPE_CLASS && mono_cominterop_is_interface (type->data.klass)){ *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE; return MONO_NATIVE_INTERFACE; } #endif *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT; return MONO_NATIVE_STRUCT; } case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC; case MONO_TYPE_GENERICINST: type = m_class_get_byval_arg (type->data.generic_class->container_class); t = type->type; goto handle_enum; case MONO_TYPE_TYPEDBYREF: default: g_error ("type 0x%02x not handled in marshal", t); } return MONO_NATIVE_MAX; } /** * mono_metadata_get_marshal_info: */ const char* mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field) { locator_t loc; MonoTableInfo *tdef = &meta->tables [MONO_TABLE_FIELDMARSHAL]; if (!tdef->base) return NULL; loc.t = tdef; loc.col_idx = MONO_FIELD_MARSHAL_PARENT; loc.idx = ((idx + 1) << MONO_HAS_FIELD_MARSHAL_BITS) | (is_field? MONO_HAS_FIELD_MARSHAL_FIELDSREF: MONO_HAS_FIELD_MARSHAL_PARAMDEF); /* FIXME: metadata-update */ /* FIXME: Index translation */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return NULL; return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE)); } MonoMethod* mono_method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context, MonoError *error) { MonoMethod *result = NULL; guint32 idx = tok >> MONO_METHODDEFORREF_BITS; error_init (error); switch (tok & MONO_METHODDEFORREF_MASK) { case MONO_METHODDEFORREF_METHODDEF: result = mono_get_method_checked (m, MONO_TOKEN_METHOD_DEF | idx, NULL, context, error); break; case MONO_METHODDEFORREF_METHODREF: result = mono_get_method_checked (m, MONO_TOKEN_MEMBER_REF | idx, NULL, context, error); break; default: mono_error_set_bad_image (error, m, "Invalid MethodDefOfRef token %x", tok); } return result; } /* * mono_class_get_overrides_full: * * Compute the method overrides belonging to class @type_token in @overrides, and the number of overrides in @num_overrides. * */ void mono_class_get_overrides_full (MonoImage *image, guint32 type_token, MonoMethod ***overrides, gint32 *num_overrides, MonoGenericContext *generic_context, MonoError *error) { locator_t loc; MonoTableInfo *tdef = &image->tables [MONO_TABLE_METHODIMPL]; guint32 start, end; gint32 i, num; guint32 cols [MONO_METHODIMPL_SIZE]; MonoMethod **result; error_init (error); *overrides = NULL; if (num_overrides) *num_overrides = 0; if (!tdef->base) return; loc.t = tdef; loc.col_idx = MONO_METHODIMPL_CLASS; loc.idx = mono_metadata_token_index (type_token); /* FIXME metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return; start = loc.result; end = start + 1; /* * We may end up in the middle of the rows... */ while (start > 0) { if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS)) start--; else break; } int rows = table_info_get_rows (tdef); while (end < rows) { if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS)) end++; else break; } num = end - start; result = g_new (MonoMethod*, num * 2); for (i = 0; i < num; ++i) { MonoMethod *method; mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE); method = mono_method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_DECLARATION], generic_context, error); if (!method) break; result [i * 2] = method; method = mono_method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_BODY], generic_context, error); if (!method) break; result [i * 2 + 1] = method; } if (!is_ok (error)) { g_free (result); *overrides = NULL; if (num_overrides) *num_overrides = 0; } else { *overrides = result; if (num_overrides) *num_overrides = num; } } /** * mono_guid_to_string: * * Converts a 16 byte Microsoft GUID to the standard string representation. */ char * mono_guid_to_string (const guint8 *guid) { return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", guid[3], guid[2], guid[1], guid[0], guid[5], guid[4], guid[7], guid[6], guid[8], guid[9], guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]); } /** * mono_guid_to_string_minimal: * * Converts a 16 byte Microsoft GUID to lower case no '-' representation.. */ char * mono_guid_to_string_minimal (const guint8 *guid) { return g_strdup_printf ("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", guid[3], guid[2], guid[1], guid[0], guid[5], guid[4], guid[7], guid[6], guid[8], guid[9], guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]); } static gboolean get_constraints (MonoImage *image, int owner, MonoClass ***constraints, MonoGenericContainer *container, MonoError *error) { MonoTableInfo *tdef = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT]; guint32 cols [MONO_GENPARCONSTRAINT_SIZE]; guint32 i, token, found; MonoClass *klass, **res; GSList *cons = NULL, *tmp; MonoGenericContext *context = &container->context; error_init (error); *constraints = NULL; found = 0; /* FIXME: metadata-update */ int rows = table_info_get_rows (tdef); for (i = 0; i < rows; ++i) { mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE); if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) { token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]); klass = mono_class_get_and_inflate_typespec_checked (image, token, context, error); if (!klass) { g_slist_free (cons); return FALSE; } cons = g_slist_append (cons, klass); ++found; } else { /* contiguous list finished */ if (found) break; } } if (!found) return TRUE; res = (MonoClass **)mono_image_alloc0 (image, sizeof (MonoClass*) * (found + 1)); for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) { res [i] = (MonoClass *)tmp->data; } g_slist_free (cons); *constraints = res; return TRUE; } /* * mono_metadata_get_generic_param_row: * * @image: * @token: TypeOrMethodDef token, owner for GenericParam * @owner: coded token, set on return * * Returns: 1-based row-id in the GenericParam table whose * owner is @token. 0 if not found. */ guint32 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner) { MonoTableInfo *tdef = &image->tables [MONO_TABLE_GENERICPARAM]; locator_t loc; g_assert (owner); if (!tdef->base) return 0; if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF) *owner = MONO_TYPEORMETHOD_TYPE; else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) *owner = MONO_TYPEORMETHOD_METHOD; else { g_error ("wrong token %x to get_generic_param_row", token); return 0; } *owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS; loc.idx = *owner; loc.col_idx = MONO_GENERICPARAM_OWNER; loc.t = tdef; /* FIXME: metadata-update */ if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) return 0; /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_GENERICPARAM_OWNER) == loc.idx)) loc.result --; return loc.result + 1; } gboolean mono_metadata_has_generic_params (MonoImage *image, guint32 token) { guint32 owner; return mono_metadata_get_generic_param_row (image, token, &owner); } /* * Memory is allocated from IMAGE's mempool. */ gboolean mono_metadata_load_generic_param_constraints_checked (MonoImage *image, guint32 token, MonoGenericContainer *container, MonoError *error) { guint32 start_row, i, owner; error_init (error); if (! (start_row = mono_metadata_get_generic_param_row (image, token, &owner))) return TRUE; for (i = 0; i < container->type_argc; i++) { if (!get_constraints (image, start_row + i, &mono_generic_container_get_param_info (container, i)->constraints, container, error)) { return FALSE; } } return TRUE; } /* * mono_metadata_load_generic_params: * * Load the type parameters from the type or method definition @token. * * Use this method after parsing a type or method definition to figure out whether it's a generic * type / method. When parsing a method definition, @parent_container points to the generic container * of the current class, if any. * * Note: This method does not load the constraints: for typedefs, this has to be done after fully * creating the type. * * Returns: NULL if @token is not a generic type or method definition or the new generic container. * * LOCKING: Acquires the loader lock * */ MonoGenericContainer * mono_metadata_load_generic_params (MonoImage *image, guint32 token, MonoGenericContainer *parent_container, gpointer real_owner) { MonoTableInfo *tdef = &image->tables [MONO_TABLE_GENERICPARAM]; guint32 cols [MONO_GENERICPARAM_SIZE]; guint32 i, owner = 0, n; MonoGenericContainer *container; MonoGenericParamFull *params; MonoGenericContext *context; gboolean is_method = mono_metadata_token_table (token) == MONO_TABLE_METHOD; gboolean is_anonymous = real_owner == NULL; if (!(i = mono_metadata_get_generic_param_row (image, token, &owner))) return NULL; mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE); params = NULL; n = 0; container = (MonoGenericContainer *)mono_image_alloc0 (image, sizeof (MonoGenericContainer)); container->is_anonymous = is_anonymous; if (is_anonymous) { container->owner.image = image; } else { if (is_method) container->owner.method = (MonoMethod*)real_owner; else container->owner.klass = (MonoClass*)real_owner; } do { n++; params = (MonoGenericParamFull *)g_realloc (params, sizeof (MonoGenericParamFull) * n); memset (&params [n - 1], 0, sizeof (MonoGenericParamFull)); params [n - 1].owner = container; params [n - 1].num = cols [MONO_GENERICPARAM_NUMBER]; params [n - 1].info.token = i | MONO_TOKEN_GENERIC_PARAM; params [n - 1].info.flags = cols [MONO_GENERICPARAM_FLAGS]; params [n - 1].info.name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]); if (params [n - 1].num != n - 1) g_warning ("GenericParam table unsorted or hole in generic param sequence: token %d", i); /* FIXME: metadata-update */ if (++i > table_info_get_rows (tdef)) break; mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE); } while (cols [MONO_GENERICPARAM_OWNER] == owner); container->type_argc = n; container->type_params = (MonoGenericParamFull *)mono_image_alloc0 (image, sizeof (MonoGenericParamFull) * n); memcpy (container->type_params, params, sizeof (MonoGenericParamFull) * n); g_free (params); container->parent = parent_container; if (is_method) container->is_method = 1; g_assert (container->parent == NULL || container->is_method); context = &container->context; if (container->is_method) { context->class_inst = container->parent ? container->parent->context.class_inst : NULL; context->method_inst = mono_get_shared_generic_inst (container); } else { context->class_inst = mono_get_shared_generic_inst (container); } return container; } MonoGenericInst * mono_get_shared_generic_inst (MonoGenericContainer *container) { MonoType **type_argv; MonoType *helper; MonoGenericInst *nginst; int i; type_argv = g_new0 (MonoType *, container->type_argc); helper = g_new0 (MonoType, container->type_argc); for (i = 0; i < container->type_argc; i++) { MonoType *t = &helper [i]; t->type = container->is_method ? MONO_TYPE_MVAR : MONO_TYPE_VAR; t->data.generic_param = mono_generic_container_get_param (container, i); type_argv [i] = t; } nginst = mono_metadata_get_generic_inst (container->type_argc, type_argv); g_free (type_argv); g_free (helper); return nginst; } /** * mono_type_is_byref: * \param type the \c MonoType operated on * \returns TRUE if \p type represents a type passed by reference, * FALSE otherwise. */ mono_bool mono_type_is_byref (MonoType *type) { mono_bool result; MONO_ENTER_GC_UNSAFE; // FIXME slow result = m_type_is_byref (type); MONO_EXIT_GC_UNSAFE; return result; } /** * mono_type_get_type: * \param type the \c MonoType operated on * \returns the IL type value for \p type. This is one of the \c MonoTypeEnum * enum members like \c MONO_TYPE_I4 or \c MONO_TYPE_STRING. */ int mono_type_get_type (MonoType *type) { return mono_type_get_type_internal (type); } /** * mono_type_get_signature: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_FNPTR . * \returns the \c MonoMethodSignature pointer that describes the signature * of the function pointer \p type represents. */ MonoMethodSignature* mono_type_get_signature (MonoType *type) { return mono_type_get_signature_internal (type); } /** * mono_type_get_class: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_CLASS or a * \c MONO_TYPE_VALUETYPE . For more general functionality, use \c mono_class_from_mono_type_internal, * instead. * \returns the \c MonoClass pointer that describes the class that \p type represents. */ MonoClass* mono_type_get_class (MonoType *type) { /* FIXME: review the runtime users before adding the assert here */ return mono_type_get_class_internal (type); } /** * mono_type_get_array_type: * \param type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_ARRAY . * \returns a \c MonoArrayType struct describing the array type that \p type * represents. The info includes details such as rank, array element type * and the sizes and bounds of multidimensional arrays. */ MonoArrayType* mono_type_get_array_type (MonoType *type) { return mono_type_get_array_type_internal (type); } /** * mono_type_get_ptr_type: * \pararm type the \c MonoType operated on * It is only valid to call this function if \p type is a \c MONO_TYPE_PTR . * \returns the \c MonoType pointer that describes the type that \p type * represents a pointer to. */ MonoType* mono_type_get_ptr_type (MonoType *type) { g_assert (type->type == MONO_TYPE_PTR); return type->data.type; } /** * mono_type_get_modifiers: */ MonoClass* mono_type_get_modifiers (MonoType *type, gboolean *is_required, gpointer *iter) { /* FIXME: implement */ return NULL; } /** * mono_type_is_struct: * \param type the \c MonoType operated on * \returns TRUE if \p type is a struct, that is a \c ValueType but not an enum * or a basic type like \c System.Int32 . FALSE otherwise. */ mono_bool mono_type_is_struct (MonoType *type) { return (!m_type_is_byref (type) && ((type->type == MONO_TYPE_VALUETYPE && !m_class_is_enumtype (type->data.klass)) || (type->type == MONO_TYPE_TYPEDBYREF) || ((type->type == MONO_TYPE_GENERICINST) && mono_metadata_generic_class_is_valuetype (type->data.generic_class) && !m_class_is_enumtype (type->data.generic_class->container_class)))); } /** * mono_type_is_void: * \param type the \c MonoType operated on * \returns TRUE if \p type is \c System.Void . FALSE otherwise. */ mono_bool mono_type_is_void (MonoType *type) { return (type && (type->type == MONO_TYPE_VOID) && !m_type_is_byref (type)); } /** * mono_type_is_pointer: * \param type the \c MonoType operated on * \returns TRUE if \p type is a managed or unmanaged pointer type. FALSE otherwise. */ mono_bool mono_type_is_pointer (MonoType *type) { return (type && ((m_type_is_byref (type) || (type->type == MONO_TYPE_I) || type->type == MONO_TYPE_STRING) || (type->type == MONO_TYPE_SZARRAY) || (type->type == MONO_TYPE_CLASS) || (type->type == MONO_TYPE_U) || (type->type == MONO_TYPE_OBJECT) || (type->type == MONO_TYPE_ARRAY) || (type->type == MONO_TYPE_PTR) || (type->type == MONO_TYPE_FNPTR))); } /** * mono_type_is_reference: * \param type the \c MonoType operated on * \returns TRUE if \p type represents an object reference. FALSE otherwise. */ mono_bool mono_type_is_reference (MonoType *type) { /* NOTE: changing this function to return TRUE more often may have * consequences for generic sharing in the AOT compiler. In * particular, returning TRUE for generic parameters with a 'class' * constraint may cause crashes. */ return (type && (((type->type == MONO_TYPE_STRING) || (type->type == MONO_TYPE_SZARRAY) || (type->type == MONO_TYPE_CLASS) || (type->type == MONO_TYPE_OBJECT) || (type->type == MONO_TYPE_ARRAY)) || ((type->type == MONO_TYPE_GENERICINST) && !mono_metadata_generic_class_is_valuetype (type->data.generic_class)))); } mono_bool mono_type_is_generic_parameter (MonoType *type) { return !m_type_is_byref (type) && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR); } /** * mono_signature_get_return_type: * \param sig the method signature inspected * \returns the return type of the method signature \p sig */ MonoType* mono_signature_get_return_type (MonoMethodSignature *sig) { MonoType *result; MONO_ENTER_GC_UNSAFE; result = sig->ret; MONO_EXIT_GC_UNSAFE; return result; } /** * mono_signature_get_params: * \param sig the method signature inspected * \param iter pointer to an iterator * Iterates over the parameters for the method signature \p sig. * A \c void* pointer must be initialized to NULL to start the iteration * and its address is passed to this function repeteadly until it returns * NULL. * \returns the next parameter type of the method signature \p sig, * NULL when finished. */ MonoType* mono_signature_get_params (MonoMethodSignature *sig, gpointer *iter) { MonoType *result; MONO_ENTER_GC_UNSAFE; result = mono_signature_get_params_internal (sig, iter); MONO_EXIT_GC_UNSAFE; return result; } MonoType* mono_signature_get_params_internal (MonoMethodSignature *sig, gpointer *iter) { MonoType** type; if (!iter) return NULL; if (!*iter) { /* start from the first */ if (sig->param_count) { *iter = &sig->params [0]; return sig->params [0]; } else { /* no method */ return NULL; } } type = (MonoType **)*iter; type++; if (type < &sig->params [sig->param_count]) { *iter = type; return *type; } return NULL; } /** * mono_signature_get_param_count: * \param sig the method signature inspected * \returns the number of parameters in the method signature \p sig. */ guint32 mono_signature_get_param_count (MonoMethodSignature *sig) { return sig->param_count; } /** * mono_signature_get_call_conv: * \param sig the method signature inspected * \returns the call convention of the method signature \p sig. */ guint32 mono_signature_get_call_conv (MonoMethodSignature *sig) { return sig->call_convention; } /** * mono_signature_vararg_start: * \param sig the method signature inspected * \returns the number of the first vararg parameter in the * method signature \param sig. \c -1 if this is not a vararg signature. */ int mono_signature_vararg_start (MonoMethodSignature *sig) { return sig->sentinelpos; } /** * mono_signature_is_instance: * \param sig the method signature inspected * \returns TRUE if this the method signature \p sig has an implicit * first instance argument. FALSE otherwise. */ gboolean mono_signature_is_instance (MonoMethodSignature *sig) { return sig->hasthis; } /** * mono_signature_param_is_out * \param sig the method signature inspected * \param param_num the 0-based index of the inspected parameter * \returns TRUE if the parameter is an out parameter, FALSE * otherwise. */ mono_bool mono_signature_param_is_out (MonoMethodSignature *sig, int param_num) { g_assert (param_num >= 0 && param_num < sig->param_count); return (sig->params [param_num]->attrs & PARAM_ATTRIBUTE_OUT) != 0; } /** * mono_signature_explicit_this: * \param sig the method signature inspected * \returns TRUE if this the method signature \p sig has an explicit * instance argument. FALSE otherwise. */ gboolean mono_signature_explicit_this (MonoMethodSignature *sig) { return sig->explicit_this; } /* for use with allocated memory blocks (assumes alignment is to 8 bytes) */ guint mono_aligned_addr_hash (gconstpointer ptr) { /* Same hashing we use for objects */ return (GPOINTER_TO_UINT (ptr) >> 3) * 2654435761u; } /* * If @field belongs to an inflated generic class, return the corresponding field of the * generic type definition class. */ MonoClassField* mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassField *field) { MonoClass *gtd; int offset; if (!mono_class_is_ginst (m_field_get_parent (field))) return field; gtd = mono_class_get_generic_class (m_field_get_parent (field))->container_class; offset = field - m_class_get_fields (m_field_get_parent (field)); return m_class_get_fields (gtd) + offset; } /* * If @event belongs to an inflated generic class, return the corresponding event of the * generic type definition class. */ MonoEvent* mono_metadata_get_corresponding_event_from_generic_type_definition (MonoEvent *event) { MonoClass *gtd; int offset; if (!mono_class_is_ginst (event->parent)) return event; gtd = mono_class_get_generic_class (event->parent)->container_class; offset = event - mono_class_get_event_info (event->parent)->events; return mono_class_get_event_info (gtd)->events + offset; } /* * If @property belongs to an inflated generic class, return the corresponding property of the * generic type definition class. */ MonoProperty* mono_metadata_get_corresponding_property_from_generic_type_definition (MonoProperty *property) { MonoClassPropertyInfo *info; MonoClass *gtd; int offset; if (!mono_class_is_ginst (property->parent)) return property; info = mono_class_get_property_info (property->parent); gtd = mono_class_get_generic_class (property->parent)->container_class; offset = property - info->properties; return mono_class_get_property_info (gtd)->properties + offset; } MonoWrapperCaches* mono_method_get_wrapper_cache (MonoMethod *method) { if (method->is_inflated) { MonoMethodInflated *imethod = (MonoMethodInflated *)method; return &imethod->owner->wrapper_caches; } else { return &m_class_get_image (method->klass)->wrapper_caches; } } void mono_loader_set_strict_assembly_name_check (gboolean enabled) { check_assembly_names_strictly = enabled; } gboolean mono_loader_get_strict_assembly_name_check (void) { return check_assembly_names_strictly; } gboolean mono_type_is_aggregate_mods (const MonoType *t) { if (!t->has_cmods) return FALSE; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; return full->is_aggregate; } MonoCustomModContainer * mono_type_get_cmods (const MonoType *t) { if (!t->has_cmods) return NULL; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; g_assert (!full->is_aggregate); return &full->mods.cmods; } MonoAggregateModContainer * mono_type_get_amods (const MonoType *t) { if (!t->has_cmods) return NULL; MonoTypeWithModifiers *full = (MonoTypeWithModifiers *)t; g_assert (full->is_aggregate); return full->mods.amods; } size_t mono_sizeof_aggregate_modifiers (uint8_t num_mods) { size_t accum = 0; accum += offsetof (MonoAggregateModContainer, modifiers); accum += sizeof (MonoSingleCustomMod) * num_mods; return accum; } size_t mono_sizeof_type_with_mods (uint8_t num_mods, gboolean is_aggregate) { if (num_mods == 0) return sizeof (MonoType); size_t accum = 0; accum += offsetof (MonoTypeWithModifiers, mods); if (!is_aggregate) { accum += offsetof (struct _MonoCustomModContainer, modifiers); accum += sizeof (MonoCustomMod) * num_mods; } else { accum += offsetof (MonoAggregateModContainer, modifiers); accum += sizeof (MonoAggregateModContainer *); } return accum; } size_t mono_sizeof_type (const MonoType *ty) { if (ty->has_cmods) { if (!mono_type_is_aggregate_mods (ty)) { MonoCustomModContainer *cmods = mono_type_get_cmods (ty); return mono_sizeof_type_with_mods (cmods->count, FALSE); } else { MonoAggregateModContainer *amods = mono_type_get_amods (ty); return mono_sizeof_type_with_mods (amods->count, TRUE); } } else return sizeof (MonoType); } void mono_type_set_amods (MonoType *t, MonoAggregateModContainer *amods) { g_assert (t->has_cmods); MonoTypeWithModifiers *t_full = (MonoTypeWithModifiers*)t; g_assert (t_full->is_aggregate); g_assert (t_full->mods.amods == NULL); t_full->mods.amods = amods; } #ifndef DISABLE_COM static void mono_signature_append_class_name (GString *res, MonoClass *klass) { if (!klass) { g_string_append (res, "<UNKNOWN>"); return; } if (m_class_get_nested_in (klass)) { mono_signature_append_class_name (res, m_class_get_nested_in (klass)); g_string_append_c (res, '+'); } else if (*m_class_get_name_space (klass)) { g_string_append (res, m_class_get_name_space (klass)); g_string_append_c (res, '.'); } g_string_append (res, m_class_get_name (klass)); } static void mono_guid_signature_append_method (GString *res, MonoMethodSignature *sig); static void mono_guid_signature_append_type (GString *res, MonoType *type) { int i; switch (type->type) { case MONO_TYPE_VOID: g_string_append (res, "void"); break; case MONO_TYPE_BOOLEAN: g_string_append (res, "bool"); break; case MONO_TYPE_CHAR: g_string_append (res, "wchar"); break; case MONO_TYPE_I1: g_string_append (res, "int8"); break; case MONO_TYPE_U1: g_string_append (res, "unsigned int8"); break; case MONO_TYPE_I2: g_string_append (res, "int16"); break; case MONO_TYPE_U2: g_string_append (res, "unsigned int16"); break; case MONO_TYPE_I4: g_string_append (res, "int32"); break; case MONO_TYPE_U4: g_string_append (res, "unsigned int32"); break; case MONO_TYPE_I8: g_string_append (res, "int64"); break; case MONO_TYPE_U8: g_string_append (res, "unsigned int64"); break; case MONO_TYPE_R4: g_string_append (res, "float32"); break; case MONO_TYPE_R8: g_string_append (res, "float64"); break; case MONO_TYPE_U: g_string_append (res, "unsigned int"); break; case MONO_TYPE_I: g_string_append (res, "int"); break; case MONO_TYPE_OBJECT: g_string_append (res, "class System.Object"); break; case MONO_TYPE_STRING: g_string_append (res, "class System.String"); break; case MONO_TYPE_TYPEDBYREF: g_string_append (res, "refany"); break; case MONO_TYPE_VALUETYPE: g_string_append (res, "value class "); mono_signature_append_class_name (res, type->data.klass); break; case MONO_TYPE_CLASS: g_string_append (res, "class "); mono_signature_append_class_name (res, type->data.klass); break; case MONO_TYPE_SZARRAY: mono_guid_signature_append_type (res, m_class_get_byval_arg (type->data.klass)); g_string_append (res, "[]"); break; case MONO_TYPE_ARRAY: mono_guid_signature_append_type (res, m_class_get_byval_arg (type->data.array->eklass)); g_string_append_c (res, '['); if (type->data.array->rank == 0) g_string_append (res, "??"); for (i = 0; i < type->data.array->rank; ++i) { if (i > 0) g_string_append_c (res, ','); if (type->data.array->sizes[i] == 0 || type->data.array->lobounds[i] == 0) continue; g_string_append_printf (res, "%d", type->data.array->lobounds[i]); g_string_append (res, "..."); g_string_append_printf (res, "%d", type->data.array->lobounds[i] + type->data.array->sizes[i] + 1); } g_string_append_c (res, ']'); break; case MONO_TYPE_MVAR: case MONO_TYPE_VAR: if (type->data.generic_param) g_string_append_printf (res, "%s%d", type->type == MONO_TYPE_VAR ? "!" : "!!", mono_generic_param_num (type->data.generic_param)); else g_string_append (res, "<UNKNOWN>"); break; case MONO_TYPE_GENERICINST: { MonoGenericContext *context; mono_guid_signature_append_type (res, m_class_get_byval_arg (type->data.generic_class->container_class)); g_string_append (res, "<"); context = &type->data.generic_class->context; if (context->class_inst) { for (i = 0; i < context->class_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ","); mono_guid_signature_append_type (res, context->class_inst->type_argv [i]); } } else if (context->method_inst) { for (i = 0; i < context->method_inst->type_argc; ++i) { if (i > 0) g_string_append (res, ","); mono_guid_signature_append_type (res, context->method_inst->type_argv [i]); } } g_string_append (res, ">"); break; } case MONO_TYPE_FNPTR: g_string_append (res, "fnptr "); mono_guid_signature_append_method (res, type->data.method); break; case MONO_TYPE_PTR: mono_guid_signature_append_type (res, type->data.type); g_string_append_c (res, '*'); break; default: break; } if (m_type_is_byref (type)) g_string_append_c (res, '&'); } static void mono_guid_signature_append_method (GString *res, MonoMethodSignature *sig) { int i, j; if (mono_signature_is_instance (sig)) g_string_append (res, "instance "); if (sig->generic_param_count) g_string_append (res, "generic "); switch (mono_signature_get_call_conv (sig)) { case MONO_CALL_DEFAULT: break; case MONO_CALL_C: g_string_append (res, "unmanaged cdecl "); break; case MONO_CALL_STDCALL: g_string_append (res, "unmanaged stdcall "); break; case MONO_CALL_THISCALL: g_string_append (res, "unmanaged thiscall "); break; case MONO_CALL_FASTCALL: g_string_append (res, "unmanaged fastcall "); break; case MONO_CALL_VARARG: g_string_append (res, "vararg "); break; default: break; } mono_guid_signature_append_type (res, mono_signature_get_return_type_internal(sig)); g_string_append_c (res, '('); for (i = 0, j = 0; i < sig->param_count && j < sig->param_count; ++i, ++j) { if (i > 0) g_string_append_c (res, ','); if (sig->params [j]->attrs & PARAM_ATTRIBUTE_IN) { /*.NET runtime "incorrectly" shifts the parameter signatures too...*/ g_string_append (res, "required_modifier System.Runtime.InteropServices.InAttribute"); if (++i == sig->param_count) break; g_string_append_c (res, ','); } mono_guid_signature_append_type (res, sig->params [j]); } g_string_append_c (res, ')'); } static void mono_generate_v3_guid_for_interface (MonoClass* klass, guint8* guid) { /* COM+ Runtime GUID {69f9cbc9-da05-11d1-9408-0000f8083460} */ static const guchar guid_name_space[] = {0x69,0xf9,0xcb,0xc9,0xda,0x05,0x11,0xd1,0x94,0x08,0x00,0x00,0xf8,0x08,0x34,0x60}; MonoMD5Context ctx; MonoMethod *method; gpointer iter = NULL; guchar byte; glong items_read, items_written; int i; mono_md5_init (&ctx); mono_md5_update (&ctx, guid_name_space, sizeof(guid_name_space)); GString *name = g_string_new (""); mono_signature_append_class_name (name, klass); gunichar2 *unicode_name = g_utf8_to_utf16 (name->str, name->len, &items_read, &items_written, NULL); mono_md5_update (&ctx, (guchar *)unicode_name, items_written * sizeof(gunichar2)); g_free (unicode_name); g_string_free (name, TRUE); while ((method = mono_class_get_methods(klass, &iter)) != NULL) { ERROR_DECL (error); if (!mono_cominterop_method_com_visible(method)) continue; MonoMethodSignature *sig = mono_method_signature_checked (method, error); mono_error_assert_ok (error); /*FIXME proper error handling*/ GString *res = g_string_new (""); mono_guid_signature_append_method (res, sig); mono_md5_update (&ctx, (guchar *)res->str, res->len); g_string_free (res, TRUE); for (i = 0; i < sig->param_count; ++i) { byte = sig->params [i]->attrs; mono_md5_update (&ctx, &byte, 1); } } byte = 0; if (mono_md5_ctx_byte_length (&ctx) & 1) mono_md5_update (&ctx, &byte, 1); mono_md5_final (&ctx, (guchar *)guid); guid[6] &= 0x0f; guid[6] |= 0x30; /* v3 (md5) */ guid[8] &= 0x3F; guid[8] |= 0x80; *(guint32 *)(guid + 0) = GUINT32_FROM_BE(*(guint32 *)(guid + 0)); *(guint16 *)(guid + 4) = GUINT16_FROM_BE(*(guint16 *)(guid + 4)); *(guint16 *)(guid + 6) = GUINT16_FROM_BE(*(guint16 *)(guid + 6)); } #endif static gint mono_unichar_xdigit_value (gunichar c) { if (c >= 0x30 && c <= 0x39) /*0-9*/ return (c - 0x30); if (c >= 0x41 && c <= 0x46) /*A-F*/ return (c - 0x37); if (c >= 0x61 && c <= 0x66) /*a-f*/ return (c - 0x57); return -1; } /** * mono_string_to_guid: * * Converts the standard string representation of a GUID * to a 16 byte Microsoft GUID. */ static void mono_string_to_guid (MonoString* string, guint8 *guid) { gunichar2 * chars = mono_string_chars_internal (string); int i = 0; static const guint8 indexes[16] = {7, 5, 3, 1, 12, 10, 17, 15, 20, 22, 25, 27, 29, 31, 33, 35}; for (i = 0; i < sizeof(indexes); i++) guid [i] = mono_unichar_xdigit_value (chars [indexes [i]]) + (mono_unichar_xdigit_value (chars [indexes [i] - 1]) << 4); } static GENERATE_GET_CLASS_WITH_CACHE (guid_attribute, "System.Runtime.InteropServices", "GuidAttribute") void mono_metadata_get_class_guid (MonoClass* klass, guint8* guid, MonoError *error) { MonoReflectionGuidAttribute *attr = NULL; MonoCustomAttrInfo *cinfo = mono_custom_attrs_from_class_checked (klass, error); if (!is_ok (error)) return; if (cinfo) { attr = (MonoReflectionGuidAttribute*)mono_custom_attrs_get_attr_checked (cinfo, mono_class_get_guid_attribute_class (), error); if (!is_ok (error)) return; if (!cinfo->cached) mono_custom_attrs_free (cinfo); } memset(guid, 0, 16); if (attr) mono_string_to_guid (attr->guid, guid); #ifndef DISABLE_COM else if (mono_class_is_interface (klass)) mono_generate_v3_guid_for_interface (klass, guid); else g_warning ("Generated GUIDs only implemented for interfaces!"); #endif }
1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/mono/mono/metadata/mono-debug.c
/** * \file * * Author: * Mono Project (http://www.mono-project.com) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * Copyright 2011 Xamarin Inc (http://www.xamarin.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <mono/metadata/assembly.h> #include <mono/metadata/assembly-internals.h> #include <mono/metadata/tabledefs.h> #include <mono/metadata/tokentype.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/mono-debug.h> #include <mono/metadata/debug-internals.h> #include <mono/metadata/mono-endian.h> #include <mono/metadata/gc-internals.h> #include <mono/metadata/mempool.h> #include <mono/metadata/debug-mono-symfile.h> #include <mono/metadata/debug-mono-ppdb.h> #include <mono/metadata/exception-internals.h> #include <mono/metadata/runtime.h> #include <mono/metadata/metadata-update.h> #include <string.h> #if NO_UNALIGNED_ACCESS #define WRITE_UNALIGNED(type, addr, val) \ memcpy(addr, &val, sizeof(type)) #define READ_UNALIGNED(type, addr, val) \ memcpy(&val, addr, sizeof(type)) #else #define WRITE_UNALIGNED(type, addr, val) \ (*(type *)(addr) = (val)) #define READ_UNALIGNED(type, addr, val) \ val = (*(type *)(addr)) #endif /* Many functions have 'domain' parameters, those are ignored */ /* * This contains per-memory manager info. */ typedef struct { MonoMemPool *mp; /* Maps MonoMethod->MonoDebugMethodAddress */ GHashTable *method_hash; } DebugMemoryManager; /* This contains JIT debugging information about a method in serialized format */ struct _MonoDebugMethodAddress { const guint8 *code_start; guint32 code_size; guint8 data [MONO_ZERO_LEN_ARRAY]; }; static MonoDebugFormat mono_debug_format = MONO_DEBUG_FORMAT_NONE; static gboolean mono_debug_initialized = FALSE; /* Maps MonoImage -> MonoMonoDebugHandle */ static GHashTable *mono_debug_handles; static mono_mutex_t debugger_lock_mutex; static gboolean is_attached = FALSE; static MonoDebugHandle *mono_debug_open_image (MonoImage *image, const guint8 *raw_contents, int size); static MonoDebugHandle *mono_debug_get_image (MonoImage *image); static void add_assembly (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer user_data, MonoError *error); static MonoDebugHandle *open_symfile_from_bundle (MonoImage *image); static DebugMemoryManager* get_mem_manager (MonoMethod *method) { MonoMemoryManager *mem_manager = m_method_get_mem_manager (method); if (!mono_debug_initialized) return NULL; if (!mem_manager->debug_info) { DebugMemoryManager *info; info = g_new0 (DebugMemoryManager, 1); info->mp = mono_mempool_new (); info->method_hash = g_hash_table_new (NULL, NULL); mono_memory_barrier (); mono_debugger_lock (); if (!mem_manager->debug_info) mem_manager->debug_info = info; // FIXME: Free otherwise mono_debugger_unlock (); } return (DebugMemoryManager*)mem_manager->debug_info; } /* * mono_mem_manager_free_debug_info: * * Free the information maintained by this module for MEM_MANAGER. */ void mono_mem_manager_free_debug_info (MonoMemoryManager *memory_manager) { DebugMemoryManager *info = (DebugMemoryManager*)memory_manager->debug_info; if (!info) return; mono_mempool_destroy (info->mp); g_hash_table_destroy (info->method_hash); g_free (info); } static void free_debug_handle (MonoDebugHandle *handle) { if (handle->ppdb) mono_ppdb_close (handle->ppdb); if (handle->symfile) mono_debug_close_mono_symbol_file (handle->symfile); /* decrease the refcount added with mono_image_addref () */ mono_image_close (handle->image); g_free (handle); } /* * Initialize debugging support. * * This method must be called after loading corlib, * but before opening the application's main assembly because we need to set some * callbacks here. */ void mono_debug_init (MonoDebugFormat format) { g_assert (!mono_debug_initialized); if (format == MONO_DEBUG_FORMAT_DEBUGGER) g_error ("The mdb debugger is no longer supported."); mono_debug_initialized = TRUE; mono_debug_format = format; mono_os_mutex_init_recursive (&debugger_lock_mutex); mono_debugger_lock (); mono_debug_handles = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) free_debug_handle); mono_install_assembly_load_hook_v2 (add_assembly, NULL, FALSE); mono_debugger_unlock (); } void mono_debug_open_image_from_memory (MonoImage *image, const guint8 *raw_contents, int size) { MONO_ENTER_GC_UNSAFE; if (!mono_debug_initialized) goto leave; mono_debug_open_image (image, raw_contents, size); leave: MONO_EXIT_GC_UNSAFE; } void mono_debug_cleanup (void) { } /** * mono_debug_domain_create: */ void mono_debug_domain_create (MonoDomain *domain) { g_assert_not_reached (); } void mono_debug_domain_unload (MonoDomain *domain) { g_assert_not_reached (); } /* * LOCKING: Assumes the debug lock is held. */ static MonoDebugHandle * mono_debug_get_image (MonoImage *image) { return (MonoDebugHandle *)g_hash_table_lookup (mono_debug_handles, image); } /** * mono_debug_close_image: */ void mono_debug_close_image (MonoImage *image) { MonoDebugHandle *handle; if (!mono_debug_initialized) return; mono_debugger_lock (); handle = mono_debug_get_image (image); if (!handle) { mono_debugger_unlock (); return; } g_hash_table_remove (mono_debug_handles, image); mono_debugger_unlock (); } MonoDebugHandle * mono_debug_get_handle (MonoImage *image) { return mono_debug_open_image (image, NULL, 0); } static MonoDebugHandle * mono_debug_open_image (MonoImage *image, const guint8 *raw_contents, int size) { MonoDebugHandle *handle; if (mono_image_is_dynamic (image)) return NULL; mono_debugger_lock (); handle = mono_debug_get_image (image); if (handle != NULL) { mono_debugger_unlock (); return handle; } handle = g_new0 (MonoDebugHandle, 1); handle->image = image; mono_image_addref (image); /* Try a ppdb file first */ handle->ppdb = mono_ppdb_load_file (handle->image, raw_contents, size); if (!handle->ppdb) handle->symfile = mono_debug_open_mono_symbols (handle, raw_contents, size, FALSE); g_hash_table_insert (mono_debug_handles, image, handle); mono_debugger_unlock (); return handle; } static void add_assembly (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer user_data, MonoError *error) { MonoDebugHandle *handle; MonoImage *image; mono_debugger_lock (); image = mono_assembly_get_image_internal (assembly); handle = open_symfile_from_bundle (image); if (!handle) mono_debug_open_image (image, NULL, 0); mono_debugger_unlock (); } struct LookupMethodData { MonoDebugMethodInfo *minfo; MonoMethod *method; }; static void lookup_method_func (gpointer key, gpointer value, gpointer user_data) { MonoDebugHandle *handle = (MonoDebugHandle *) value; struct LookupMethodData *data = (struct LookupMethodData *) user_data; if (data->minfo) return; if (handle->ppdb) data->minfo = mono_ppdb_lookup_method (handle, data->method); else if (handle->symfile) data->minfo = mono_debug_symfile_lookup_method (handle, data->method); } static MonoDebugMethodInfo * lookup_method (MonoMethod *method) { struct LookupMethodData data; data.minfo = NULL; data.method = method; if (!mono_debug_handles) return NULL; g_hash_table_foreach (mono_debug_handles, lookup_method_func, &data); return data.minfo; } /** * mono_debug_lookup_method: * * Lookup symbol file information for the method \p method. The returned * \c MonoDebugMethodInfo is a private structure, but it can be passed to * \c mono_debug_symfile_lookup_location. */ MonoDebugMethodInfo * mono_debug_lookup_method (MonoMethod *method) { MonoDebugMethodInfo *minfo; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); mono_debugger_unlock (); return minfo; } typedef struct { gboolean found; MonoImage *image; } LookupImageData; static void lookup_image_func (gpointer key, gpointer value, gpointer user_data) { MonoDebugHandle *handle = (MonoDebugHandle *) value; LookupImageData *data = (LookupImageData *) user_data; if (data->found) return; if (handle->image == data->image && (handle->symfile || handle->ppdb)) data->found = TRUE; } gboolean mono_debug_image_has_debug_info (MonoImage *image) { LookupImageData data; if (!mono_debug_handles) return FALSE; memset (&data, 0, sizeof (data)); data.image = image; mono_debugger_lock (); g_hash_table_foreach (mono_debug_handles, lookup_image_func, &data); mono_debugger_unlock (); return data.found; } static void write_leb128 (guint32 value, guint8 *ptr, guint8 **rptr) { do { guint8 byte = value & 0x7f; value >>= 7; if (value) byte |= 0x80; *ptr++ = byte; } while (value); *rptr = ptr; } static void write_sleb128 (gint32 value, guint8 *ptr, guint8 **rptr) { gboolean more = 1; while (more) { guint8 byte = value & 0x7f; value >>= 7; if (((value == 0) && ((byte & 0x40) == 0)) || ((value == -1) && (byte & 0x40))) more = 0; else byte |= 0x80; *ptr++ = byte; } *rptr = ptr; } /* leb128 uses a maximum of 5 bytes for a 32 bit value */ #define LEB128_MAX_SIZE 5 #define WRITE_VARIABLE_MAX_SIZE (5 * LEB128_MAX_SIZE + sizeof (gpointer)) static void write_variable (MonoDebugVarInfo *var, guint8 *ptr, guint8 **rptr) { write_leb128 (var->index, ptr, &ptr); write_sleb128 (var->offset, ptr, &ptr); write_leb128 (var->size, ptr, &ptr); write_leb128 (var->begin_scope, ptr, &ptr); write_leb128 (var->end_scope, ptr, &ptr); WRITE_UNALIGNED (gpointer, ptr, var->type); ptr += sizeof (gpointer); *rptr = ptr; } /** * mono_debug_add_method: */ MonoDebugMethodAddress * mono_debug_add_method (MonoMethod *method, MonoDebugMethodJitInfo *jit, MonoDomain *domain) { DebugMemoryManager *info; MonoDebugMethodAddress *address; guint8 buffer [BUFSIZ]; guint8 *ptr, *oldptr; guint32 i, size, total_size, max_size; info = get_mem_manager (method); max_size = (5 * LEB128_MAX_SIZE) + 1 + (2 * LEB128_MAX_SIZE * jit->num_line_numbers); if (jit->has_var_info) { /* this */ max_size += 1; if (jit->this_var) max_size += WRITE_VARIABLE_MAX_SIZE; /* params */ max_size += LEB128_MAX_SIZE; max_size += jit->num_params * WRITE_VARIABLE_MAX_SIZE; /* locals */ max_size += LEB128_MAX_SIZE; max_size += jit->num_locals * WRITE_VARIABLE_MAX_SIZE; /* gsharedvt */ max_size += 1; if (jit->gsharedvt_info_var) max_size += 2 * WRITE_VARIABLE_MAX_SIZE; } if (max_size > BUFSIZ) ptr = oldptr = (guint8 *)g_malloc (max_size); else ptr = oldptr = buffer; write_leb128 (jit->prologue_end, ptr, &ptr); write_leb128 (jit->epilogue_begin, ptr, &ptr); write_leb128 (jit->num_line_numbers, ptr, &ptr); for (i = 0; i < jit->num_line_numbers; i++) { MonoDebugLineNumberEntry *lne = &jit->line_numbers [i]; write_sleb128 (lne->il_offset, ptr, &ptr); write_sleb128 (lne->native_offset, ptr, &ptr); } write_leb128 (jit->has_var_info, ptr, &ptr); if (jit->has_var_info) { *ptr++ = jit->this_var ? 1 : 0; if (jit->this_var) write_variable (jit->this_var, ptr, &ptr); write_leb128 (jit->num_params, ptr, &ptr); for (i = 0; i < jit->num_params; i++) write_variable (&jit->params [i], ptr, &ptr); write_leb128 (jit->num_locals, ptr, &ptr); for (i = 0; i < jit->num_locals; i++) write_variable (&jit->locals [i], ptr, &ptr); *ptr++ = jit->gsharedvt_info_var ? 1 : 0; if (jit->gsharedvt_info_var) { write_variable (jit->gsharedvt_info_var, ptr, &ptr); write_variable (jit->gsharedvt_locals_var, ptr, &ptr); } } size = ptr - oldptr; g_assert (size < max_size); total_size = size + sizeof (MonoDebugMethodAddress); mono_debugger_lock (); if (method_is_dynamic (method)) { address = (MonoDebugMethodAddress *)g_malloc0 (total_size); } else { address = (MonoDebugMethodAddress *)mono_mempool_alloc (info->mp, total_size); } address->code_start = jit->code_start; address->code_size = jit->code_size; memcpy (&address->data, oldptr, size); if (max_size > BUFSIZ) g_free (oldptr); g_hash_table_insert (info->method_hash, method, address); mono_debugger_unlock (); return address; } void mono_debug_remove_method (MonoMethod *method, MonoDomain *domain) { DebugMemoryManager *info; MonoDebugMethodAddress *address; if (!mono_debug_initialized) return; g_assert (method_is_dynamic (method)); info = get_mem_manager (method); mono_debugger_lock (); address = (MonoDebugMethodAddress *)g_hash_table_lookup (info->method_hash, method); if (address) g_free (address); g_hash_table_remove (info->method_hash, method); mono_debugger_unlock (); } /** * mono_debug_add_delegate_trampoline: */ void mono_debug_add_delegate_trampoline (gpointer code, int size) { } static guint32 read_leb128 (guint8 *ptr, guint8 **rptr) { guint32 result = 0, shift = 0; while (TRUE) { guint8 byte = *ptr++; result |= (byte & 0x7f) << shift; if ((byte & 0x80) == 0) break; shift += 7; } *rptr = ptr; return result; } static gint32 read_sleb128 (guint8 *ptr, guint8 **rptr) { gint32 result = 0; guint32 shift = 0; while (TRUE) { guint8 byte = *ptr++; result |= (byte & 0x7f) << shift; shift += 7; if (byte & 0x80) continue; if ((shift < 32) && (byte & 0x40)) result |= - (1 << shift); break; } *rptr = ptr; return result; } static void read_variable (MonoDebugVarInfo *var, guint8 *ptr, guint8 **rptr) { var->index = read_leb128 (ptr, &ptr); var->offset = read_sleb128 (ptr, &ptr); var->size = read_leb128 (ptr, &ptr); var->begin_scope = read_leb128 (ptr, &ptr); var->end_scope = read_leb128 (ptr, &ptr); READ_UNALIGNED (MonoType *, ptr, var->type); ptr += sizeof (gpointer); *rptr = ptr; } static void free_method_jit_info (MonoDebugMethodJitInfo *jit, gboolean stack) { if (!jit) return; g_free (jit->line_numbers); g_free (jit->this_var); g_free (jit->params); g_free (jit->locals); g_free (jit->gsharedvt_info_var); g_free (jit->gsharedvt_locals_var); if (!stack) g_free (jit); } void mono_debug_free_method_jit_info (MonoDebugMethodJitInfo *jit) { free_method_jit_info (jit, FALSE); } static MonoDebugMethodJitInfo * mono_debug_read_method (MonoDebugMethodAddress *address, MonoDebugMethodJitInfo *jit) { guint32 i; guint8 *ptr; memset (jit, 0, sizeof (*jit)); jit->code_start = address->code_start; jit->code_size = address->code_size; ptr = (guint8 *) &address->data; jit->prologue_end = read_leb128 (ptr, &ptr); jit->epilogue_begin = read_leb128 (ptr, &ptr); jit->num_line_numbers = read_leb128 (ptr, &ptr); jit->line_numbers = g_new0 (MonoDebugLineNumberEntry, jit->num_line_numbers); for (i = 0; i < jit->num_line_numbers; i++) { MonoDebugLineNumberEntry *lne = &jit->line_numbers [i]; lne->il_offset = read_sleb128 (ptr, &ptr); lne->native_offset = read_sleb128 (ptr, &ptr); } jit->has_var_info = read_leb128 (ptr, &ptr); if (jit->has_var_info) { if (*ptr++) { jit->this_var = g_new0 (MonoDebugVarInfo, 1); read_variable (jit->this_var, ptr, &ptr); } jit->num_params = read_leb128 (ptr, &ptr); jit->params = g_new0 (MonoDebugVarInfo, jit->num_params); for (i = 0; i < jit->num_params; i++) read_variable (&jit->params [i], ptr, &ptr); jit->num_locals = read_leb128 (ptr, &ptr); jit->locals = g_new0 (MonoDebugVarInfo, jit->num_locals); for (i = 0; i < jit->num_locals; i++) read_variable (&jit->locals [i], ptr, &ptr); if (*ptr++) { jit->gsharedvt_info_var = g_new0 (MonoDebugVarInfo, 1); jit->gsharedvt_locals_var = g_new0 (MonoDebugVarInfo, 1); read_variable (jit->gsharedvt_info_var, ptr, &ptr); read_variable (jit->gsharedvt_locals_var, ptr, &ptr); } } return jit; } static MonoDebugMethodJitInfo * find_method (MonoMethod *method, MonoDebugMethodJitInfo *jit) { DebugMemoryManager *info; MonoDebugMethodAddress *address; info = get_mem_manager (method); address = (MonoDebugMethodAddress *)g_hash_table_lookup (info->method_hash, method); if (!address) return NULL; return mono_debug_read_method (address, jit); } MonoDebugMethodJitInfo * mono_debug_find_method (MonoMethod *method, MonoDomain *domain) { if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; MonoDebugMethodJitInfo *res = g_new0 (MonoDebugMethodJitInfo, 1); mono_debugger_lock (); find_method (method, res); mono_debugger_unlock (); return res; } MonoDebugMethodAddressList * mono_debug_lookup_method_addresses (MonoMethod *method) { g_assert_not_reached (); return NULL; } static gint32 il_offset_from_address (MonoMethod *method, guint32 native_offset) { MonoDebugMethodJitInfo mem; int i; MonoDebugMethodJitInfo *jit = find_method (method, &mem); if (!jit || !jit->line_numbers) goto cleanup_and_fail; for (i = jit->num_line_numbers - 1; i >= 0; i--) { MonoDebugLineNumberEntry lne = jit->line_numbers [i]; if (lne.native_offset <= native_offset) { free_method_jit_info (jit, TRUE); return lne.il_offset; } } cleanup_and_fail: free_method_jit_info (jit, TRUE); return -1; } /** * mono_debug_il_offset_from_address: * * Compute the IL offset corresponding to \p native_offset inside the native * code of \p method in \p domain. */ gint32 mono_debug_il_offset_from_address (MonoMethod *method, MonoDomain *domain, guint32 native_offset) { gint32 res; mono_debugger_lock (); res = il_offset_from_address (method, native_offset); mono_debugger_unlock (); return res; } /** * mono_debug_lookup_source_location: * \param address Native offset within the \p method's machine code. * Lookup the source code corresponding to the machine instruction located at * native offset \p address within \p method. * The returned \c MonoDebugSourceLocation contains both file / line number * information and the corresponding IL offset. It must be freed by * \c mono_debug_free_source_location. */ MonoDebugSourceLocation * mono_debug_lookup_source_location (MonoMethod *method, guint32 address, MonoDomain *domain) { MonoDebugMethodInfo *minfo; MonoDebugSourceLocation *location; gint32 offset; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (!minfo->handle->ppdb && (!minfo->handle->symfile || !mono_debug_symfile_is_loaded (minfo->handle->symfile))) { mono_debugger_unlock (); return NULL; } offset = il_offset_from_address (method, address); if (offset < 0) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) location = mono_ppdb_lookup_location (minfo, offset); else location = mono_debug_symfile_lookup_location (minfo, offset); mono_debugger_unlock (); return location; } /** * mono_debug_lookup_source_location_by_il: * * Same as mono_debug_lookup_source_location but take an IL_OFFSET argument. */ MonoDebugSourceLocation * mono_debug_lookup_source_location_by_il (MonoMethod *method, guint32 il_offset, MonoDomain *domain) { MonoDebugMethodInfo *minfo; MonoDebugSourceLocation *location; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (!minfo->handle->ppdb && (!minfo->handle->symfile || !mono_debug_symfile_is_loaded (minfo->handle->symfile))) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) location = mono_ppdb_lookup_location (minfo, il_offset); else location = mono_debug_symfile_lookup_location (minfo, il_offset); mono_debugger_unlock (); return location; } MonoDebugSourceLocation * mono_debug_method_lookup_location (MonoDebugMethodInfo *minfo, int il_offset) { MonoImage* img = m_class_get_image (minfo->method->klass); if (img->has_updates) { int idx = mono_metadata_token_index (minfo->method->token); MonoDebugInformationEnc *mdie = (MonoDebugInformationEnc *) mono_metadata_update_get_updated_method_ppdb (img, idx); if (mdie != NULL) { MonoDebugSourceLocation * ret = mono_ppdb_lookup_location_enc (mdie->ppdb_file, mdie->idx, il_offset); if (ret) return ret; } } MonoDebugSourceLocation *location; mono_debugger_lock (); if (minfo->handle->ppdb) location = mono_ppdb_lookup_location (minfo, il_offset); else location = mono_debug_symfile_lookup_location (minfo, il_offset); mono_debugger_unlock (); return location; } /* * mono_debug_lookup_locals: * * Return information about the local variables of MINFO. * The result should be freed using mono_debug_free_locals (). */ MonoDebugLocalsInfo* mono_debug_lookup_locals (MonoMethod *method) { MonoDebugMethodInfo *minfo; MonoDebugLocalsInfo *res; MonoImage* img = m_class_get_image (method->klass); if (img->has_updates) { int idx = mono_metadata_token_index (method->token); MonoDebugInformationEnc *mdie = (MonoDebugInformationEnc *) mono_metadata_update_get_updated_method_ppdb (img, idx); if (mdie != NULL) { res = mono_ppdb_lookup_locals_enc (mdie->ppdb_file->image, mdie->idx); if (res != NULL) return res; } } if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) { res = mono_ppdb_lookup_locals (minfo); } else { if (!minfo->handle->symfile || !mono_debug_symfile_is_loaded (minfo->handle->symfile)) res = NULL; else res = mono_debug_symfile_lookup_locals (minfo); } mono_debugger_unlock (); return res; } /* * mono_debug_free_locals: * * Free all the data allocated by mono_debug_lookup_locals (). */ void mono_debug_free_locals (MonoDebugLocalsInfo *info) { int i; for (i = 0; i < info->num_locals; ++i) g_free (info->locals [i].name); g_free (info->locals); g_free (info->code_blocks); g_free (info); } /* * mono_debug_lookup_method_async_debug_info: * * Return information about the async stepping information of method. * The result should be freed using mono_debug_free_async_debug_info (). */ MonoDebugMethodAsyncInfo* mono_debug_lookup_method_async_debug_info (MonoMethod *method) { MonoDebugMethodInfo *minfo; MonoDebugMethodAsyncInfo *res = NULL; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) res = mono_ppdb_lookup_method_async_debug_info (minfo); mono_debugger_unlock (); return res; } /* * mono_debug_free_method_async_debug_info: * * Free all the data allocated by mono_debug_lookup_method_async_debug_info (). */ void mono_debug_free_method_async_debug_info (MonoDebugMethodAsyncInfo *info) { if (info->num_awaits) { g_free (info->yield_offsets); g_free (info->resume_offsets); g_free (info->move_next_method_token); } g_free (info); } /** * mono_debug_free_source_location: * \param location A \c MonoDebugSourceLocation * Frees the \p location. */ void mono_debug_free_source_location (MonoDebugSourceLocation *location) { if (location) { g_free (location->source_file); g_free (location); } } static int (*get_seq_point) (MonoMethod *method, gint32 native_offset); void mono_install_get_seq_point (MonoGetSeqPointFunc func) { get_seq_point = func; } /** * mono_debug_print_stack_frame: * \param native_offset Native offset within the \p method's machine code. * Conventient wrapper around \c mono_debug_lookup_source_location which can be * used if you only want to use the location to print a stack frame. */ gchar * mono_debug_print_stack_frame (MonoMethod *method, guint32 native_offset, MonoDomain *domain) { MonoDebugSourceLocation *location; gchar *fname, *ptr, *res; int offset; fname = mono_method_full_name (method, TRUE); for (ptr = fname; *ptr; ptr++) { if (*ptr == ':') *ptr = '.'; } location = mono_debug_lookup_source_location (method, native_offset, NULL); if (!location) { if (mono_debug_initialized) { mono_debugger_lock (); offset = il_offset_from_address (method, native_offset); mono_debugger_unlock (); } else { offset = -1; } if (offset < 0 && get_seq_point) offset = get_seq_point (method, native_offset); if (offset < 0) res = g_strdup_printf ("at %s <0x%05x>", fname, native_offset); else { char *mvid = mono_guid_to_string_minimal ((uint8_t*)m_class_get_image (method->klass)->heap_guid.data); char *aotid = mono_runtime_get_aotid (); if (aotid) res = g_strdup_printf ("at %s [0x%05x] in <%s#%s>:0" , fname, offset, mvid, aotid); else res = g_strdup_printf ("at %s [0x%05x] in <%s>:0" , fname, offset, mvid); g_free (aotid); g_free (mvid); } g_free (fname); return res; } res = g_strdup_printf ("at %s [0x%05x] in %s:%d", fname, location->il_offset, location->source_file, location->row); g_free (fname); mono_debug_free_source_location (location); return res; } void mono_set_is_debugger_attached (gboolean attached) { is_attached = attached; } gboolean mono_is_debugger_attached (void) { return is_attached; } /* * Bundles */ typedef struct _BundledSymfile BundledSymfile; struct _BundledSymfile { BundledSymfile *next; const char *aname; const mono_byte *raw_contents; int size; }; static BundledSymfile *bundled_symfiles = NULL; /** * mono_register_symfile_for_assembly: */ void mono_register_symfile_for_assembly (const char *assembly_name, const mono_byte *raw_contents, int size) { BundledSymfile *bsymfile; bsymfile = g_new0 (BundledSymfile, 1); bsymfile->aname = assembly_name; bsymfile->raw_contents = raw_contents; bsymfile->size = size; bsymfile->next = bundled_symfiles; bundled_symfiles = bsymfile; } static MonoDebugHandle * open_symfile_from_bundle (MonoImage *image) { BundledSymfile *bsymfile; for (bsymfile = bundled_symfiles; bsymfile; bsymfile = bsymfile->next) { if (strcmp (bsymfile->aname, image->module_name)) continue; return mono_debug_open_image (image, bsymfile->raw_contents, bsymfile->size); } return NULL; } void mono_debugger_lock (void) { g_assert (mono_debug_initialized); mono_os_mutex_lock (&debugger_lock_mutex); } void mono_debugger_unlock (void) { g_assert (mono_debug_initialized); mono_os_mutex_unlock (&debugger_lock_mutex); } /** * mono_debug_enabled: * * Returns true is debug information is enabled. This doesn't relate if a debugger is present or not. */ mono_bool mono_debug_enabled (void) { return mono_debug_format != MONO_DEBUG_FORMAT_NONE; } void mono_debug_get_seq_points (MonoDebugMethodInfo *minfo, char **source_file, GPtrArray **source_file_list, int **source_files, MonoSymSeqPoint **seq_points, int *n_seq_points) { MonoImage* img = m_class_get_image (minfo->method->klass); if (img->has_updates) { int idx = mono_metadata_token_index (minfo->method->token); MonoDebugInformationEnc *mdie = (MonoDebugInformationEnc *) mono_metadata_update_get_updated_method_ppdb (img, idx); if (mdie != NULL) { if (mono_ppdb_get_seq_points_enc (minfo, mdie->ppdb_file, mdie->idx, source_file, source_file_list, source_files, seq_points, n_seq_points)) return; } } if (minfo->handle->ppdb) mono_ppdb_get_seq_points (minfo, source_file, source_file_list, source_files, seq_points, n_seq_points); else mono_debug_symfile_get_seq_points (minfo, source_file, source_file_list, source_files, seq_points, n_seq_points); } char* mono_debug_image_get_sourcelink (MonoImage *image) { MonoDebugHandle *handle = mono_debug_get_handle (image); if (handle && handle->ppdb) return mono_ppdb_get_sourcelink (handle); else return NULL; }
/** * \file * * Author: * Mono Project (http://www.mono-project.com) * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * Copyright 2011 Xamarin Inc (http://www.xamarin.com) * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <config.h> #include <mono/metadata/assembly.h> #include <mono/metadata/assembly-internals.h> #include <mono/metadata/tabledefs.h> #include <mono/metadata/tokentype.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/mono-debug.h> #include <mono/metadata/debug-internals.h> #include <mono/metadata/mono-endian.h> #include <mono/metadata/gc-internals.h> #include <mono/metadata/mempool.h> #include <mono/metadata/debug-mono-symfile.h> #include <mono/metadata/debug-mono-ppdb.h> #include <mono/metadata/exception-internals.h> #include <mono/metadata/runtime.h> #include <mono/metadata/metadata-update.h> #include <string.h> #if NO_UNALIGNED_ACCESS #define WRITE_UNALIGNED(type, addr, val) \ memcpy(addr, &val, sizeof(type)) #define READ_UNALIGNED(type, addr, val) \ memcpy(&val, addr, sizeof(type)) #else #define WRITE_UNALIGNED(type, addr, val) \ (*(type *)(addr) = (val)) #define READ_UNALIGNED(type, addr, val) \ val = (*(type *)(addr)) #endif /* Many functions have 'domain' parameters, those are ignored */ /* * This contains per-memory manager info. */ typedef struct { MonoMemPool *mp; /* Maps MonoMethod->MonoDebugMethodAddress */ GHashTable *method_hash; } DebugMemoryManager; /* This contains JIT debugging information about a method in serialized format */ struct _MonoDebugMethodAddress { const guint8 *code_start; guint32 code_size; guint8 data [MONO_ZERO_LEN_ARRAY]; }; static MonoDebugFormat mono_debug_format = MONO_DEBUG_FORMAT_NONE; static gboolean mono_debug_initialized = FALSE; /* Maps MonoImage -> MonoMonoDebugHandle */ static GHashTable *mono_debug_handles; static mono_mutex_t debugger_lock_mutex; static gboolean is_attached = FALSE; static MonoDebugHandle *mono_debug_open_image (MonoImage *image, const guint8 *raw_contents, int size); static MonoDebugHandle *mono_debug_get_image (MonoImage *image); static void add_assembly (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer user_data, MonoError *error); static MonoDebugHandle *open_symfile_from_bundle (MonoImage *image); static DebugMemoryManager* get_mem_manager (MonoMethod *method) { MonoMemoryManager *mem_manager = m_method_get_mem_manager (method); if (!mono_debug_initialized) return NULL; if (!mem_manager->debug_info) { DebugMemoryManager *info; info = g_new0 (DebugMemoryManager, 1); info->mp = mono_mempool_new (); info->method_hash = g_hash_table_new (NULL, NULL); mono_memory_barrier (); mono_debugger_lock (); if (!mem_manager->debug_info) mem_manager->debug_info = info; // FIXME: Free otherwise mono_debugger_unlock (); } return (DebugMemoryManager*)mem_manager->debug_info; } /* * mono_mem_manager_free_debug_info: * * Free the information maintained by this module for MEM_MANAGER. */ void mono_mem_manager_free_debug_info (MonoMemoryManager *memory_manager) { DebugMemoryManager *info = (DebugMemoryManager*)memory_manager->debug_info; if (!info) return; mono_mempool_destroy (info->mp); g_hash_table_destroy (info->method_hash); g_free (info); } static void free_debug_handle (MonoDebugHandle *handle) { if (handle->ppdb) mono_ppdb_close (handle->ppdb); if (handle->symfile) mono_debug_close_mono_symbol_file (handle->symfile); /* decrease the refcount added with mono_image_addref () */ mono_image_close (handle->image); g_free (handle); } /* * Initialize debugging support. * * This method must be called after loading corlib, * but before opening the application's main assembly because we need to set some * callbacks here. */ void mono_debug_init (MonoDebugFormat format) { g_assert (!mono_debug_initialized); if (format == MONO_DEBUG_FORMAT_DEBUGGER) g_error ("The mdb debugger is no longer supported."); mono_debug_initialized = TRUE; mono_debug_format = format; mono_os_mutex_init_recursive (&debugger_lock_mutex); mono_debugger_lock (); mono_debug_handles = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) free_debug_handle); mono_install_assembly_load_hook_v2 (add_assembly, NULL, FALSE); mono_debugger_unlock (); } void mono_debug_open_image_from_memory (MonoImage *image, const guint8 *raw_contents, int size) { MONO_ENTER_GC_UNSAFE; if (!mono_debug_initialized) goto leave; mono_debug_open_image (image, raw_contents, size); leave: MONO_EXIT_GC_UNSAFE; } void mono_debug_cleanup (void) { } /** * mono_debug_domain_create: */ void mono_debug_domain_create (MonoDomain *domain) { g_assert_not_reached (); } void mono_debug_domain_unload (MonoDomain *domain) { g_assert_not_reached (); } /* * LOCKING: Assumes the debug lock is held. */ static MonoDebugHandle * mono_debug_get_image (MonoImage *image) { return (MonoDebugHandle *)g_hash_table_lookup (mono_debug_handles, image); } /** * mono_debug_close_image: */ void mono_debug_close_image (MonoImage *image) { MonoDebugHandle *handle; if (!mono_debug_initialized) return; mono_debugger_lock (); handle = mono_debug_get_image (image); if (!handle) { mono_debugger_unlock (); return; } g_hash_table_remove (mono_debug_handles, image); mono_debugger_unlock (); } MonoDebugHandle * mono_debug_get_handle (MonoImage *image) { return mono_debug_open_image (image, NULL, 0); } static MonoDebugHandle * mono_debug_open_image (MonoImage *image, const guint8 *raw_contents, int size) { MonoDebugHandle *handle; if (mono_image_is_dynamic (image)) return NULL; mono_debugger_lock (); handle = mono_debug_get_image (image); if (handle != NULL) { mono_debugger_unlock (); return handle; } handle = g_new0 (MonoDebugHandle, 1); handle->image = image; mono_image_addref (image); /* Try a ppdb file first */ handle->ppdb = mono_ppdb_load_file (handle->image, raw_contents, size); if (!handle->ppdb) handle->symfile = mono_debug_open_mono_symbols (handle, raw_contents, size, FALSE); g_hash_table_insert (mono_debug_handles, image, handle); mono_debugger_unlock (); return handle; } static void add_assembly (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer user_data, MonoError *error) { MonoDebugHandle *handle; MonoImage *image; mono_debugger_lock (); image = mono_assembly_get_image_internal (assembly); handle = open_symfile_from_bundle (image); if (!handle) mono_debug_open_image (image, NULL, 0); mono_debugger_unlock (); } struct LookupMethodData { MonoDebugMethodInfo *minfo; MonoMethod *method; }; static void lookup_method_func (gpointer key, gpointer value, gpointer user_data) { MonoDebugHandle *handle = (MonoDebugHandle *) value; struct LookupMethodData *data = (struct LookupMethodData *) user_data; if (data->minfo) return; if (handle->ppdb) data->minfo = mono_ppdb_lookup_method (handle, data->method); else if (handle->symfile) data->minfo = mono_debug_symfile_lookup_method (handle, data->method); } static MonoDebugMethodInfo * lookup_method (MonoMethod *method) { struct LookupMethodData data; data.minfo = NULL; data.method = method; if (!mono_debug_handles) return NULL; g_hash_table_foreach (mono_debug_handles, lookup_method_func, &data); return data.minfo; } /** * mono_debug_lookup_method: * * Lookup symbol file information for the method \p method. The returned * \c MonoDebugMethodInfo is a private structure, but it can be passed to * \c mono_debug_symfile_lookup_location. */ MonoDebugMethodInfo * mono_debug_lookup_method (MonoMethod *method) { MonoDebugMethodInfo *minfo; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); mono_debugger_unlock (); return minfo; } typedef struct { gboolean found; MonoImage *image; } LookupImageData; static void lookup_image_func (gpointer key, gpointer value, gpointer user_data) { MonoDebugHandle *handle = (MonoDebugHandle *) value; LookupImageData *data = (LookupImageData *) user_data; if (data->found) return; if (handle->image == data->image && (handle->symfile || handle->ppdb)) data->found = TRUE; } gboolean mono_debug_image_has_debug_info (MonoImage *image) { LookupImageData data; if (!mono_debug_handles) return FALSE; memset (&data, 0, sizeof (data)); data.image = image; mono_debugger_lock (); g_hash_table_foreach (mono_debug_handles, lookup_image_func, &data); mono_debugger_unlock (); return data.found; } static void write_leb128 (guint32 value, guint8 *ptr, guint8 **rptr) { do { guint8 byte = value & 0x7f; value >>= 7; if (value) byte |= 0x80; *ptr++ = byte; } while (value); *rptr = ptr; } static void write_sleb128 (gint32 value, guint8 *ptr, guint8 **rptr) { gboolean more = 1; while (more) { guint8 byte = value & 0x7f; value >>= 7; if (((value == 0) && ((byte & 0x40) == 0)) || ((value == -1) && (byte & 0x40))) more = 0; else byte |= 0x80; *ptr++ = byte; } *rptr = ptr; } /* leb128 uses a maximum of 5 bytes for a 32 bit value */ #define LEB128_MAX_SIZE 5 #define WRITE_VARIABLE_MAX_SIZE (5 * LEB128_MAX_SIZE + sizeof (gpointer)) static void write_variable (MonoDebugVarInfo *var, guint8 *ptr, guint8 **rptr) { write_leb128 (var->index, ptr, &ptr); write_sleb128 (var->offset, ptr, &ptr); write_leb128 (var->size, ptr, &ptr); write_leb128 (var->begin_scope, ptr, &ptr); write_leb128 (var->end_scope, ptr, &ptr); WRITE_UNALIGNED (gpointer, ptr, var->type); ptr += sizeof (gpointer); *rptr = ptr; } /** * mono_debug_add_method: */ MonoDebugMethodAddress * mono_debug_add_method (MonoMethod *method, MonoDebugMethodJitInfo *jit, MonoDomain *domain) { DebugMemoryManager *info; MonoDebugMethodAddress *address; guint8 buffer [BUFSIZ]; guint8 *ptr, *oldptr; guint32 i, size, total_size, max_size; info = get_mem_manager (method); max_size = (5 * LEB128_MAX_SIZE) + 1 + (2 * LEB128_MAX_SIZE * jit->num_line_numbers); if (jit->has_var_info) { /* this */ max_size += 1; if (jit->this_var) max_size += WRITE_VARIABLE_MAX_SIZE; /* params */ max_size += LEB128_MAX_SIZE; max_size += jit->num_params * WRITE_VARIABLE_MAX_SIZE; /* locals */ max_size += LEB128_MAX_SIZE; max_size += jit->num_locals * WRITE_VARIABLE_MAX_SIZE; /* gsharedvt */ max_size += 1; if (jit->gsharedvt_info_var) max_size += 2 * WRITE_VARIABLE_MAX_SIZE; } if (max_size > BUFSIZ) ptr = oldptr = (guint8 *)g_malloc (max_size); else ptr = oldptr = buffer; write_leb128 (jit->prologue_end, ptr, &ptr); write_leb128 (jit->epilogue_begin, ptr, &ptr); write_leb128 (jit->num_line_numbers, ptr, &ptr); for (i = 0; i < jit->num_line_numbers; i++) { MonoDebugLineNumberEntry *lne = &jit->line_numbers [i]; write_sleb128 (lne->il_offset, ptr, &ptr); write_sleb128 (lne->native_offset, ptr, &ptr); } write_leb128 (jit->has_var_info, ptr, &ptr); if (jit->has_var_info) { *ptr++ = jit->this_var ? 1 : 0; if (jit->this_var) write_variable (jit->this_var, ptr, &ptr); write_leb128 (jit->num_params, ptr, &ptr); for (i = 0; i < jit->num_params; i++) write_variable (&jit->params [i], ptr, &ptr); write_leb128 (jit->num_locals, ptr, &ptr); for (i = 0; i < jit->num_locals; i++) write_variable (&jit->locals [i], ptr, &ptr); *ptr++ = jit->gsharedvt_info_var ? 1 : 0; if (jit->gsharedvt_info_var) { write_variable (jit->gsharedvt_info_var, ptr, &ptr); write_variable (jit->gsharedvt_locals_var, ptr, &ptr); } } size = ptr - oldptr; g_assert (size < max_size); total_size = size + sizeof (MonoDebugMethodAddress); mono_debugger_lock (); if (method_is_dynamic (method)) { address = (MonoDebugMethodAddress *)g_malloc0 (total_size); } else { address = (MonoDebugMethodAddress *)mono_mempool_alloc (info->mp, total_size); } address->code_start = jit->code_start; address->code_size = jit->code_size; memcpy (&address->data, oldptr, size); if (max_size > BUFSIZ) g_free (oldptr); g_hash_table_insert (info->method_hash, method, address); mono_debugger_unlock (); return address; } void mono_debug_remove_method (MonoMethod *method, MonoDomain *domain) { DebugMemoryManager *info; MonoDebugMethodAddress *address; if (!mono_debug_initialized) return; g_assert (method_is_dynamic (method)); info = get_mem_manager (method); mono_debugger_lock (); address = (MonoDebugMethodAddress *)g_hash_table_lookup (info->method_hash, method); if (address) g_free (address); g_hash_table_remove (info->method_hash, method); mono_debugger_unlock (); } /** * mono_debug_add_delegate_trampoline: */ void mono_debug_add_delegate_trampoline (gpointer code, int size) { } static guint32 read_leb128 (guint8 *ptr, guint8 **rptr) { guint32 result = 0, shift = 0; while (TRUE) { guint8 byte = *ptr++; result |= (byte & 0x7f) << shift; if ((byte & 0x80) == 0) break; shift += 7; } *rptr = ptr; return result; } static gint32 read_sleb128 (guint8 *ptr, guint8 **rptr) { gint32 result = 0; guint32 shift = 0; while (TRUE) { guint8 byte = *ptr++; result |= (byte & 0x7f) << shift; shift += 7; if (byte & 0x80) continue; if ((shift < 32) && (byte & 0x40)) result |= - (1 << shift); break; } *rptr = ptr; return result; } static void read_variable (MonoDebugVarInfo *var, guint8 *ptr, guint8 **rptr) { var->index = read_leb128 (ptr, &ptr); var->offset = read_sleb128 (ptr, &ptr); var->size = read_leb128 (ptr, &ptr); var->begin_scope = read_leb128 (ptr, &ptr); var->end_scope = read_leb128 (ptr, &ptr); READ_UNALIGNED (MonoType *, ptr, var->type); ptr += sizeof (gpointer); *rptr = ptr; } static void free_method_jit_info (MonoDebugMethodJitInfo *jit, gboolean stack) { if (!jit) return; g_free (jit->line_numbers); g_free (jit->this_var); g_free (jit->params); g_free (jit->locals); g_free (jit->gsharedvt_info_var); g_free (jit->gsharedvt_locals_var); if (!stack) g_free (jit); } void mono_debug_free_method_jit_info (MonoDebugMethodJitInfo *jit) { free_method_jit_info (jit, FALSE); } static MonoDebugMethodJitInfo * mono_debug_read_method (MonoDebugMethodAddress *address, MonoDebugMethodJitInfo *jit) { guint32 i; guint8 *ptr; memset (jit, 0, sizeof (*jit)); jit->code_start = address->code_start; jit->code_size = address->code_size; ptr = (guint8 *) &address->data; jit->prologue_end = read_leb128 (ptr, &ptr); jit->epilogue_begin = read_leb128 (ptr, &ptr); jit->num_line_numbers = read_leb128 (ptr, &ptr); jit->line_numbers = g_new0 (MonoDebugLineNumberEntry, jit->num_line_numbers); for (i = 0; i < jit->num_line_numbers; i++) { MonoDebugLineNumberEntry *lne = &jit->line_numbers [i]; lne->il_offset = read_sleb128 (ptr, &ptr); lne->native_offset = read_sleb128 (ptr, &ptr); } jit->has_var_info = read_leb128 (ptr, &ptr); if (jit->has_var_info) { if (*ptr++) { jit->this_var = g_new0 (MonoDebugVarInfo, 1); read_variable (jit->this_var, ptr, &ptr); } jit->num_params = read_leb128 (ptr, &ptr); jit->params = g_new0 (MonoDebugVarInfo, jit->num_params); for (i = 0; i < jit->num_params; i++) read_variable (&jit->params [i], ptr, &ptr); jit->num_locals = read_leb128 (ptr, &ptr); jit->locals = g_new0 (MonoDebugVarInfo, jit->num_locals); for (i = 0; i < jit->num_locals; i++) read_variable (&jit->locals [i], ptr, &ptr); if (*ptr++) { jit->gsharedvt_info_var = g_new0 (MonoDebugVarInfo, 1); jit->gsharedvt_locals_var = g_new0 (MonoDebugVarInfo, 1); read_variable (jit->gsharedvt_info_var, ptr, &ptr); read_variable (jit->gsharedvt_locals_var, ptr, &ptr); } } return jit; } static MonoDebugMethodJitInfo * find_method (MonoMethod *method, MonoDebugMethodJitInfo *jit) { DebugMemoryManager *info; MonoDebugMethodAddress *address; info = get_mem_manager (method); address = (MonoDebugMethodAddress *)g_hash_table_lookup (info->method_hash, method); if (!address) return NULL; return mono_debug_read_method (address, jit); } MonoDebugMethodJitInfo * mono_debug_find_method (MonoMethod *method, MonoDomain *domain) { if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; MonoDebugMethodJitInfo *res = g_new0 (MonoDebugMethodJitInfo, 1); mono_debugger_lock (); find_method (method, res); mono_debugger_unlock (); return res; } MonoDebugMethodAddressList * mono_debug_lookup_method_addresses (MonoMethod *method) { g_assert_not_reached (); return NULL; } static gint32 il_offset_from_address (MonoMethod *method, guint32 native_offset) { MonoDebugMethodJitInfo mem; int i; MonoDebugMethodJitInfo *jit = find_method (method, &mem); if (!jit || !jit->line_numbers) goto cleanup_and_fail; for (i = jit->num_line_numbers - 1; i >= 0; i--) { MonoDebugLineNumberEntry lne = jit->line_numbers [i]; if (lne.native_offset <= native_offset) { free_method_jit_info (jit, TRUE); return lne.il_offset; } } cleanup_and_fail: free_method_jit_info (jit, TRUE); return -1; } /** * mono_debug_il_offset_from_address: * * Compute the IL offset corresponding to \p native_offset inside the native * code of \p method in \p domain. */ gint32 mono_debug_il_offset_from_address (MonoMethod *method, MonoDomain *domain, guint32 native_offset) { gint32 res; mono_debugger_lock (); res = il_offset_from_address (method, native_offset); mono_debugger_unlock (); return res; } /** * mono_debug_lookup_source_location: * \param address Native offset within the \p method's machine code. * Lookup the source code corresponding to the machine instruction located at * native offset \p address within \p method. * The returned \c MonoDebugSourceLocation contains both file / line number * information and the corresponding IL offset. It must be freed by * \c mono_debug_free_source_location. */ MonoDebugSourceLocation * mono_debug_lookup_source_location (MonoMethod *method, guint32 address, MonoDomain *domain) { MonoDebugMethodInfo *minfo; MonoDebugSourceLocation *location; gint32 offset; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (!minfo->handle->ppdb && (!minfo->handle->symfile || !mono_debug_symfile_is_loaded (minfo->handle->symfile))) { mono_debugger_unlock (); return NULL; } offset = il_offset_from_address (method, address); if (offset < 0) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) location = mono_ppdb_lookup_location (minfo, offset); else location = mono_debug_symfile_lookup_location (minfo, offset); mono_debugger_unlock (); return location; } /** * mono_debug_lookup_source_location_by_il: * * Same as mono_debug_lookup_source_location but take an IL_OFFSET argument. */ MonoDebugSourceLocation * mono_debug_lookup_source_location_by_il (MonoMethod *method, guint32 il_offset, MonoDomain *domain) { MonoDebugMethodInfo *minfo; MonoDebugSourceLocation *location; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (!minfo->handle->ppdb && (!minfo->handle->symfile || !mono_debug_symfile_is_loaded (minfo->handle->symfile))) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) location = mono_ppdb_lookup_location (minfo, il_offset); else location = mono_debug_symfile_lookup_location (minfo, il_offset); mono_debugger_unlock (); return location; } MonoDebugSourceLocation * mono_debug_method_lookup_location (MonoDebugMethodInfo *minfo, int il_offset) { MonoImage* img = m_class_get_image (minfo->method->klass); if (img->has_updates) { int idx = mono_metadata_token_index (minfo->method->token); MonoDebugInformationEnc *mdie = (MonoDebugInformationEnc *) mono_metadata_update_get_updated_method_ppdb (img, idx); if (mdie != NULL) { MonoDebugSourceLocation * ret = mono_ppdb_lookup_location_enc (mdie->ppdb_file, mdie->idx, il_offset); if (ret) return ret; } else { gboolean added_method = idx >= table_info_get_rows (&img->tables[MONO_TABLE_METHOD]); if (added_method) return NULL; } } MonoDebugSourceLocation *location; mono_debugger_lock (); if (minfo->handle->ppdb) location = mono_ppdb_lookup_location (minfo, il_offset); else location = mono_debug_symfile_lookup_location (minfo, il_offset); mono_debugger_unlock (); return location; } /* * mono_debug_lookup_locals: * * Return information about the local variables of MINFO. * The result should be freed using mono_debug_free_locals (). */ MonoDebugLocalsInfo* mono_debug_lookup_locals (MonoMethod *method) { MonoDebugMethodInfo *minfo; MonoDebugLocalsInfo *res; MonoImage* img = m_class_get_image (method->klass); if (img->has_updates) { int idx = mono_metadata_token_index (method->token); MonoDebugInformationEnc *mdie = (MonoDebugInformationEnc *) mono_metadata_update_get_updated_method_ppdb (img, idx); if (mdie != NULL) { res = mono_ppdb_lookup_locals_enc (mdie->ppdb_file->image, mdie->idx); if (res != NULL) return res; } } if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) { res = mono_ppdb_lookup_locals (minfo); } else { if (!minfo->handle->symfile || !mono_debug_symfile_is_loaded (minfo->handle->symfile)) res = NULL; else res = mono_debug_symfile_lookup_locals (minfo); } mono_debugger_unlock (); return res; } /* * mono_debug_free_locals: * * Free all the data allocated by mono_debug_lookup_locals (). */ void mono_debug_free_locals (MonoDebugLocalsInfo *info) { int i; for (i = 0; i < info->num_locals; ++i) g_free (info->locals [i].name); g_free (info->locals); g_free (info->code_blocks); g_free (info); } /* * mono_debug_lookup_method_async_debug_info: * * Return information about the async stepping information of method. * The result should be freed using mono_debug_free_async_debug_info (). */ MonoDebugMethodAsyncInfo* mono_debug_lookup_method_async_debug_info (MonoMethod *method) { MonoDebugMethodInfo *minfo; MonoDebugMethodAsyncInfo *res = NULL; if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) return NULL; mono_debugger_lock (); minfo = lookup_method (method); if (!minfo || !minfo->handle) { mono_debugger_unlock (); return NULL; } if (minfo->handle->ppdb) res = mono_ppdb_lookup_method_async_debug_info (minfo); mono_debugger_unlock (); return res; } /* * mono_debug_free_method_async_debug_info: * * Free all the data allocated by mono_debug_lookup_method_async_debug_info (). */ void mono_debug_free_method_async_debug_info (MonoDebugMethodAsyncInfo *info) { if (info->num_awaits) { g_free (info->yield_offsets); g_free (info->resume_offsets); g_free (info->move_next_method_token); } g_free (info); } /** * mono_debug_free_source_location: * \param location A \c MonoDebugSourceLocation * Frees the \p location. */ void mono_debug_free_source_location (MonoDebugSourceLocation *location) { if (location) { g_free (location->source_file); g_free (location); } } static int (*get_seq_point) (MonoMethod *method, gint32 native_offset); void mono_install_get_seq_point (MonoGetSeqPointFunc func) { get_seq_point = func; } /** * mono_debug_print_stack_frame: * \param native_offset Native offset within the \p method's machine code. * Conventient wrapper around \c mono_debug_lookup_source_location which can be * used if you only want to use the location to print a stack frame. */ gchar * mono_debug_print_stack_frame (MonoMethod *method, guint32 native_offset, MonoDomain *domain) { MonoDebugSourceLocation *location; gchar *fname, *ptr, *res; int offset; fname = mono_method_full_name (method, TRUE); for (ptr = fname; *ptr; ptr++) { if (*ptr == ':') *ptr = '.'; } location = mono_debug_lookup_source_location (method, native_offset, NULL); if (!location) { if (mono_debug_initialized) { mono_debugger_lock (); offset = il_offset_from_address (method, native_offset); mono_debugger_unlock (); } else { offset = -1; } if (offset < 0 && get_seq_point) offset = get_seq_point (method, native_offset); if (offset < 0) res = g_strdup_printf ("at %s <0x%05x>", fname, native_offset); else { char *mvid = mono_guid_to_string_minimal ((uint8_t*)m_class_get_image (method->klass)->heap_guid.data); char *aotid = mono_runtime_get_aotid (); if (aotid) res = g_strdup_printf ("at %s [0x%05x] in <%s#%s>:0" , fname, offset, mvid, aotid); else res = g_strdup_printf ("at %s [0x%05x] in <%s>:0" , fname, offset, mvid); g_free (aotid); g_free (mvid); } g_free (fname); return res; } res = g_strdup_printf ("at %s [0x%05x] in %s:%d", fname, location->il_offset, location->source_file, location->row); g_free (fname); mono_debug_free_source_location (location); return res; } void mono_set_is_debugger_attached (gboolean attached) { is_attached = attached; } gboolean mono_is_debugger_attached (void) { return is_attached; } /* * Bundles */ typedef struct _BundledSymfile BundledSymfile; struct _BundledSymfile { BundledSymfile *next; const char *aname; const mono_byte *raw_contents; int size; }; static BundledSymfile *bundled_symfiles = NULL; /** * mono_register_symfile_for_assembly: */ void mono_register_symfile_for_assembly (const char *assembly_name, const mono_byte *raw_contents, int size) { BundledSymfile *bsymfile; bsymfile = g_new0 (BundledSymfile, 1); bsymfile->aname = assembly_name; bsymfile->raw_contents = raw_contents; bsymfile->size = size; bsymfile->next = bundled_symfiles; bundled_symfiles = bsymfile; } static MonoDebugHandle * open_symfile_from_bundle (MonoImage *image) { BundledSymfile *bsymfile; for (bsymfile = bundled_symfiles; bsymfile; bsymfile = bsymfile->next) { if (strcmp (bsymfile->aname, image->module_name)) continue; return mono_debug_open_image (image, bsymfile->raw_contents, bsymfile->size); } return NULL; } void mono_debugger_lock (void) { g_assert (mono_debug_initialized); mono_os_mutex_lock (&debugger_lock_mutex); } void mono_debugger_unlock (void) { g_assert (mono_debug_initialized); mono_os_mutex_unlock (&debugger_lock_mutex); } /** * mono_debug_enabled: * * Returns true is debug information is enabled. This doesn't relate if a debugger is present or not. */ mono_bool mono_debug_enabled (void) { return mono_debug_format != MONO_DEBUG_FORMAT_NONE; } void mono_debug_get_seq_points (MonoDebugMethodInfo *minfo, char **source_file, GPtrArray **source_file_list, int **source_files, MonoSymSeqPoint **seq_points, int *n_seq_points) { MonoImage* img = m_class_get_image (minfo->method->klass); if (img->has_updates) { int idx = mono_metadata_token_index (minfo->method->token); MonoDebugInformationEnc *mdie = (MonoDebugInformationEnc *) mono_metadata_update_get_updated_method_ppdb (img, idx); if (mdie != NULL) { if (mono_ppdb_get_seq_points_enc (minfo, mdie->ppdb_file, mdie->idx, source_file, source_file_list, source_files, seq_points, n_seq_points)) return; } /* * dotnet watch sometimes sends us updated with PPDB deltas, but the baseline * project has debug info (and we use it for seq points?). In tht case, just say * the added method has no sequence points. N.B. intentionally, comparing idx to * the baseline tables. For methods that already existed, use their old seq points. */ if (idx >= table_info_get_rows (&img->tables[MONO_TABLE_METHOD])) { if (source_file) *source_file = NULL; if (source_file_list) *source_file_list = NULL; if (source_files) *source_files = NULL; if (seq_points) *seq_points = NULL; if (n_seq_points) *n_seq_points = 0; return; } } if (minfo->handle->ppdb) mono_ppdb_get_seq_points (minfo, source_file, source_file_list, source_files, seq_points, n_seq_points); else mono_debug_symfile_get_seq_points (minfo, source_file, source_file_list, source_files, seq_points, n_seq_points); } char* mono_debug_image_get_sourcelink (MonoImage *image) { MonoDebugHandle *handle = mono_debug_get_handle (image); if (handle && handle->ppdb) return mono_ppdb_get_sourcelink (handle); else return NULL; }
1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Runtime.Numerics/tests/BigInteger/IsZero.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Numerics.Tests { public class IsZeroTest { private static int s_seed = 0; [Fact] public static void RunIsZeroTests() { Random random = new Random(s_seed); //Just basic tests // Zero VerifyIsZero(BigInteger.Zero, true); // Negative One VerifyIsZero(BigInteger.MinusOne, false); // One VerifyIsZero(BigInteger.One, false); // -Int32.MaxValue VerifyIsZero((BigInteger)int.MaxValue * -1, false); // Int32.MaxValue VerifyIsZero((BigInteger)int.MaxValue, false); // int32.MaxValue + 1 VerifyIsZero((BigInteger)int.MaxValue + 1, false); // UInt32.MaxValue VerifyIsZero((BigInteger)uint.MaxValue, false); // Uint32.MaxValue + 1 VerifyIsZero((BigInteger)uint.MaxValue + 1, false); } private static void VerifyIsZero(BigInteger bigInt, bool expectedAnswer) { Assert.Equal(expectedAnswer, bigInt.IsZero); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Numerics.Tests { public class IsZeroTest { private static int s_seed = 0; [Fact] public static void RunIsZeroTests() { Random random = new Random(s_seed); //Just basic tests // Zero VerifyIsZero(BigInteger.Zero, true); // Negative One VerifyIsZero(BigInteger.MinusOne, false); // One VerifyIsZero(BigInteger.One, false); // -Int32.MaxValue VerifyIsZero((BigInteger)int.MaxValue * -1, false); // Int32.MaxValue VerifyIsZero((BigInteger)int.MaxValue, false); // int32.MaxValue + 1 VerifyIsZero((BigInteger)int.MaxValue + 1, false); // UInt32.MaxValue VerifyIsZero((BigInteger)uint.MaxValue, false); // Uint32.MaxValue + 1 VerifyIsZero((BigInteger)uint.MaxValue + 1, false); } private static void VerifyIsZero(BigInteger bigInt, bool expectedAnswer) { Assert.Equal(expectedAnswer, bigInt.IsZero); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/HardwareIntrinsics/X86/Sse3/HorizontalAdd.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void HorizontalAddSingle() { var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalAddSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(HorizontalBinaryOpTest__HorizontalAddSingle testClass) { var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(HorizontalBinaryOpTest__HorizontalAddSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static HorizontalBinaryOpTest__HorizontalAddSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public HorizontalBinaryOpTest__HorizontalAddSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse3.HorizontalAdd( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse3.HorizontalAdd( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse3.HorizontalAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var outer = 0; outer < (LargestVectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Single)); inner++) { var i1 = (outer * (16 / sizeof(Single))) + inner; var i2 = i1 + (8 / sizeof(Single)); var i3 = (outer * (16 / sizeof(Single))) + (inner * 2); if (BitConverter.SingleToInt32Bits(result[i1]) != BitConverter.SingleToInt32Bits(left[i3] + left[i3 + 1])) { succeeded = false; break; } if (BitConverter.SingleToInt32Bits(result[i2]) != BitConverter.SingleToInt32Bits(right[i3] + right[i3 + 1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse3)}.{nameof(Sse3.HorizontalAdd)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void HorizontalAddSingle() { var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalAddSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(HorizontalBinaryOpTest__HorizontalAddSingle testClass) { var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(HorizontalBinaryOpTest__HorizontalAddSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static HorizontalBinaryOpTest__HorizontalAddSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public HorizontalBinaryOpTest__HorizontalAddSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse3.HorizontalAdd( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse3.HorizontalAdd( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse3.HorizontalAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new HorizontalBinaryOpTest__HorizontalAddSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse3.HorizontalAdd( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var outer = 0; outer < (LargestVectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Single)); inner++) { var i1 = (outer * (16 / sizeof(Single))) + inner; var i2 = i1 + (8 / sizeof(Single)); var i3 = (outer * (16 / sizeof(Single))) + (inner * 2); if (BitConverter.SingleToInt32Bits(result[i1]) != BitConverter.SingleToInt32Bits(left[i3] + left[i3 + 1])) { succeeded = false; break; } if (BitConverter.SingleToInt32Bits(result[i2]) != BitConverter.SingleToInt32Bits(right[i3] + right[i3 + 1])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse3)}.{nameof(Sse3.HorizontalAdd)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/baseservices/threading/generics/threadstart/thread18.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen { void Target<U>(); } class Gen : IGen { public virtual void Target<U>() { //dummy line to avoid warnings Test_thread18.Eval(typeof(U)!=null); Interlocked.Increment(ref Test_thread18.Xcounter); } public static void ThreadPoolTest<U>() { Thread[] threads = new Thread[Test_thread18.nThreads]; IGen obj = new Gen(); for (int i = 0; i < Test_thread18.nThreads; i++) { threads[i] = new Thread(new ThreadStart(obj.Target<U>)); threads[i].Start(); } for (int i = 0; i < Test_thread18.nThreads; i++) { threads[i].Join(); } Test_thread18.Eval(Test_thread18.Xcounter==Test_thread18.nThreads); Test_thread18.Xcounter = 0; } } public class Test_thread18 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Gen.ThreadPoolTest<object>(); Gen.ThreadPoolTest<string>(); Gen.ThreadPoolTest<Guid>(); Gen.ThreadPoolTest<int>(); Gen.ThreadPoolTest<double>(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen { void Target<U>(); } class Gen : IGen { public virtual void Target<U>() { //dummy line to avoid warnings Test_thread18.Eval(typeof(U)!=null); Interlocked.Increment(ref Test_thread18.Xcounter); } public static void ThreadPoolTest<U>() { Thread[] threads = new Thread[Test_thread18.nThreads]; IGen obj = new Gen(); for (int i = 0; i < Test_thread18.nThreads; i++) { threads[i] = new Thread(new ThreadStart(obj.Target<U>)); threads[i].Start(); } for (int i = 0; i < Test_thread18.nThreads; i++) { threads[i].Join(); } Test_thread18.Eval(Test_thread18.Xcounter==Test_thread18.nThreads); Test_thread18.Xcounter = 0; } } public class Test_thread18 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Gen.ThreadPoolTest<object>(); Gen.ThreadPoolTest<string>(); Gen.ThreadPoolTest<Guid>(); Gen.ThreadPoolTest<int>(); Gen.ThreadPoolTest<double>(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/Interop/NativeLibrary/NativeLibraryToLoad/NativeLibraryToLoad.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; public class NativeLibraryToLoad { public const string Name = "NativeLibrary"; public const string InvalidName = "DoesNotExist"; public static string GetFileName() { if (OperatingSystem.IsWindows()) return $"{Name}.dll"; if (OperatingSystem.IsLinux()) return $"lib{Name}.so"; if (OperatingSystem.IsMacOS()) return $"lib{Name}.dylib"; throw new PlatformNotSupportedException(); } public static string GetFullPath() { Assembly assembly = Assembly.GetExecutingAssembly(); string directory = Path.GetDirectoryName(assembly.Location); return Path.Combine(directory, GetFileName()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; public class NativeLibraryToLoad { public const string Name = "NativeLibrary"; public const string InvalidName = "DoesNotExist"; public static string GetFileName() { if (OperatingSystem.IsWindows()) return $"{Name}.dll"; if (OperatingSystem.IsLinux()) return $"lib{Name}.so"; if (OperatingSystem.IsMacOS()) return $"lib{Name}.dylib"; throw new PlatformNotSupportedException(); } public static string GetFullPath() { Assembly assembly = Assembly.GetExecutingAssembly(); string directory = Path.GetDirectoryName(assembly.Location); return Path.Combine(directory, GetFileName()); } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/ObjectPool`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Threading; namespace System.Reflection.Internal { /// <summary> /// Generic implementation of object pooling pattern with predefined pool size limit. The main /// purpose is that limited number of frequently used objects can be kept in the pool for /// further recycling. /// /// Notes: /// 1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there /// is no space in the pool, extra returned objects will be dropped. /// /// 2) it is implied that if object was obtained from a pool, the caller will return it back in /// a relatively short time. Keeping checked out objects for long durations is ok, but /// reduces usefulness of pooling. Just new up your own. /// /// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice. /// Rationale: /// If there is no intent for reusing the object, do not use pool - just use "new". /// </summary> internal sealed class ObjectPool<T> where T : class { private struct Element { internal T? Value; } // storage for the pool objects. private readonly Element[] _items; // factory is stored for the lifetime of the pool. We will call this only when pool needs to // expand. compared to "new T()", Func gives more flexibility to implementers and faster // than "new T()". private readonly Func<T> _factory; internal ObjectPool(Func<T> factory) : this(factory, Environment.ProcessorCount * 2) { } internal ObjectPool(Func<T> factory, int size) { _factory = factory; _items = new Element[size]; } private T CreateInstance() { var inst = _factory(); return inst; } /// <summary> /// Produces an instance. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search. /// </remarks> internal T Allocate() { var items = _items; T? inst; for (int i = 0; i < items.Length; i++) { // Note that the read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. inst = items[i].Value; if (inst != null) { if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst)) { goto gotInstance; } } } inst = CreateInstance(); gotInstance: return inst; } /// <summary> /// Returns objects to the pool. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search in Allocate. /// </remarks> internal void Free(T obj) { var items = _items; for (int i = 0; i < items.Length; i++) { if (items[i].Value == null) { // Intentionally not using interlocked here. // In a worst case scenario two objects may be stored into same slot. // It is very unlikely to happen and will only mean that one of the objects will get collected. items[i].Value = obj; break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Threading; namespace System.Reflection.Internal { /// <summary> /// Generic implementation of object pooling pattern with predefined pool size limit. The main /// purpose is that limited number of frequently used objects can be kept in the pool for /// further recycling. /// /// Notes: /// 1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there /// is no space in the pool, extra returned objects will be dropped. /// /// 2) it is implied that if object was obtained from a pool, the caller will return it back in /// a relatively short time. Keeping checked out objects for long durations is ok, but /// reduces usefulness of pooling. Just new up your own. /// /// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice. /// Rationale: /// If there is no intent for reusing the object, do not use pool - just use "new". /// </summary> internal sealed class ObjectPool<T> where T : class { private struct Element { internal T? Value; } // storage for the pool objects. private readonly Element[] _items; // factory is stored for the lifetime of the pool. We will call this only when pool needs to // expand. compared to "new T()", Func gives more flexibility to implementers and faster // than "new T()". private readonly Func<T> _factory; internal ObjectPool(Func<T> factory) : this(factory, Environment.ProcessorCount * 2) { } internal ObjectPool(Func<T> factory, int size) { _factory = factory; _items = new Element[size]; } private T CreateInstance() { var inst = _factory(); return inst; } /// <summary> /// Produces an instance. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search. /// </remarks> internal T Allocate() { var items = _items; T? inst; for (int i = 0; i < items.Length; i++) { // Note that the read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. inst = items[i].Value; if (inst != null) { if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst)) { goto gotInstance; } } } inst = CreateInstance(); gotInstance: return inst; } /// <summary> /// Returns objects to the pool. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search in Allocate. /// </remarks> internal void Free(T obj) { var items = _items; for (int i = 0; i < items.Length; i++) { if (items[i].Value == null) { // Intentionally not using interlocked here. // In a worst case scenario two objects may be stored into same slot. // It is very unlikely to happen and will only mean that one of the objects will get collected. items[i].Value = obj; break; } } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Performance/CodeQuality/Benchstones/MDBenchI/MDAddArray2/MDAddArray2.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> <PropertyGroup> <ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> <PropertyGroup> <ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile> </PropertyGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/Loader/classloader/generics/Instantiation/Positive/NestedBaseClass02.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public struct ValX0 {} public struct ValY0 {} public struct ValX1<T> {} public struct ValY1<T> {} public struct ValX2<T,U> {} public struct ValY2<T,U>{} public struct ValX3<T,U,V>{} public struct ValY3<T,U,V>{} public class RefX0 {} public class RefY0 {} public class RefX1<T> {} public class RefY1<T> {} public class RefX2<T,U> {} public class RefY2<T,U>{} public class RefX3<T,U,V>{} public class RefY3<T,U,V>{} public class GenOuter<U> { public class GenBase<T> { public T Fld1; public GenBase(T fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(GenBase<T>) ); } return result; } } } public class GenInt : GenOuter<int>.GenBase<int> { public GenInt() : base(1) {} public bool InstVerify() { return base.InstVerify(typeof(int)); } } public class GenDouble: GenOuter<int>.GenBase<double> { public GenDouble() : base(1) {} public bool InstVerify() { return base.InstVerify(typeof(double)); } } public class GenString : GenOuter<string>.GenBase<String> { public GenString() : base("string") {} public bool InstVerify() { return base.InstVerify(typeof(string)); } } public class GenObject : GenOuter<string>.GenBase<object> { public GenObject() : base(new object()) {} public bool InstVerify() { return base.InstVerify(typeof(object)); } } public class GenGuid : GenOuter<object>.GenBase<Guid> { public GenGuid() : base(new Guid()) {} public bool InstVerify() { return base.InstVerify(typeof(Guid)); } } public class GenConstructedReference : GenOuter<object>.GenBase<RefX1<int>> { public GenConstructedReference() : base(new RefX1<int>()) {} public bool InstVerify() { return base.InstVerify(typeof(RefX1<int>)); } } public class GenConstructedValue: GenOuter<double>.GenBase<ValX1<string>> { public GenConstructedValue() : base(new ValX1<string>()) {} public bool InstVerify() { return base.InstVerify(typeof(ValX1<string>)); } } public class GenInt1DArray : GenOuter<double>.GenBase<int[]> { public GenInt1DArray() : base(new int[1]) {} public bool InstVerify() { return base.InstVerify(typeof(int[])); } } public class GenString2DArray : GenOuter<Guid>.GenBase<string[,]> { public GenString2DArray() : base(new string[1,1]) {} public bool InstVerify() { return base.InstVerify(typeof(string[,])); } } public class GenIntJaggedArray : GenOuter<Guid>.GenBase<int[][]> { public GenIntJaggedArray() : base(new int[1][]) {} public bool InstVerify() { return base.InstVerify(typeof(int[][])); } } public class Test_NestedBaseClass02 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Eval(new GenInt().InstVerify()); Eval(new GenDouble().InstVerify()); Eval(new GenString().InstVerify()); Eval(new GenObject().InstVerify()); Eval(new GenGuid().InstVerify()); Eval(new GenConstructedReference().InstVerify()); Eval(new GenConstructedValue().InstVerify()); Eval(new GenInt1DArray().InstVerify()); Eval(new GenString2DArray().InstVerify()); Eval(new GenIntJaggedArray().InstVerify()); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; public struct ValX0 {} public struct ValY0 {} public struct ValX1<T> {} public struct ValY1<T> {} public struct ValX2<T,U> {} public struct ValY2<T,U>{} public struct ValX3<T,U,V>{} public struct ValY3<T,U,V>{} public class RefX0 {} public class RefY0 {} public class RefX1<T> {} public class RefY1<T> {} public class RefX2<T,U> {} public class RefY2<T,U>{} public class RefX3<T,U,V>{} public class RefY3<T,U,V>{} public class GenOuter<U> { public class GenBase<T> { public T Fld1; public GenBase(T fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(GenBase<T>) ); } return result; } } } public class GenInt : GenOuter<int>.GenBase<int> { public GenInt() : base(1) {} public bool InstVerify() { return base.InstVerify(typeof(int)); } } public class GenDouble: GenOuter<int>.GenBase<double> { public GenDouble() : base(1) {} public bool InstVerify() { return base.InstVerify(typeof(double)); } } public class GenString : GenOuter<string>.GenBase<String> { public GenString() : base("string") {} public bool InstVerify() { return base.InstVerify(typeof(string)); } } public class GenObject : GenOuter<string>.GenBase<object> { public GenObject() : base(new object()) {} public bool InstVerify() { return base.InstVerify(typeof(object)); } } public class GenGuid : GenOuter<object>.GenBase<Guid> { public GenGuid() : base(new Guid()) {} public bool InstVerify() { return base.InstVerify(typeof(Guid)); } } public class GenConstructedReference : GenOuter<object>.GenBase<RefX1<int>> { public GenConstructedReference() : base(new RefX1<int>()) {} public bool InstVerify() { return base.InstVerify(typeof(RefX1<int>)); } } public class GenConstructedValue: GenOuter<double>.GenBase<ValX1<string>> { public GenConstructedValue() : base(new ValX1<string>()) {} public bool InstVerify() { return base.InstVerify(typeof(ValX1<string>)); } } public class GenInt1DArray : GenOuter<double>.GenBase<int[]> { public GenInt1DArray() : base(new int[1]) {} public bool InstVerify() { return base.InstVerify(typeof(int[])); } } public class GenString2DArray : GenOuter<Guid>.GenBase<string[,]> { public GenString2DArray() : base(new string[1,1]) {} public bool InstVerify() { return base.InstVerify(typeof(string[,])); } } public class GenIntJaggedArray : GenOuter<Guid>.GenBase<int[][]> { public GenIntJaggedArray() : base(new int[1][]) {} public bool InstVerify() { return base.InstVerify(typeof(int[][])); } } public class Test_NestedBaseClass02 { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Eval(new GenInt().InstVerify()); Eval(new GenDouble().InstVerify()); Eval(new GenString().InstVerify()); Eval(new GenObject().InstVerify()); Eval(new GenGuid().InstVerify()); Eval(new GenConstructedReference().InstVerify()); Eval(new GenConstructedValue().InstVerify()); Eval(new GenInt1DArray().InstVerify()); Eval(new GenString2DArray().InstVerify()); Eval(new GenIntJaggedArray().InstVerify()); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Data.Common/src/System/Data/ITableMapping.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Data { public interface ITableMapping { IColumnMappingCollection ColumnMappings { get; } string DataSetTable { get; set; } string SourceTable { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Data { public interface ITableMapping { IColumnMappingCollection ColumnMappings { get; } string DataSetTable { get; set; } string SourceTable { get; set; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/Common/src/System/Net/ContextFlagsPal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace System.Net { [Flags] internal enum ContextFlagsPal { None = 0, Delegate = 0x00000001, MutualAuth = 0x00000002, ReplayDetect = 0x00000004, SequenceDetect = 0x00000008, Confidentiality = 0x00000010, UseSessionKey = 0x00000020, AllocateMemory = 0x00000100, Connection = 0x00000800, InitExtendedError = 0x00004000, AcceptExtendedError = 0x00008000, InitStream = 0x00008000, AcceptStream = 0x00010000, InitIntegrity = 0x00010000, AcceptIntegrity = 0x00020000, InitManualCredValidation = 0x00080000, InitUseSuppliedCreds = 0x00000080, InitIdentify = 0x00020000, AcceptIdentify = 0x00080000, ProxyBindings = 0x04000000, AllowMissingBindings = 0x10000000, UnverifiedTargetName = 0x20000000, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace System.Net { [Flags] internal enum ContextFlagsPal { None = 0, Delegate = 0x00000001, MutualAuth = 0x00000002, ReplayDetect = 0x00000004, SequenceDetect = 0x00000008, Confidentiality = 0x00000010, UseSessionKey = 0x00000020, AllocateMemory = 0x00000100, Connection = 0x00000800, InitExtendedError = 0x00004000, AcceptExtendedError = 0x00008000, InitStream = 0x00008000, AcceptStream = 0x00010000, InitIntegrity = 0x00010000, AcceptIntegrity = 0x00020000, InitManualCredValidation = 0x00080000, InitUseSuppliedCreds = 0x00000080, InitIdentify = 0x00020000, AcceptIdentify = 0x00080000, ProxyBindings = 0x04000000, AllowMissingBindings = 0x10000000, UnverifiedTargetName = 0x20000000, } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/HardwareIntrinsics/X86/General/VectorArgs_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="VectorArgs.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="VectorArgs.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectorySecurityTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.DirectoryServices.Tests { public class ActiveDirectorySecurityTests { [Fact] public void Ctor_Default() { var security = new ActiveDirectorySecurity(); Assert.Equal(typeof(ActiveDirectoryRights), security.AccessRightType); Assert.Equal(typeof(ActiveDirectoryAccessRule), security.AccessRuleType); Assert.Equal(typeof(ActiveDirectoryAuditRule), security.AuditRuleType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.DirectoryServices.Tests { public class ActiveDirectorySecurityTests { [Fact] public void Ctor_Default() { var security = new ActiveDirectorySecurity(); Assert.Equal(typeof(ActiveDirectoryRights), security.AccessRightType); Assert.Equal(typeof(ActiveDirectoryAccessRule), security.AccessRuleType); Assert.Equal(typeof(ActiveDirectoryAuditRule), security.AuditRuleType); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.ComponentModel.TypeConverter/src/System/Timers/TimersDescriptionAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics; namespace System.Timers { /// <summary> /// DescriptionAttribute marks a property, event, or extender with a /// description. Visual designers can display this description when referencing /// the member. /// </summary> [AttributeUsage(AttributeTargets.All)] public class TimersDescriptionAttribute : DescriptionAttribute { private bool _replaced; /// <summary> /// Constructs a new sys description. /// </summary> public TimersDescriptionAttribute(string description) : base(description) { } /// <summary> /// Constructs a new localized sys description. /// </summary> internal TimersDescriptionAttribute(string description, string? unused) : base(SR.GetResourceString(description)) { // Needed for overload resolution Debug.Assert(unused == null); } /// <summary> /// Retrieves the description text. /// </summary> public override string Description { get { if (!_replaced) { _replaced = true; DescriptionValue = SR.Format(base.Description); } return base.Description; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics; namespace System.Timers { /// <summary> /// DescriptionAttribute marks a property, event, or extender with a /// description. Visual designers can display this description when referencing /// the member. /// </summary> [AttributeUsage(AttributeTargets.All)] public class TimersDescriptionAttribute : DescriptionAttribute { private bool _replaced; /// <summary> /// Constructs a new sys description. /// </summary> public TimersDescriptionAttribute(string description) : base(description) { } /// <summary> /// Constructs a new localized sys description. /// </summary> internal TimersDescriptionAttribute(string description, string? unused) : base(SR.GetResourceString(description)) { // Needed for overload resolution Debug.Assert(unused == null); } /// <summary> /// Retrieves the description text. /// </summary> public override string Description { get { if (!_replaced) { _replaced = true; DescriptionValue = SR.Format(base.Description); } return base.Description; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Configuration.ConfigurationManager/tests/System/Configuration/CustomHostTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Runtime.InteropServices; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Configuration.Tests { /// <summary> /// Tests ConfigurationManager works even when Assembly.GetEntryAssembly() returns null. /// </summary> public class CustomHostTests { [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Does not apply to .NET Framework.")] public void FilePathIsPopulatedCorrectly() { RemoteExecutor.Invoke(() => { MakeAssemblyGetEntryAssemblyReturnNull(); string expectedFilePathEnding = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe.config" : "dotnet.config"; Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); Assert.EndsWith(expectedFilePathEnding, config.FilePath); }).Dispose(); } /// <summary> /// Makes Assembly.GetEntryAssembly() return null using private reflection. /// </summary> private static void MakeAssemblyGetEntryAssemblyReturnNull() { typeof(Assembly) .GetField("s_forceNullEntryPoint", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, true); Assert.Null(Assembly.GetEntryAssembly()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Runtime.InteropServices; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Configuration.Tests { /// <summary> /// Tests ConfigurationManager works even when Assembly.GetEntryAssembly() returns null. /// </summary> public class CustomHostTests { [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Does not apply to .NET Framework.")] public void FilePathIsPopulatedCorrectly() { RemoteExecutor.Invoke(() => { MakeAssemblyGetEntryAssemblyReturnNull(); string expectedFilePathEnding = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe.config" : "dotnet.config"; Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); Assert.EndsWith(expectedFilePathEnding, config.FilePath); }).Dispose(); } /// <summary> /// Makes Assembly.GetEntryAssembly() return null using private reflection. /// </summary> private static void MakeAssemblyGetEntryAssemblyReturnNull() { typeof(Assembly) .GetField("s_forceNullEntryPoint", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, true); Assert.Null(Assembly.GetEntryAssembly()); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Reflection.TypeExtensions/src/System.Reflection.TypeExtensions.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly> <Nullable>enable</Nullable> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="System\Reflection\TypeExtensions.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(CoreLibProject)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly> <Nullable>enable</Nullable> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="System\Reflection\TypeExtensions.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(CoreLibProject)" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/jit64/opt/rngchk/JaggedArray.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; namespace SimpleArray_01 { public delegate void RngTest(); internal class Class1 { private static int Main() { int retVal = 100; int testNum = 0; RngTest[] Tests ={ new RngTest(Test.Test1), new RngTest(Test.Test2), new RngTest(Test.Test3), new RngTest(Test.Test4), new RngTest(Test.Test5)}; foreach (RngTest test in Tests) { testNum++; if (DoTest(test)) { Console.WriteLine("Test {0} Passed", testNum); } else { Console.WriteLine("Test {0} Failed", testNum); retVal = 1; } } return retVal; } //Test shall throw IndexOutOfRangeException if rangecheck is inserted properly private static bool DoTest(RngTest Test) { bool bResult = false; try { Test(); } catch (System.IndexOutOfRangeException) { bResult = true; } catch (Exception e) { Console.WriteLine(e.Message); } return bResult; } } internal class Test { /******************************************************************************************** * RngChk shall not be eliminated if directly access jaggedArray elements *********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test1() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < myJaggedArray[i].Length; i++) { myJaggedArray[2][j] = 1; } } } /******************************************************************************************** * RngChk shall not be eliminated if the loop upper limit is larger than the array bound ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test2() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int innerUpper = myJaggedArray[2].Length; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < innerUpper; j++) { myJaggedArray[i][j] = 1; } } } /******************************************************************************************** * RngChk is not eliminated if the array is modified ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test3() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int[][] dummy = new int[2][] { new int[5], new int[3] }; int upper = myJaggedArray.Length; for (i = 0; i < upper; i++) { for (j = 0; j < myJaggedArray[i].Length; j++) { myJaggedArray[i][j] = 1; myJaggedArray = dummy; } myJaggedArray[i][0] = i; } } /******************************************************************************************** * RngChk is not eliminated if the upper limit of the array is modified ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test4() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int innerUpper = myJaggedArray[2].Length; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < innerUpper; j++, innerUpper++) { myJaggedArray[i][j] = 1; } } } /******************************************************************************************** * RngChk is not eliminated if induction variable is modified ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test5() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int innerUpper = myJaggedArray[2].Length; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < innerUpper; j++) { myJaggedArray[i][++j] = 1; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.CompilerServices; namespace SimpleArray_01 { public delegate void RngTest(); internal class Class1 { private static int Main() { int retVal = 100; int testNum = 0; RngTest[] Tests ={ new RngTest(Test.Test1), new RngTest(Test.Test2), new RngTest(Test.Test3), new RngTest(Test.Test4), new RngTest(Test.Test5)}; foreach (RngTest test in Tests) { testNum++; if (DoTest(test)) { Console.WriteLine("Test {0} Passed", testNum); } else { Console.WriteLine("Test {0} Failed", testNum); retVal = 1; } } return retVal; } //Test shall throw IndexOutOfRangeException if rangecheck is inserted properly private static bool DoTest(RngTest Test) { bool bResult = false; try { Test(); } catch (System.IndexOutOfRangeException) { bResult = true; } catch (Exception e) { Console.WriteLine(e.Message); } return bResult; } } internal class Test { /******************************************************************************************** * RngChk shall not be eliminated if directly access jaggedArray elements *********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test1() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < myJaggedArray[i].Length; i++) { myJaggedArray[2][j] = 1; } } } /******************************************************************************************** * RngChk shall not be eliminated if the loop upper limit is larger than the array bound ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test2() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int innerUpper = myJaggedArray[2].Length; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < innerUpper; j++) { myJaggedArray[i][j] = 1; } } } /******************************************************************************************** * RngChk is not eliminated if the array is modified ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test3() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int[][] dummy = new int[2][] { new int[5], new int[3] }; int upper = myJaggedArray.Length; for (i = 0; i < upper; i++) { for (j = 0; j < myJaggedArray[i].Length; j++) { myJaggedArray[i][j] = 1; myJaggedArray = dummy; } myJaggedArray[i][0] = i; } } /******************************************************************************************** * RngChk is not eliminated if the upper limit of the array is modified ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test4() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int innerUpper = myJaggedArray[2].Length; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < innerUpper; j++, innerUpper++) { myJaggedArray[i][j] = 1; } } } /******************************************************************************************** * RngChk is not eliminated if induction variable is modified ********************************************************************************************/ [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Test5() { int[][] myJaggedArray = new int[3][] { new int[5], new int[3], new int[4] }; int i, j; int innerUpper = myJaggedArray[2].Length; for (i = 0; i < myJaggedArray.Length; i++) { for (j = 0; j < innerUpper; j++) { myJaggedArray[i][++j] = 1; } } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyAddByScalar.Vector64.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyAddByScalar_Vector64_Int32() { var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public Vector64<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32 testClass) { var result = AdvSimd.MultiplyAddByScalar(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) fixed (Vector64<Int32>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), AdvSimd.LoadVector64((Int32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private static Vector64<Int32> _clsVar3; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private Vector64<Int32> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyAddByScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddByScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddByScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyAddByScalar( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) fixed (Vector64<Int32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((Int32*)(pClsVar2)), AdvSimd.LoadVector64((Int32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyAddByScalar(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyAddByScalar(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32(); var result = AdvSimd.MultiplyAddByScalar(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) fixed (Vector64<Int32>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), AdvSimd.LoadVector64((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyAddByScalar(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) fixed (Vector64<Int32>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), AdvSimd.LoadVector64((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddByScalar(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((Int32*)(&test._fld2)), AdvSimd.LoadVector64((Int32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector64<Int32> op2, Vector64<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[0]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAddByScalar)}<Int32>(Vector64<Int32>, Vector64<Int32>, Vector64<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyAddByScalar_Vector64_Int32() { var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public Vector64<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32 testClass) { var result = AdvSimd.MultiplyAddByScalar(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) fixed (Vector64<Int32>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), AdvSimd.LoadVector64((Int32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private static Vector64<Int32> _clsVar3; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private Vector64<Int32> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyAddByScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddByScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddByScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyAddByScalar( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) fixed (Vector64<Int32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((Int32*)(pClsVar2)), AdvSimd.LoadVector64((Int32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr); var result = AdvSimd.MultiplyAddByScalar(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.MultiplyAddByScalar(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32(); var result = AdvSimd.MultiplyAddByScalar(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) fixed (Vector64<Int32>* pFld3 = &test._fld3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), AdvSimd.LoadVector64((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyAddByScalar(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) fixed (Vector64<Int32>* pFld3 = &_fld3) { var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)), AdvSimd.LoadVector64((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddByScalar(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyAddByScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((Int32*)(&test._fld2)), AdvSimd.LoadVector64((Int32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector64<Int32> op2, Vector64<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[0]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAddByScalar)}<Int32>(Vector64<Int32>, Vector64<Int32>, Vector64<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Directed/coverage/oldtests/lclfldsub.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //Testing simple math on local vars and fields - sub #pragma warning disable 0414 using System; internal class lclfldsub { //user-defined class that overloads operator - public class numHolder { private int _i_num; private uint _ui_num; private long _l_num; private ulong _ul_num; private float _f_num; private double _d_num; private decimal _m_num; public numHolder(int i_num) { _i_num = Convert.ToInt32(i_num); _ui_num = Convert.ToUInt32(i_num); _l_num = Convert.ToInt64(i_num); _ul_num = Convert.ToUInt64(i_num); _f_num = Convert.ToSingle(i_num); _d_num = Convert.ToDouble(i_num); _m_num = Convert.ToDecimal(i_num); } public static int operator -(numHolder a, int b) { return a._i_num - b; } public numHolder(uint ui_num) { _i_num = Convert.ToInt32(ui_num); _ui_num = Convert.ToUInt32(ui_num); _l_num = Convert.ToInt64(ui_num); _ul_num = Convert.ToUInt64(ui_num); _f_num = Convert.ToSingle(ui_num); _d_num = Convert.ToDouble(ui_num); _m_num = Convert.ToDecimal(ui_num); } public static uint operator -(numHolder a, uint b) { return a._ui_num - b; } public numHolder(long l_num) { _i_num = Convert.ToInt32(l_num); _ui_num = Convert.ToUInt32(l_num); _l_num = Convert.ToInt64(l_num); _ul_num = Convert.ToUInt64(l_num); _f_num = Convert.ToSingle(l_num); _d_num = Convert.ToDouble(l_num); _m_num = Convert.ToDecimal(l_num); } public static long operator -(numHolder a, long b) { return a._l_num - b; } public numHolder(ulong ul_num) { _i_num = Convert.ToInt32(ul_num); _ui_num = Convert.ToUInt32(ul_num); _l_num = Convert.ToInt64(ul_num); _ul_num = Convert.ToUInt64(ul_num); _f_num = Convert.ToSingle(ul_num); _d_num = Convert.ToDouble(ul_num); _m_num = Convert.ToDecimal(ul_num); } public static long operator -(numHolder a, ulong b) { return (long)(a._ul_num - b); } public numHolder(float f_num) { _i_num = Convert.ToInt32(f_num); _ui_num = Convert.ToUInt32(f_num); _l_num = Convert.ToInt64(f_num); _ul_num = Convert.ToUInt64(f_num); _f_num = Convert.ToSingle(f_num); _d_num = Convert.ToDouble(f_num); _m_num = Convert.ToDecimal(f_num); } public static float operator -(numHolder a, float b) { return a._f_num - b; } public numHolder(double d_num) { _i_num = Convert.ToInt32(d_num); _ui_num = Convert.ToUInt32(d_num); _l_num = Convert.ToInt64(d_num); _ul_num = Convert.ToUInt64(d_num); _f_num = Convert.ToSingle(d_num); _d_num = Convert.ToDouble(d_num); _m_num = Convert.ToDecimal(d_num); } public static double operator -(numHolder a, double b) { return a._d_num - b; } public numHolder(decimal m_num) { _i_num = Convert.ToInt32(m_num); _ui_num = Convert.ToUInt32(m_num); _l_num = Convert.ToInt64(m_num); _ul_num = Convert.ToUInt64(m_num); _f_num = Convert.ToSingle(m_num); _d_num = Convert.ToDouble(m_num); _m_num = Convert.ToDecimal(m_num); } public static int operator -(numHolder a, decimal b) { return (int)(a._m_num - b); } public static int operator -(numHolder a, numHolder b) { return a._i_num - b._i_num; } } private static int s_i_s_op1 = 16; private static uint s_ui_s_op1 = 16; private static long s_l_s_op1 = 16; private static ulong s_ul_s_op1 = 16; private static float s_f_s_op1 = 16; private static double s_d_s_op1 = 16; private static decimal s_m_s_op1 = 16; private static int s_i_s_op2 = 15; private static uint s_ui_s_op2 = 15; private static long s_l_s_op2 = 15; private static ulong s_ul_s_op2 = 15; private static float s_f_s_op2 = 15; private static double s_d_s_op2 = 15; private static decimal s_m_s_op2 = 15; private static numHolder s_nHldr_s_op2 = new numHolder(15); public static int i_f(String s) { if (s == "op1") return 16; else return 15; } public static uint ui_f(String s) { if (s == "op1") return 16; else return 15; } public static long l_f(String s) { if (s == "op1") return 16; else return 15; } public static ulong ul_f(String s) { if (s == "op1") return 16; else return 15; } public static float f_f(String s) { if (s == "op1") return 16; else return 15; } public static double d_f(String s) { if (s == "op1") return 16; else return 15; } public static decimal m_f(String s) { if (s == "op1") return 16; else return 15; } public static numHolder nHldr_f(String s) { if (s == "op1") return new numHolder(16); else return new numHolder(15); } private class CL { public int i_cl_op1 = 16; public uint ui_cl_op1 = 16; public long l_cl_op1 = 16; public ulong ul_cl_op1 = 16; public float f_cl_op1 = 16; public double d_cl_op1 = 16; public decimal m_cl_op1 = 16; public int i_cl_op2 = 15; public uint ui_cl_op2 = 15; public long l_cl_op2 = 15; public ulong ul_cl_op2 = 15; public float f_cl_op2 = 15; public double d_cl_op2 = 15; public decimal m_cl_op2 = 15; public numHolder nHldr_cl_op2 = new numHolder(15); } private struct VT { public int i_vt_op1; public uint ui_vt_op1; public long l_vt_op1; public ulong ul_vt_op1; public float f_vt_op1; public double d_vt_op1; public decimal m_vt_op1; public int i_vt_op2; public uint ui_vt_op2; public long l_vt_op2; public ulong ul_vt_op2; public float f_vt_op2; public double d_vt_op2; public decimal m_vt_op2; public numHolder nHldr_vt_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.i_vt_op1 = 16; vt1.ui_vt_op1 = 16; vt1.l_vt_op1 = 16; vt1.ul_vt_op1 = 16; vt1.f_vt_op1 = 16; vt1.d_vt_op1 = 16; vt1.m_vt_op1 = 16; vt1.i_vt_op2 = 15; vt1.ui_vt_op2 = 15; vt1.l_vt_op2 = 15; vt1.ul_vt_op2 = 15; vt1.f_vt_op2 = 15; vt1.d_vt_op2 = 15; vt1.m_vt_op2 = 15; vt1.nHldr_vt_op2 = new numHolder(15); int[] i_arr1d_op1 = { 0, 16 }; int[,] i_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; int[,,] i_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; uint[] ui_arr1d_op1 = { 0, 16 }; uint[,] ui_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; uint[,,] ui_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; long[] l_arr1d_op1 = { 0, 16 }; long[,] l_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; long[,,] l_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; ulong[] ul_arr1d_op1 = { 0, 16 }; ulong[,] ul_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; ulong[,,] ul_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; float[] f_arr1d_op1 = { 0, 16 }; float[,] f_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; float[,,] f_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; double[] d_arr1d_op1 = { 0, 16 }; double[,] d_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; double[,,] d_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; decimal[] m_arr1d_op1 = { 0, 16 }; decimal[,] m_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; decimal[,,] m_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; int[] i_arr1d_op2 = { 15, 0, 1 }; int[,] i_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; int[,,] i_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; uint[] ui_arr1d_op2 = { 15, 0, 1 }; uint[,] ui_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; uint[,,] ui_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; long[] l_arr1d_op2 = { 15, 0, 1 }; long[,] l_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; long[,,] l_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; ulong[] ul_arr1d_op2 = { 15, 0, 1 }; ulong[,] ul_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; ulong[,,] ul_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; float[] f_arr1d_op2 = { 15, 0, 1 }; float[,] f_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; float[,,] f_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; double[] d_arr1d_op2 = { 15, 0, 1 }; double[,] d_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; double[,,] d_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; decimal[] m_arr1d_op2 = { 15, 0, 1 }; decimal[,] m_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; decimal[,,] m_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; numHolder[] nHldr_arr1d_op2 = { new numHolder(15), new numHolder(0), new numHolder(1) }; numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } }; numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { int i_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((i_l_op1 - i_l_op2 != i_l_op1 - ui_l_op2) || (i_l_op1 - ui_l_op2 != i_l_op1 - l_l_op2) || (i_l_op1 - l_l_op2 != i_l_op1 - (int)ul_l_op2) || (i_l_op1 - (int)ul_l_op2 != i_l_op1 - f_l_op2) || (i_l_op1 - f_l_op2 != i_l_op1 - d_l_op2) || ((decimal)(i_l_op1 - d_l_op2) != i_l_op1 - m_l_op2) || (i_l_op1 - m_l_op2 != i_l_op1 - i_l_op2) || (i_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 1 failed"); passed = false; } if ((i_l_op1 - s_i_s_op2 != i_l_op1 - s_ui_s_op2) || (i_l_op1 - s_ui_s_op2 != i_l_op1 - s_l_s_op2) || (i_l_op1 - s_l_s_op2 != i_l_op1 - (int)s_ul_s_op2) || (i_l_op1 - (int)s_ul_s_op2 != i_l_op1 - s_f_s_op2) || (i_l_op1 - s_f_s_op2 != i_l_op1 - s_d_s_op2) || ((decimal)(i_l_op1 - s_d_s_op2) != i_l_op1 - s_m_s_op2) || (i_l_op1 - s_m_s_op2 != i_l_op1 - s_i_s_op2) || (i_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 2 failed"); passed = false; } if ((s_i_s_op1 - i_l_op2 != s_i_s_op1 - ui_l_op2) || (s_i_s_op1 - ui_l_op2 != s_i_s_op1 - l_l_op2) || (s_i_s_op1 - l_l_op2 != s_i_s_op1 - (int)ul_l_op2) || (s_i_s_op1 - (int)ul_l_op2 != s_i_s_op1 - f_l_op2) || (s_i_s_op1 - f_l_op2 != s_i_s_op1 - d_l_op2) || ((decimal)(s_i_s_op1 - d_l_op2) != s_i_s_op1 - m_l_op2) || (s_i_s_op1 - m_l_op2 != s_i_s_op1 - i_l_op2) || (s_i_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 3 failed"); passed = false; } if ((s_i_s_op1 - s_i_s_op2 != s_i_s_op1 - s_ui_s_op2) || (s_i_s_op1 - s_ui_s_op2 != s_i_s_op1 - s_l_s_op2) || (s_i_s_op1 - s_l_s_op2 != s_i_s_op1 - (int)s_ul_s_op2) || (s_i_s_op1 - (int)s_ul_s_op2 != s_i_s_op1 - s_f_s_op2) || (s_i_s_op1 - s_f_s_op2 != s_i_s_op1 - s_d_s_op2) || ((decimal)(s_i_s_op1 - s_d_s_op2) != s_i_s_op1 - s_m_s_op2) || (s_i_s_op1 - s_m_s_op2 != s_i_s_op1 - s_i_s_op2) || (s_i_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 4 failed"); passed = false; } } { uint ui_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ui_l_op1 - i_l_op2 != ui_l_op1 - ui_l_op2) || (ui_l_op1 - ui_l_op2 != ui_l_op1 - l_l_op2) || ((ulong)(ui_l_op1 - l_l_op2) != ui_l_op1 - ul_l_op2) || (ui_l_op1 - ul_l_op2 != ui_l_op1 - f_l_op2) || (ui_l_op1 - f_l_op2 != ui_l_op1 - d_l_op2) || ((decimal)(ui_l_op1 - d_l_op2) != ui_l_op1 - m_l_op2) || (ui_l_op1 - m_l_op2 != ui_l_op1 - i_l_op2) || (ui_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 5 failed"); passed = false; } if ((ui_l_op1 - s_i_s_op2 != ui_l_op1 - s_ui_s_op2) || (ui_l_op1 - s_ui_s_op2 != ui_l_op1 - s_l_s_op2) || ((ulong)(ui_l_op1 - s_l_s_op2) != ui_l_op1 - s_ul_s_op2) || (ui_l_op1 - s_ul_s_op2 != ui_l_op1 - s_f_s_op2) || (ui_l_op1 - s_f_s_op2 != ui_l_op1 - s_d_s_op2) || ((decimal)(ui_l_op1 - s_d_s_op2) != ui_l_op1 - s_m_s_op2) || (ui_l_op1 - s_m_s_op2 != ui_l_op1 - s_i_s_op2) || (ui_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 6 failed"); passed = false; } if ((s_ui_s_op1 - i_l_op2 != s_ui_s_op1 - ui_l_op2) || (s_ui_s_op1 - ui_l_op2 != s_ui_s_op1 - l_l_op2) || ((ulong)(s_ui_s_op1 - l_l_op2) != s_ui_s_op1 - ul_l_op2) || (s_ui_s_op1 - ul_l_op2 != s_ui_s_op1 - f_l_op2) || (s_ui_s_op1 - f_l_op2 != s_ui_s_op1 - d_l_op2) || ((decimal)(s_ui_s_op1 - d_l_op2) != s_ui_s_op1 - m_l_op2) || (s_ui_s_op1 - m_l_op2 != s_ui_s_op1 - i_l_op2) || (s_ui_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 7 failed"); passed = false; } if ((s_ui_s_op1 - s_i_s_op2 != s_ui_s_op1 - s_ui_s_op2) || (s_ui_s_op1 - s_ui_s_op2 != s_ui_s_op1 - s_l_s_op2) || ((ulong)(s_ui_s_op1 - s_l_s_op2) != s_ui_s_op1 - s_ul_s_op2) || (s_ui_s_op1 - s_ul_s_op2 != s_ui_s_op1 - s_f_s_op2) || (s_ui_s_op1 - s_f_s_op2 != s_ui_s_op1 - s_d_s_op2) || ((decimal)(s_ui_s_op1 - s_d_s_op2) != s_ui_s_op1 - s_m_s_op2) || (s_ui_s_op1 - s_m_s_op2 != s_ui_s_op1 - s_i_s_op2) || (s_ui_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 8 failed"); passed = false; } } { long l_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((l_l_op1 - i_l_op2 != l_l_op1 - ui_l_op2) || (l_l_op1 - ui_l_op2 != l_l_op1 - l_l_op2) || (l_l_op1 - l_l_op2 != l_l_op1 - (long)ul_l_op2) || (l_l_op1 - (long)ul_l_op2 != l_l_op1 - f_l_op2) || (l_l_op1 - f_l_op2 != l_l_op1 - d_l_op2) || ((decimal)(l_l_op1 - d_l_op2) != l_l_op1 - m_l_op2) || (l_l_op1 - m_l_op2 != l_l_op1 - i_l_op2) || (l_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 9 failed"); passed = false; } if ((l_l_op1 - s_i_s_op2 != l_l_op1 - s_ui_s_op2) || (l_l_op1 - s_ui_s_op2 != l_l_op1 - s_l_s_op2) || (l_l_op1 - s_l_s_op2 != l_l_op1 - (long)s_ul_s_op2) || (l_l_op1 - (long)s_ul_s_op2 != l_l_op1 - s_f_s_op2) || (l_l_op1 - s_f_s_op2 != l_l_op1 - s_d_s_op2) || ((decimal)(l_l_op1 - s_d_s_op2) != l_l_op1 - s_m_s_op2) || (l_l_op1 - s_m_s_op2 != l_l_op1 - s_i_s_op2) || (l_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 10 failed"); passed = false; } if ((s_l_s_op1 - i_l_op2 != s_l_s_op1 - ui_l_op2) || (s_l_s_op1 - ui_l_op2 != s_l_s_op1 - l_l_op2) || (s_l_s_op1 - l_l_op2 != s_l_s_op1 - (long)ul_l_op2) || (s_l_s_op1 - (long)ul_l_op2 != s_l_s_op1 - f_l_op2) || (s_l_s_op1 - f_l_op2 != s_l_s_op1 - d_l_op2) || ((decimal)(s_l_s_op1 - d_l_op2) != s_l_s_op1 - m_l_op2) || (s_l_s_op1 - m_l_op2 != s_l_s_op1 - i_l_op2) || (s_l_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 11 failed"); passed = false; } if ((s_l_s_op1 - s_i_s_op2 != s_l_s_op1 - s_ui_s_op2) || (s_l_s_op1 - s_ui_s_op2 != s_l_s_op1 - s_l_s_op2) || (s_l_s_op1 - s_l_s_op2 != s_l_s_op1 - (long)s_ul_s_op2) || (s_l_s_op1 - (long)s_ul_s_op2 != s_l_s_op1 - s_f_s_op2) || (s_l_s_op1 - s_f_s_op2 != s_l_s_op1 - s_d_s_op2) || ((decimal)(s_l_s_op1 - s_d_s_op2) != s_l_s_op1 - s_m_s_op2) || (s_l_s_op1 - s_m_s_op2 != s_l_s_op1 - s_i_s_op2) || (s_l_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 12 failed"); passed = false; } } { ulong ul_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ul_l_op1 - (ulong)i_l_op2 != ul_l_op1 - ui_l_op2) || (ul_l_op1 - ui_l_op2 != ul_l_op1 - (ulong)l_l_op2) || (ul_l_op1 - (ulong)l_l_op2 != ul_l_op1 - ul_l_op2) || (ul_l_op1 - ul_l_op2 != ul_l_op1 - f_l_op2) || (ul_l_op1 - f_l_op2 != ul_l_op1 - d_l_op2) || ((decimal)(ul_l_op1 - d_l_op2) != ul_l_op1 - m_l_op2) || (ul_l_op1 - m_l_op2 != ul_l_op1 - (ulong)i_l_op2) || (ul_l_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 13 failed"); passed = false; } if ((ul_l_op1 - (ulong)s_i_s_op2 != ul_l_op1 - s_ui_s_op2) || (ul_l_op1 - s_ui_s_op2 != ul_l_op1 - (ulong)s_l_s_op2) || (ul_l_op1 - (ulong)s_l_s_op2 != ul_l_op1 - s_ul_s_op2) || (ul_l_op1 - s_ul_s_op2 != ul_l_op1 - s_f_s_op2) || (ul_l_op1 - s_f_s_op2 != ul_l_op1 - s_d_s_op2) || ((decimal)(ul_l_op1 - s_d_s_op2) != ul_l_op1 - s_m_s_op2) || (ul_l_op1 - s_m_s_op2 != ul_l_op1 - (ulong)s_i_s_op2) || (ul_l_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 14 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)i_l_op2 != s_ul_s_op1 - ui_l_op2) || (s_ul_s_op1 - ui_l_op2 != s_ul_s_op1 - (ulong)l_l_op2) || (s_ul_s_op1 - (ulong)l_l_op2 != s_ul_s_op1 - ul_l_op2) || (s_ul_s_op1 - ul_l_op2 != s_ul_s_op1 - f_l_op2) || (s_ul_s_op1 - f_l_op2 != s_ul_s_op1 - d_l_op2) || ((decimal)(s_ul_s_op1 - d_l_op2) != s_ul_s_op1 - m_l_op2) || (s_ul_s_op1 - m_l_op2 != s_ul_s_op1 - (ulong)i_l_op2) || (s_ul_s_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 15 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)s_i_s_op2 != s_ul_s_op1 - s_ui_s_op2) || (s_ul_s_op1 - s_ui_s_op2 != s_ul_s_op1 - (ulong)s_l_s_op2) || (s_ul_s_op1 - (ulong)s_l_s_op2 != s_ul_s_op1 - s_ul_s_op2) || (s_ul_s_op1 - s_ul_s_op2 != s_ul_s_op1 - s_f_s_op2) || (s_ul_s_op1 - s_f_s_op2 != s_ul_s_op1 - s_d_s_op2) || ((decimal)(s_ul_s_op1 - s_d_s_op2) != s_ul_s_op1 - s_m_s_op2) || (s_ul_s_op1 - s_m_s_op2 != s_ul_s_op1 - (ulong)s_i_s_op2) || (s_ul_s_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 16 failed"); passed = false; } } { float f_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((f_l_op1 - i_l_op2 != f_l_op1 - ui_l_op2) || (f_l_op1 - ui_l_op2 != f_l_op1 - l_l_op2) || (f_l_op1 - l_l_op2 != f_l_op1 - ul_l_op2) || (f_l_op1 - ul_l_op2 != f_l_op1 - f_l_op2) || (f_l_op1 - f_l_op2 != f_l_op1 - d_l_op2) || (f_l_op1 - d_l_op2 != f_l_op1 - (float)m_l_op2) || (f_l_op1 - (float)m_l_op2 != f_l_op1 - i_l_op2) || (f_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 17 failed"); passed = false; } if ((f_l_op1 - s_i_s_op2 != f_l_op1 - s_ui_s_op2) || (f_l_op1 - s_ui_s_op2 != f_l_op1 - s_l_s_op2) || (f_l_op1 - s_l_s_op2 != f_l_op1 - s_ul_s_op2) || (f_l_op1 - s_ul_s_op2 != f_l_op1 - s_f_s_op2) || (f_l_op1 - s_f_s_op2 != f_l_op1 - s_d_s_op2) || (f_l_op1 - s_d_s_op2 != f_l_op1 - (float)s_m_s_op2) || (f_l_op1 - (float)s_m_s_op2 != f_l_op1 - s_i_s_op2) || (f_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 18 failed"); passed = false; } if ((s_f_s_op1 - i_l_op2 != s_f_s_op1 - ui_l_op2) || (s_f_s_op1 - ui_l_op2 != s_f_s_op1 - l_l_op2) || (s_f_s_op1 - l_l_op2 != s_f_s_op1 - ul_l_op2) || (s_f_s_op1 - ul_l_op2 != s_f_s_op1 - f_l_op2) || (s_f_s_op1 - f_l_op2 != s_f_s_op1 - d_l_op2) || (s_f_s_op1 - d_l_op2 != s_f_s_op1 - (float)m_l_op2) || (s_f_s_op1 - (float)m_l_op2 != s_f_s_op1 - i_l_op2) || (s_f_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 19 failed"); passed = false; } if ((s_f_s_op1 - s_i_s_op2 != s_f_s_op1 - s_ui_s_op2) || (s_f_s_op1 - s_ui_s_op2 != s_f_s_op1 - s_l_s_op2) || (s_f_s_op1 - s_l_s_op2 != s_f_s_op1 - s_ul_s_op2) || (s_f_s_op1 - s_ul_s_op2 != s_f_s_op1 - s_f_s_op2) || (s_f_s_op1 - s_f_s_op2 != s_f_s_op1 - s_d_s_op2) || (s_f_s_op1 - s_d_s_op2 != s_f_s_op1 - (float)s_m_s_op2) || (s_f_s_op1 - (float)s_m_s_op2 != s_f_s_op1 - s_i_s_op2) || (s_f_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 20 failed"); passed = false; } } { double d_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((d_l_op1 - i_l_op2 != d_l_op1 - ui_l_op2) || (d_l_op1 - ui_l_op2 != d_l_op1 - l_l_op2) || (d_l_op1 - l_l_op2 != d_l_op1 - ul_l_op2) || (d_l_op1 - ul_l_op2 != d_l_op1 - f_l_op2) || (d_l_op1 - f_l_op2 != d_l_op1 - d_l_op2) || (d_l_op1 - d_l_op2 != d_l_op1 - (double)m_l_op2) || (d_l_op1 - (double)m_l_op2 != d_l_op1 - i_l_op2) || (d_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 21 failed"); passed = false; } if ((d_l_op1 - s_i_s_op2 != d_l_op1 - s_ui_s_op2) || (d_l_op1 - s_ui_s_op2 != d_l_op1 - s_l_s_op2) || (d_l_op1 - s_l_s_op2 != d_l_op1 - s_ul_s_op2) || (d_l_op1 - s_ul_s_op2 != d_l_op1 - s_f_s_op2) || (d_l_op1 - s_f_s_op2 != d_l_op1 - s_d_s_op2) || (d_l_op1 - s_d_s_op2 != d_l_op1 - (double)s_m_s_op2) || (d_l_op1 - (double)s_m_s_op2 != d_l_op1 - s_i_s_op2) || (d_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 22 failed"); passed = false; } if ((s_d_s_op1 - i_l_op2 != s_d_s_op1 - ui_l_op2) || (s_d_s_op1 - ui_l_op2 != s_d_s_op1 - l_l_op2) || (s_d_s_op1 - l_l_op2 != s_d_s_op1 - ul_l_op2) || (s_d_s_op1 - ul_l_op2 != s_d_s_op1 - f_l_op2) || (s_d_s_op1 - f_l_op2 != s_d_s_op1 - d_l_op2) || (s_d_s_op1 - d_l_op2 != s_d_s_op1 - (double)m_l_op2) || (s_d_s_op1 - (double)m_l_op2 != s_d_s_op1 - i_l_op2) || (s_d_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 23 failed"); passed = false; } if ((s_d_s_op1 - s_i_s_op2 != s_d_s_op1 - s_ui_s_op2) || (s_d_s_op1 - s_ui_s_op2 != s_d_s_op1 - s_l_s_op2) || (s_d_s_op1 - s_l_s_op2 != s_d_s_op1 - s_ul_s_op2) || (s_d_s_op1 - s_ul_s_op2 != s_d_s_op1 - s_f_s_op2) || (s_d_s_op1 - s_f_s_op2 != s_d_s_op1 - s_d_s_op2) || (s_d_s_op1 - s_d_s_op2 != s_d_s_op1 - (double)s_m_s_op2) || (s_d_s_op1 - (double)s_m_s_op2 != s_d_s_op1 - s_i_s_op2) || (s_d_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 24 failed"); passed = false; } } { decimal m_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((m_l_op1 - i_l_op2 != m_l_op1 - ui_l_op2) || (m_l_op1 - ui_l_op2 != m_l_op1 - l_l_op2) || (m_l_op1 - l_l_op2 != m_l_op1 - ul_l_op2) || (m_l_op1 - ul_l_op2 != m_l_op1 - (decimal)f_l_op2) || (m_l_op1 - (decimal)f_l_op2 != m_l_op1 - (decimal)d_l_op2) || (m_l_op1 - (decimal)d_l_op2 != m_l_op1 - m_l_op2) || (m_l_op1 - m_l_op2 != m_l_op1 - i_l_op2) || (m_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 25 failed"); passed = false; } if ((m_l_op1 - s_i_s_op2 != m_l_op1 - s_ui_s_op2) || (m_l_op1 - s_ui_s_op2 != m_l_op1 - s_l_s_op2) || (m_l_op1 - s_l_s_op2 != m_l_op1 - s_ul_s_op2) || (m_l_op1 - s_ul_s_op2 != m_l_op1 - (decimal)s_f_s_op2) || (m_l_op1 - (decimal)s_f_s_op2 != m_l_op1 - (decimal)s_d_s_op2) || (m_l_op1 - (decimal)s_d_s_op2 != m_l_op1 - s_m_s_op2) || (m_l_op1 - s_m_s_op2 != m_l_op1 - s_i_s_op2) || (m_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 26 failed"); passed = false; } if ((s_m_s_op1 - i_l_op2 != s_m_s_op1 - ui_l_op2) || (s_m_s_op1 - ui_l_op2 != s_m_s_op1 - l_l_op2) || (s_m_s_op1 - l_l_op2 != s_m_s_op1 - ul_l_op2) || (s_m_s_op1 - ul_l_op2 != s_m_s_op1 - (decimal)f_l_op2) || (s_m_s_op1 - (decimal)f_l_op2 != s_m_s_op1 - (decimal)d_l_op2) || (s_m_s_op1 - (decimal)d_l_op2 != s_m_s_op1 - m_l_op2) || (s_m_s_op1 - m_l_op2 != s_m_s_op1 - i_l_op2) || (s_m_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 27 failed"); passed = false; } if ((s_m_s_op1 - s_i_s_op2 != s_m_s_op1 - s_ui_s_op2) || (s_m_s_op1 - s_ui_s_op2 != s_m_s_op1 - s_l_s_op2) || (s_m_s_op1 - s_l_s_op2 != s_m_s_op1 - s_ul_s_op2) || (s_m_s_op1 - s_ul_s_op2 != s_m_s_op1 - (decimal)s_f_s_op2) || (s_m_s_op1 - (decimal)s_f_s_op2 != s_m_s_op1 - (decimal)s_d_s_op2) || (s_m_s_op1 - (decimal)s_d_s_op2 != s_m_s_op1 - s_m_s_op2) || (s_m_s_op1 - s_m_s_op2 != s_m_s_op1 - s_i_s_op2) || (s_m_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 28 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. //Testing simple math on local vars and fields - sub #pragma warning disable 0414 using System; internal class lclfldsub { //user-defined class that overloads operator - public class numHolder { private int _i_num; private uint _ui_num; private long _l_num; private ulong _ul_num; private float _f_num; private double _d_num; private decimal _m_num; public numHolder(int i_num) { _i_num = Convert.ToInt32(i_num); _ui_num = Convert.ToUInt32(i_num); _l_num = Convert.ToInt64(i_num); _ul_num = Convert.ToUInt64(i_num); _f_num = Convert.ToSingle(i_num); _d_num = Convert.ToDouble(i_num); _m_num = Convert.ToDecimal(i_num); } public static int operator -(numHolder a, int b) { return a._i_num - b; } public numHolder(uint ui_num) { _i_num = Convert.ToInt32(ui_num); _ui_num = Convert.ToUInt32(ui_num); _l_num = Convert.ToInt64(ui_num); _ul_num = Convert.ToUInt64(ui_num); _f_num = Convert.ToSingle(ui_num); _d_num = Convert.ToDouble(ui_num); _m_num = Convert.ToDecimal(ui_num); } public static uint operator -(numHolder a, uint b) { return a._ui_num - b; } public numHolder(long l_num) { _i_num = Convert.ToInt32(l_num); _ui_num = Convert.ToUInt32(l_num); _l_num = Convert.ToInt64(l_num); _ul_num = Convert.ToUInt64(l_num); _f_num = Convert.ToSingle(l_num); _d_num = Convert.ToDouble(l_num); _m_num = Convert.ToDecimal(l_num); } public static long operator -(numHolder a, long b) { return a._l_num - b; } public numHolder(ulong ul_num) { _i_num = Convert.ToInt32(ul_num); _ui_num = Convert.ToUInt32(ul_num); _l_num = Convert.ToInt64(ul_num); _ul_num = Convert.ToUInt64(ul_num); _f_num = Convert.ToSingle(ul_num); _d_num = Convert.ToDouble(ul_num); _m_num = Convert.ToDecimal(ul_num); } public static long operator -(numHolder a, ulong b) { return (long)(a._ul_num - b); } public numHolder(float f_num) { _i_num = Convert.ToInt32(f_num); _ui_num = Convert.ToUInt32(f_num); _l_num = Convert.ToInt64(f_num); _ul_num = Convert.ToUInt64(f_num); _f_num = Convert.ToSingle(f_num); _d_num = Convert.ToDouble(f_num); _m_num = Convert.ToDecimal(f_num); } public static float operator -(numHolder a, float b) { return a._f_num - b; } public numHolder(double d_num) { _i_num = Convert.ToInt32(d_num); _ui_num = Convert.ToUInt32(d_num); _l_num = Convert.ToInt64(d_num); _ul_num = Convert.ToUInt64(d_num); _f_num = Convert.ToSingle(d_num); _d_num = Convert.ToDouble(d_num); _m_num = Convert.ToDecimal(d_num); } public static double operator -(numHolder a, double b) { return a._d_num - b; } public numHolder(decimal m_num) { _i_num = Convert.ToInt32(m_num); _ui_num = Convert.ToUInt32(m_num); _l_num = Convert.ToInt64(m_num); _ul_num = Convert.ToUInt64(m_num); _f_num = Convert.ToSingle(m_num); _d_num = Convert.ToDouble(m_num); _m_num = Convert.ToDecimal(m_num); } public static int operator -(numHolder a, decimal b) { return (int)(a._m_num - b); } public static int operator -(numHolder a, numHolder b) { return a._i_num - b._i_num; } } private static int s_i_s_op1 = 16; private static uint s_ui_s_op1 = 16; private static long s_l_s_op1 = 16; private static ulong s_ul_s_op1 = 16; private static float s_f_s_op1 = 16; private static double s_d_s_op1 = 16; private static decimal s_m_s_op1 = 16; private static int s_i_s_op2 = 15; private static uint s_ui_s_op2 = 15; private static long s_l_s_op2 = 15; private static ulong s_ul_s_op2 = 15; private static float s_f_s_op2 = 15; private static double s_d_s_op2 = 15; private static decimal s_m_s_op2 = 15; private static numHolder s_nHldr_s_op2 = new numHolder(15); public static int i_f(String s) { if (s == "op1") return 16; else return 15; } public static uint ui_f(String s) { if (s == "op1") return 16; else return 15; } public static long l_f(String s) { if (s == "op1") return 16; else return 15; } public static ulong ul_f(String s) { if (s == "op1") return 16; else return 15; } public static float f_f(String s) { if (s == "op1") return 16; else return 15; } public static double d_f(String s) { if (s == "op1") return 16; else return 15; } public static decimal m_f(String s) { if (s == "op1") return 16; else return 15; } public static numHolder nHldr_f(String s) { if (s == "op1") return new numHolder(16); else return new numHolder(15); } private class CL { public int i_cl_op1 = 16; public uint ui_cl_op1 = 16; public long l_cl_op1 = 16; public ulong ul_cl_op1 = 16; public float f_cl_op1 = 16; public double d_cl_op1 = 16; public decimal m_cl_op1 = 16; public int i_cl_op2 = 15; public uint ui_cl_op2 = 15; public long l_cl_op2 = 15; public ulong ul_cl_op2 = 15; public float f_cl_op2 = 15; public double d_cl_op2 = 15; public decimal m_cl_op2 = 15; public numHolder nHldr_cl_op2 = new numHolder(15); } private struct VT { public int i_vt_op1; public uint ui_vt_op1; public long l_vt_op1; public ulong ul_vt_op1; public float f_vt_op1; public double d_vt_op1; public decimal m_vt_op1; public int i_vt_op2; public uint ui_vt_op2; public long l_vt_op2; public ulong ul_vt_op2; public float f_vt_op2; public double d_vt_op2; public decimal m_vt_op2; public numHolder nHldr_vt_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.i_vt_op1 = 16; vt1.ui_vt_op1 = 16; vt1.l_vt_op1 = 16; vt1.ul_vt_op1 = 16; vt1.f_vt_op1 = 16; vt1.d_vt_op1 = 16; vt1.m_vt_op1 = 16; vt1.i_vt_op2 = 15; vt1.ui_vt_op2 = 15; vt1.l_vt_op2 = 15; vt1.ul_vt_op2 = 15; vt1.f_vt_op2 = 15; vt1.d_vt_op2 = 15; vt1.m_vt_op2 = 15; vt1.nHldr_vt_op2 = new numHolder(15); int[] i_arr1d_op1 = { 0, 16 }; int[,] i_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; int[,,] i_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; uint[] ui_arr1d_op1 = { 0, 16 }; uint[,] ui_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; uint[,,] ui_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; long[] l_arr1d_op1 = { 0, 16 }; long[,] l_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; long[,,] l_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; ulong[] ul_arr1d_op1 = { 0, 16 }; ulong[,] ul_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; ulong[,,] ul_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; float[] f_arr1d_op1 = { 0, 16 }; float[,] f_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; float[,,] f_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; double[] d_arr1d_op1 = { 0, 16 }; double[,] d_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; double[,,] d_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; decimal[] m_arr1d_op1 = { 0, 16 }; decimal[,] m_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; decimal[,,] m_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; int[] i_arr1d_op2 = { 15, 0, 1 }; int[,] i_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; int[,,] i_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; uint[] ui_arr1d_op2 = { 15, 0, 1 }; uint[,] ui_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; uint[,,] ui_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; long[] l_arr1d_op2 = { 15, 0, 1 }; long[,] l_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; long[,,] l_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; ulong[] ul_arr1d_op2 = { 15, 0, 1 }; ulong[,] ul_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; ulong[,,] ul_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; float[] f_arr1d_op2 = { 15, 0, 1 }; float[,] f_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; float[,,] f_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; double[] d_arr1d_op2 = { 15, 0, 1 }; double[,] d_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; double[,,] d_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; decimal[] m_arr1d_op2 = { 15, 0, 1 }; decimal[,] m_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; decimal[,,] m_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; numHolder[] nHldr_arr1d_op2 = { new numHolder(15), new numHolder(0), new numHolder(1) }; numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } }; numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { int i_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((i_l_op1 - i_l_op2 != i_l_op1 - ui_l_op2) || (i_l_op1 - ui_l_op2 != i_l_op1 - l_l_op2) || (i_l_op1 - l_l_op2 != i_l_op1 - (int)ul_l_op2) || (i_l_op1 - (int)ul_l_op2 != i_l_op1 - f_l_op2) || (i_l_op1 - f_l_op2 != i_l_op1 - d_l_op2) || ((decimal)(i_l_op1 - d_l_op2) != i_l_op1 - m_l_op2) || (i_l_op1 - m_l_op2 != i_l_op1 - i_l_op2) || (i_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 1 failed"); passed = false; } if ((i_l_op1 - s_i_s_op2 != i_l_op1 - s_ui_s_op2) || (i_l_op1 - s_ui_s_op2 != i_l_op1 - s_l_s_op2) || (i_l_op1 - s_l_s_op2 != i_l_op1 - (int)s_ul_s_op2) || (i_l_op1 - (int)s_ul_s_op2 != i_l_op1 - s_f_s_op2) || (i_l_op1 - s_f_s_op2 != i_l_op1 - s_d_s_op2) || ((decimal)(i_l_op1 - s_d_s_op2) != i_l_op1 - s_m_s_op2) || (i_l_op1 - s_m_s_op2 != i_l_op1 - s_i_s_op2) || (i_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 2 failed"); passed = false; } if ((s_i_s_op1 - i_l_op2 != s_i_s_op1 - ui_l_op2) || (s_i_s_op1 - ui_l_op2 != s_i_s_op1 - l_l_op2) || (s_i_s_op1 - l_l_op2 != s_i_s_op1 - (int)ul_l_op2) || (s_i_s_op1 - (int)ul_l_op2 != s_i_s_op1 - f_l_op2) || (s_i_s_op1 - f_l_op2 != s_i_s_op1 - d_l_op2) || ((decimal)(s_i_s_op1 - d_l_op2) != s_i_s_op1 - m_l_op2) || (s_i_s_op1 - m_l_op2 != s_i_s_op1 - i_l_op2) || (s_i_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 3 failed"); passed = false; } if ((s_i_s_op1 - s_i_s_op2 != s_i_s_op1 - s_ui_s_op2) || (s_i_s_op1 - s_ui_s_op2 != s_i_s_op1 - s_l_s_op2) || (s_i_s_op1 - s_l_s_op2 != s_i_s_op1 - (int)s_ul_s_op2) || (s_i_s_op1 - (int)s_ul_s_op2 != s_i_s_op1 - s_f_s_op2) || (s_i_s_op1 - s_f_s_op2 != s_i_s_op1 - s_d_s_op2) || ((decimal)(s_i_s_op1 - s_d_s_op2) != s_i_s_op1 - s_m_s_op2) || (s_i_s_op1 - s_m_s_op2 != s_i_s_op1 - s_i_s_op2) || (s_i_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 4 failed"); passed = false; } } { uint ui_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ui_l_op1 - i_l_op2 != ui_l_op1 - ui_l_op2) || (ui_l_op1 - ui_l_op2 != ui_l_op1 - l_l_op2) || ((ulong)(ui_l_op1 - l_l_op2) != ui_l_op1 - ul_l_op2) || (ui_l_op1 - ul_l_op2 != ui_l_op1 - f_l_op2) || (ui_l_op1 - f_l_op2 != ui_l_op1 - d_l_op2) || ((decimal)(ui_l_op1 - d_l_op2) != ui_l_op1 - m_l_op2) || (ui_l_op1 - m_l_op2 != ui_l_op1 - i_l_op2) || (ui_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 5 failed"); passed = false; } if ((ui_l_op1 - s_i_s_op2 != ui_l_op1 - s_ui_s_op2) || (ui_l_op1 - s_ui_s_op2 != ui_l_op1 - s_l_s_op2) || ((ulong)(ui_l_op1 - s_l_s_op2) != ui_l_op1 - s_ul_s_op2) || (ui_l_op1 - s_ul_s_op2 != ui_l_op1 - s_f_s_op2) || (ui_l_op1 - s_f_s_op2 != ui_l_op1 - s_d_s_op2) || ((decimal)(ui_l_op1 - s_d_s_op2) != ui_l_op1 - s_m_s_op2) || (ui_l_op1 - s_m_s_op2 != ui_l_op1 - s_i_s_op2) || (ui_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 6 failed"); passed = false; } if ((s_ui_s_op1 - i_l_op2 != s_ui_s_op1 - ui_l_op2) || (s_ui_s_op1 - ui_l_op2 != s_ui_s_op1 - l_l_op2) || ((ulong)(s_ui_s_op1 - l_l_op2) != s_ui_s_op1 - ul_l_op2) || (s_ui_s_op1 - ul_l_op2 != s_ui_s_op1 - f_l_op2) || (s_ui_s_op1 - f_l_op2 != s_ui_s_op1 - d_l_op2) || ((decimal)(s_ui_s_op1 - d_l_op2) != s_ui_s_op1 - m_l_op2) || (s_ui_s_op1 - m_l_op2 != s_ui_s_op1 - i_l_op2) || (s_ui_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 7 failed"); passed = false; } if ((s_ui_s_op1 - s_i_s_op2 != s_ui_s_op1 - s_ui_s_op2) || (s_ui_s_op1 - s_ui_s_op2 != s_ui_s_op1 - s_l_s_op2) || ((ulong)(s_ui_s_op1 - s_l_s_op2) != s_ui_s_op1 - s_ul_s_op2) || (s_ui_s_op1 - s_ul_s_op2 != s_ui_s_op1 - s_f_s_op2) || (s_ui_s_op1 - s_f_s_op2 != s_ui_s_op1 - s_d_s_op2) || ((decimal)(s_ui_s_op1 - s_d_s_op2) != s_ui_s_op1 - s_m_s_op2) || (s_ui_s_op1 - s_m_s_op2 != s_ui_s_op1 - s_i_s_op2) || (s_ui_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 8 failed"); passed = false; } } { long l_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((l_l_op1 - i_l_op2 != l_l_op1 - ui_l_op2) || (l_l_op1 - ui_l_op2 != l_l_op1 - l_l_op2) || (l_l_op1 - l_l_op2 != l_l_op1 - (long)ul_l_op2) || (l_l_op1 - (long)ul_l_op2 != l_l_op1 - f_l_op2) || (l_l_op1 - f_l_op2 != l_l_op1 - d_l_op2) || ((decimal)(l_l_op1 - d_l_op2) != l_l_op1 - m_l_op2) || (l_l_op1 - m_l_op2 != l_l_op1 - i_l_op2) || (l_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 9 failed"); passed = false; } if ((l_l_op1 - s_i_s_op2 != l_l_op1 - s_ui_s_op2) || (l_l_op1 - s_ui_s_op2 != l_l_op1 - s_l_s_op2) || (l_l_op1 - s_l_s_op2 != l_l_op1 - (long)s_ul_s_op2) || (l_l_op1 - (long)s_ul_s_op2 != l_l_op1 - s_f_s_op2) || (l_l_op1 - s_f_s_op2 != l_l_op1 - s_d_s_op2) || ((decimal)(l_l_op1 - s_d_s_op2) != l_l_op1 - s_m_s_op2) || (l_l_op1 - s_m_s_op2 != l_l_op1 - s_i_s_op2) || (l_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 10 failed"); passed = false; } if ((s_l_s_op1 - i_l_op2 != s_l_s_op1 - ui_l_op2) || (s_l_s_op1 - ui_l_op2 != s_l_s_op1 - l_l_op2) || (s_l_s_op1 - l_l_op2 != s_l_s_op1 - (long)ul_l_op2) || (s_l_s_op1 - (long)ul_l_op2 != s_l_s_op1 - f_l_op2) || (s_l_s_op1 - f_l_op2 != s_l_s_op1 - d_l_op2) || ((decimal)(s_l_s_op1 - d_l_op2) != s_l_s_op1 - m_l_op2) || (s_l_s_op1 - m_l_op2 != s_l_s_op1 - i_l_op2) || (s_l_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 11 failed"); passed = false; } if ((s_l_s_op1 - s_i_s_op2 != s_l_s_op1 - s_ui_s_op2) || (s_l_s_op1 - s_ui_s_op2 != s_l_s_op1 - s_l_s_op2) || (s_l_s_op1 - s_l_s_op2 != s_l_s_op1 - (long)s_ul_s_op2) || (s_l_s_op1 - (long)s_ul_s_op2 != s_l_s_op1 - s_f_s_op2) || (s_l_s_op1 - s_f_s_op2 != s_l_s_op1 - s_d_s_op2) || ((decimal)(s_l_s_op1 - s_d_s_op2) != s_l_s_op1 - s_m_s_op2) || (s_l_s_op1 - s_m_s_op2 != s_l_s_op1 - s_i_s_op2) || (s_l_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 12 failed"); passed = false; } } { ulong ul_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ul_l_op1 - (ulong)i_l_op2 != ul_l_op1 - ui_l_op2) || (ul_l_op1 - ui_l_op2 != ul_l_op1 - (ulong)l_l_op2) || (ul_l_op1 - (ulong)l_l_op2 != ul_l_op1 - ul_l_op2) || (ul_l_op1 - ul_l_op2 != ul_l_op1 - f_l_op2) || (ul_l_op1 - f_l_op2 != ul_l_op1 - d_l_op2) || ((decimal)(ul_l_op1 - d_l_op2) != ul_l_op1 - m_l_op2) || (ul_l_op1 - m_l_op2 != ul_l_op1 - (ulong)i_l_op2) || (ul_l_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 13 failed"); passed = false; } if ((ul_l_op1 - (ulong)s_i_s_op2 != ul_l_op1 - s_ui_s_op2) || (ul_l_op1 - s_ui_s_op2 != ul_l_op1 - (ulong)s_l_s_op2) || (ul_l_op1 - (ulong)s_l_s_op2 != ul_l_op1 - s_ul_s_op2) || (ul_l_op1 - s_ul_s_op2 != ul_l_op1 - s_f_s_op2) || (ul_l_op1 - s_f_s_op2 != ul_l_op1 - s_d_s_op2) || ((decimal)(ul_l_op1 - s_d_s_op2) != ul_l_op1 - s_m_s_op2) || (ul_l_op1 - s_m_s_op2 != ul_l_op1 - (ulong)s_i_s_op2) || (ul_l_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 14 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)i_l_op2 != s_ul_s_op1 - ui_l_op2) || (s_ul_s_op1 - ui_l_op2 != s_ul_s_op1 - (ulong)l_l_op2) || (s_ul_s_op1 - (ulong)l_l_op2 != s_ul_s_op1 - ul_l_op2) || (s_ul_s_op1 - ul_l_op2 != s_ul_s_op1 - f_l_op2) || (s_ul_s_op1 - f_l_op2 != s_ul_s_op1 - d_l_op2) || ((decimal)(s_ul_s_op1 - d_l_op2) != s_ul_s_op1 - m_l_op2) || (s_ul_s_op1 - m_l_op2 != s_ul_s_op1 - (ulong)i_l_op2) || (s_ul_s_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 15 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)s_i_s_op2 != s_ul_s_op1 - s_ui_s_op2) || (s_ul_s_op1 - s_ui_s_op2 != s_ul_s_op1 - (ulong)s_l_s_op2) || (s_ul_s_op1 - (ulong)s_l_s_op2 != s_ul_s_op1 - s_ul_s_op2) || (s_ul_s_op1 - s_ul_s_op2 != s_ul_s_op1 - s_f_s_op2) || (s_ul_s_op1 - s_f_s_op2 != s_ul_s_op1 - s_d_s_op2) || ((decimal)(s_ul_s_op1 - s_d_s_op2) != s_ul_s_op1 - s_m_s_op2) || (s_ul_s_op1 - s_m_s_op2 != s_ul_s_op1 - (ulong)s_i_s_op2) || (s_ul_s_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 16 failed"); passed = false; } } { float f_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((f_l_op1 - i_l_op2 != f_l_op1 - ui_l_op2) || (f_l_op1 - ui_l_op2 != f_l_op1 - l_l_op2) || (f_l_op1 - l_l_op2 != f_l_op1 - ul_l_op2) || (f_l_op1 - ul_l_op2 != f_l_op1 - f_l_op2) || (f_l_op1 - f_l_op2 != f_l_op1 - d_l_op2) || (f_l_op1 - d_l_op2 != f_l_op1 - (float)m_l_op2) || (f_l_op1 - (float)m_l_op2 != f_l_op1 - i_l_op2) || (f_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 17 failed"); passed = false; } if ((f_l_op1 - s_i_s_op2 != f_l_op1 - s_ui_s_op2) || (f_l_op1 - s_ui_s_op2 != f_l_op1 - s_l_s_op2) || (f_l_op1 - s_l_s_op2 != f_l_op1 - s_ul_s_op2) || (f_l_op1 - s_ul_s_op2 != f_l_op1 - s_f_s_op2) || (f_l_op1 - s_f_s_op2 != f_l_op1 - s_d_s_op2) || (f_l_op1 - s_d_s_op2 != f_l_op1 - (float)s_m_s_op2) || (f_l_op1 - (float)s_m_s_op2 != f_l_op1 - s_i_s_op2) || (f_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 18 failed"); passed = false; } if ((s_f_s_op1 - i_l_op2 != s_f_s_op1 - ui_l_op2) || (s_f_s_op1 - ui_l_op2 != s_f_s_op1 - l_l_op2) || (s_f_s_op1 - l_l_op2 != s_f_s_op1 - ul_l_op2) || (s_f_s_op1 - ul_l_op2 != s_f_s_op1 - f_l_op2) || (s_f_s_op1 - f_l_op2 != s_f_s_op1 - d_l_op2) || (s_f_s_op1 - d_l_op2 != s_f_s_op1 - (float)m_l_op2) || (s_f_s_op1 - (float)m_l_op2 != s_f_s_op1 - i_l_op2) || (s_f_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 19 failed"); passed = false; } if ((s_f_s_op1 - s_i_s_op2 != s_f_s_op1 - s_ui_s_op2) || (s_f_s_op1 - s_ui_s_op2 != s_f_s_op1 - s_l_s_op2) || (s_f_s_op1 - s_l_s_op2 != s_f_s_op1 - s_ul_s_op2) || (s_f_s_op1 - s_ul_s_op2 != s_f_s_op1 - s_f_s_op2) || (s_f_s_op1 - s_f_s_op2 != s_f_s_op1 - s_d_s_op2) || (s_f_s_op1 - s_d_s_op2 != s_f_s_op1 - (float)s_m_s_op2) || (s_f_s_op1 - (float)s_m_s_op2 != s_f_s_op1 - s_i_s_op2) || (s_f_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 20 failed"); passed = false; } } { double d_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((d_l_op1 - i_l_op2 != d_l_op1 - ui_l_op2) || (d_l_op1 - ui_l_op2 != d_l_op1 - l_l_op2) || (d_l_op1 - l_l_op2 != d_l_op1 - ul_l_op2) || (d_l_op1 - ul_l_op2 != d_l_op1 - f_l_op2) || (d_l_op1 - f_l_op2 != d_l_op1 - d_l_op2) || (d_l_op1 - d_l_op2 != d_l_op1 - (double)m_l_op2) || (d_l_op1 - (double)m_l_op2 != d_l_op1 - i_l_op2) || (d_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 21 failed"); passed = false; } if ((d_l_op1 - s_i_s_op2 != d_l_op1 - s_ui_s_op2) || (d_l_op1 - s_ui_s_op2 != d_l_op1 - s_l_s_op2) || (d_l_op1 - s_l_s_op2 != d_l_op1 - s_ul_s_op2) || (d_l_op1 - s_ul_s_op2 != d_l_op1 - s_f_s_op2) || (d_l_op1 - s_f_s_op2 != d_l_op1 - s_d_s_op2) || (d_l_op1 - s_d_s_op2 != d_l_op1 - (double)s_m_s_op2) || (d_l_op1 - (double)s_m_s_op2 != d_l_op1 - s_i_s_op2) || (d_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 22 failed"); passed = false; } if ((s_d_s_op1 - i_l_op2 != s_d_s_op1 - ui_l_op2) || (s_d_s_op1 - ui_l_op2 != s_d_s_op1 - l_l_op2) || (s_d_s_op1 - l_l_op2 != s_d_s_op1 - ul_l_op2) || (s_d_s_op1 - ul_l_op2 != s_d_s_op1 - f_l_op2) || (s_d_s_op1 - f_l_op2 != s_d_s_op1 - d_l_op2) || (s_d_s_op1 - d_l_op2 != s_d_s_op1 - (double)m_l_op2) || (s_d_s_op1 - (double)m_l_op2 != s_d_s_op1 - i_l_op2) || (s_d_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 23 failed"); passed = false; } if ((s_d_s_op1 - s_i_s_op2 != s_d_s_op1 - s_ui_s_op2) || (s_d_s_op1 - s_ui_s_op2 != s_d_s_op1 - s_l_s_op2) || (s_d_s_op1 - s_l_s_op2 != s_d_s_op1 - s_ul_s_op2) || (s_d_s_op1 - s_ul_s_op2 != s_d_s_op1 - s_f_s_op2) || (s_d_s_op1 - s_f_s_op2 != s_d_s_op1 - s_d_s_op2) || (s_d_s_op1 - s_d_s_op2 != s_d_s_op1 - (double)s_m_s_op2) || (s_d_s_op1 - (double)s_m_s_op2 != s_d_s_op1 - s_i_s_op2) || (s_d_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 24 failed"); passed = false; } } { decimal m_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((m_l_op1 - i_l_op2 != m_l_op1 - ui_l_op2) || (m_l_op1 - ui_l_op2 != m_l_op1 - l_l_op2) || (m_l_op1 - l_l_op2 != m_l_op1 - ul_l_op2) || (m_l_op1 - ul_l_op2 != m_l_op1 - (decimal)f_l_op2) || (m_l_op1 - (decimal)f_l_op2 != m_l_op1 - (decimal)d_l_op2) || (m_l_op1 - (decimal)d_l_op2 != m_l_op1 - m_l_op2) || (m_l_op1 - m_l_op2 != m_l_op1 - i_l_op2) || (m_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 25 failed"); passed = false; } if ((m_l_op1 - s_i_s_op2 != m_l_op1 - s_ui_s_op2) || (m_l_op1 - s_ui_s_op2 != m_l_op1 - s_l_s_op2) || (m_l_op1 - s_l_s_op2 != m_l_op1 - s_ul_s_op2) || (m_l_op1 - s_ul_s_op2 != m_l_op1 - (decimal)s_f_s_op2) || (m_l_op1 - (decimal)s_f_s_op2 != m_l_op1 - (decimal)s_d_s_op2) || (m_l_op1 - (decimal)s_d_s_op2 != m_l_op1 - s_m_s_op2) || (m_l_op1 - s_m_s_op2 != m_l_op1 - s_i_s_op2) || (m_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 26 failed"); passed = false; } if ((s_m_s_op1 - i_l_op2 != s_m_s_op1 - ui_l_op2) || (s_m_s_op1 - ui_l_op2 != s_m_s_op1 - l_l_op2) || (s_m_s_op1 - l_l_op2 != s_m_s_op1 - ul_l_op2) || (s_m_s_op1 - ul_l_op2 != s_m_s_op1 - (decimal)f_l_op2) || (s_m_s_op1 - (decimal)f_l_op2 != s_m_s_op1 - (decimal)d_l_op2) || (s_m_s_op1 - (decimal)d_l_op2 != s_m_s_op1 - m_l_op2) || (s_m_s_op1 - m_l_op2 != s_m_s_op1 - i_l_op2) || (s_m_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 27 failed"); passed = false; } if ((s_m_s_op1 - s_i_s_op2 != s_m_s_op1 - s_ui_s_op2) || (s_m_s_op1 - s_ui_s_op2 != s_m_s_op1 - s_l_s_op2) || (s_m_s_op1 - s_l_s_op2 != s_m_s_op1 - s_ul_s_op2) || (s_m_s_op1 - s_ul_s_op2 != s_m_s_op1 - (decimal)s_f_s_op2) || (s_m_s_op1 - (decimal)s_f_s_op2 != s_m_s_op1 - (decimal)s_d_s_op2) || (s_m_s_op1 - (decimal)s_d_s_op2 != s_m_s_op1 - s_m_s_op2) || (s_m_s_op1 - s_m_s_op2 != s_m_s_op1 - s_i_s_op2) || (s_m_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 28 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.CodeDom/src/System/CodeDom/CodeCastExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.CodeDom { public class CodeCastExpression : CodeExpression { private CodeTypeReference _targetType; public CodeCastExpression() { } public CodeCastExpression(CodeTypeReference targetType, CodeExpression expression) { TargetType = targetType; Expression = expression; } public CodeCastExpression(string targetType, CodeExpression expression) { TargetType = new CodeTypeReference(targetType); Expression = expression; } public CodeCastExpression(Type targetType, CodeExpression expression) { TargetType = new CodeTypeReference(targetType); Expression = expression; } public CodeTypeReference TargetType { get => _targetType ?? (_targetType = new CodeTypeReference("")); set => _targetType = value; } public CodeExpression Expression { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.CodeDom { public class CodeCastExpression : CodeExpression { private CodeTypeReference _targetType; public CodeCastExpression() { } public CodeCastExpression(CodeTypeReference targetType, CodeExpression expression) { TargetType = targetType; Expression = expression; } public CodeCastExpression(string targetType, CodeExpression expression) { TargetType = new CodeTypeReference(targetType); Expression = expression; } public CodeCastExpression(Type targetType, CodeExpression expression) { TargetType = new CodeTypeReference(targetType); Expression = expression; } public CodeTypeReference TargetType { get => _targetType ?? (_targetType = new CodeTypeReference("")); set => _targetType = value; } public CodeExpression Expression { get; set; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/Common/src/Interop/Windows/OleAut32/Interop.SysFreeString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class OleAut32 { [GeneratedDllImport(Libraries.OleAut32)] internal static partial void SysFreeString(IntPtr bstr); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class OleAut32 { [GeneratedDllImport(Libraries.OleAut32)] internal static partial void SysFreeString(IntPtr bstr); } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocket.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { public sealed partial class ClientWebSocket : WebSocket { /// <summary>This is really an InternalState value, but Interlocked doesn't support operations on values of enum types.</summary> private int _state; private WebSocketHandle? _innerWebSocket; public ClientWebSocket() { _state = (int)InternalState.Created; Options = WebSocketHandle.CreateDefaultOptions(); } public ClientWebSocketOptions Options { get; } public override WebSocketCloseStatus? CloseStatus => _innerWebSocket?.WebSocket?.CloseStatus; public override string? CloseStatusDescription => _innerWebSocket?.WebSocket?.CloseStatusDescription; public override string? SubProtocol => _innerWebSocket?.WebSocket?.SubProtocol; public override WebSocketState State { get { // state == Connected or Disposed if (_innerWebSocket != null) { return _innerWebSocket.State; } switch ((InternalState)_state) { case InternalState.Created: return WebSocketState.None; case InternalState.Connecting: return WebSocketState.Connecting; default: // We only get here if disposed before connecting Debug.Assert((InternalState)_state == InternalState.Disposed); return WebSocketState.Closed; } } } public Task ConnectAsync(Uri uri!!, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { throw new ArgumentException(SR.net_uri_NotAbsolute, nameof(uri)); } if (uri.Scheme != UriScheme.Ws && uri.Scheme != UriScheme.Wss) { throw new ArgumentException(SR.net_WebSockets_Scheme, nameof(uri)); } // Check that we have not started already. switch ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connecting, (int)InternalState.Created)) { case InternalState.Disposed: throw new ObjectDisposedException(GetType().FullName); case InternalState.Created: break; default: throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted); } Options.SetToReadOnly(); return ConnectAsyncCore(uri, cancellationToken); } private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken) { _innerWebSocket = new WebSocketHandle(); try { await _innerWebSocket.ConnectAsync(uri, cancellationToken, Options).ConfigureAwait(false); } catch { Dispose(); throw; } if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting) { Debug.Assert(_state == (int)InternalState.Disposed); throw new ObjectDisposedException(GetType().FullName); } } public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => ConnectedWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public override ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => ConnectedWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) => ConnectedWebSocket.ReceiveAsync(buffer, cancellationToken); public override ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken cancellationToken) => ConnectedWebSocket.ReceiveAsync(buffer, cancellationToken); public override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) => ConnectedWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) => ConnectedWebSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); private WebSocket ConnectedWebSocket { get { if ((InternalState)_state == InternalState.Disposed) { throw new ObjectDisposedException(GetType().FullName); } else if ((InternalState)_state != InternalState.Connected) { throw new InvalidOperationException(SR.net_WebSockets_NotConnected); } Debug.Assert(_innerWebSocket != null); Debug.Assert(_innerWebSocket.WebSocket != null); return _innerWebSocket.WebSocket; } } public override void Abort() { if ((InternalState)_state != InternalState.Disposed) { _innerWebSocket?.Abort(); Dispose(); } } public override void Dispose() { if ((InternalState)Interlocked.Exchange(ref _state, (int)InternalState.Disposed) != InternalState.Disposed) { _innerWebSocket?.Dispose(); } } private enum InternalState { Created = 0, Connecting = 1, Connected = 2, Disposed = 3 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { public sealed partial class ClientWebSocket : WebSocket { /// <summary>This is really an InternalState value, but Interlocked doesn't support operations on values of enum types.</summary> private int _state; private WebSocketHandle? _innerWebSocket; public ClientWebSocket() { _state = (int)InternalState.Created; Options = WebSocketHandle.CreateDefaultOptions(); } public ClientWebSocketOptions Options { get; } public override WebSocketCloseStatus? CloseStatus => _innerWebSocket?.WebSocket?.CloseStatus; public override string? CloseStatusDescription => _innerWebSocket?.WebSocket?.CloseStatusDescription; public override string? SubProtocol => _innerWebSocket?.WebSocket?.SubProtocol; public override WebSocketState State { get { // state == Connected or Disposed if (_innerWebSocket != null) { return _innerWebSocket.State; } switch ((InternalState)_state) { case InternalState.Created: return WebSocketState.None; case InternalState.Connecting: return WebSocketState.Connecting; default: // We only get here if disposed before connecting Debug.Assert((InternalState)_state == InternalState.Disposed); return WebSocketState.Closed; } } } public Task ConnectAsync(Uri uri!!, CancellationToken cancellationToken) { if (!uri.IsAbsoluteUri) { throw new ArgumentException(SR.net_uri_NotAbsolute, nameof(uri)); } if (uri.Scheme != UriScheme.Ws && uri.Scheme != UriScheme.Wss) { throw new ArgumentException(SR.net_WebSockets_Scheme, nameof(uri)); } // Check that we have not started already. switch ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connecting, (int)InternalState.Created)) { case InternalState.Disposed: throw new ObjectDisposedException(GetType().FullName); case InternalState.Created: break; default: throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted); } Options.SetToReadOnly(); return ConnectAsyncCore(uri, cancellationToken); } private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken) { _innerWebSocket = new WebSocketHandle(); try { await _innerWebSocket.ConnectAsync(uri, cancellationToken, Options).ConfigureAwait(false); } catch { Dispose(); throw; } if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting) { Debug.Assert(_state == (int)InternalState.Disposed); throw new ObjectDisposedException(GetType().FullName); } } public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => ConnectedWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public override ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) => ConnectedWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) => ConnectedWebSocket.ReceiveAsync(buffer, cancellationToken); public override ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken cancellationToken) => ConnectedWebSocket.ReceiveAsync(buffer, cancellationToken); public override Task CloseAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) => ConnectedWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string? statusDescription, CancellationToken cancellationToken) => ConnectedWebSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); private WebSocket ConnectedWebSocket { get { if ((InternalState)_state == InternalState.Disposed) { throw new ObjectDisposedException(GetType().FullName); } else if ((InternalState)_state != InternalState.Connected) { throw new InvalidOperationException(SR.net_WebSockets_NotConnected); } Debug.Assert(_innerWebSocket != null); Debug.Assert(_innerWebSocket.WebSocket != null); return _innerWebSocket.WebSocket; } } public override void Abort() { if ((InternalState)_state != InternalState.Disposed) { _innerWebSocket?.Abort(); Dispose(); } } public override void Dispose() { if ((InternalState)Interlocked.Exchange(ref _state, (int)InternalState.Disposed) != InternalState.Disposed) { _innerWebSocket?.Dispose(); } } private enum InternalState { Created = 0, Connecting = 1, Connected = 2, Disposed = 3 } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Reflection.Emit/tests/Utilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using Xunit; namespace System.Reflection.Emit.Tests { public class EmptyNonGenericClass { } public class EmptyGenericClass<T> { } public sealed class SealedClass { } public static class StaticClass { } public struct EmptyNonGenericStruct { } public struct EmptyGenericStruct<T> { } public enum EmptyEnum { } public delegate EventHandler BasicDelegate(); public interface EmptyNonGenericInterface1 { } public interface EmptyNonGenericInterface2 { } public interface EmptyGenericInterface<T> { } public class EmptyAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class IntAllAttribute : Attribute { public int _i; public IntAllAttribute(int i) { _i = i; } } public static class TypeExtensions { public static Type AsType(this Type type) { return type; } } public static class Helpers { public const BindingFlags AllFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public static AssemblyBuilder DynamicAssembly(string name = "TestAssembly", AssemblyBuilderAccess access = AssemblyBuilderAccess.Run) { AssemblyName assemblyName = new AssemblyName(name); return AssemblyBuilder.DefineDynamicAssembly(assemblyName, access); } public static ModuleBuilder DynamicModule(string assemblyName = "TestAssembly", string moduleName = "TestModule") { return DynamicAssembly(assemblyName).DefineDynamicModule(moduleName); } public static TypeBuilder DynamicType(TypeAttributes attributes, string assemblyName = "TestAssembly", string moduleName = "TestModule", string typeName = "TestType", Type? baseType = null) { if (baseType is null) { return DynamicModule(assemblyName, moduleName).DefineType(typeName, attributes); } else { return DynamicModule(assemblyName, moduleName).DefineType(typeName, attributes, baseType); } } public static EnumBuilder DynamicEnum(TypeAttributes visibility, Type underlyingType, string enumName = "TestEnum", string assemblyName = "TestAssembly", string moduleName = "TestModule") { return DynamicModule(assemblyName, moduleName).DefineEnum(enumName, visibility, underlyingType); } public static void VerifyType(TypeBuilder type, Module module, TypeBuilder declaringType, string name, TypeAttributes attributes, Type baseType, int size, PackingSize packingSize, Type[] implementedInterfaces) { Assert.Equal(module, type.Module); Assert.Equal(module.Assembly, type.Assembly); Assert.Equal(name, type.Name); if (declaringType == null) { Assert.Equal(GetFullName(name), type.FullName); } else { Assert.Equal(GetFullName(declaringType.Name) + "+" + GetFullName(type.Name), type.FullName); } Assert.Equal(attributes, type.Attributes); Assert.Equal(declaringType?.AsType(), type.DeclaringType); Assert.Equal(baseType, type.BaseType); Assert.Equal(size, type.Size); Assert.Equal(packingSize, type.PackingSize); Assert.Equal(implementedInterfaces ?? new Type[0], type.GetInterfaces()); if (declaringType == null && !type.IsInterface && (implementedInterfaces == null || implementedInterfaces.Length == 0)) { Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal(createdType, module.GetType(name, false, false)); Assert.Equal(createdType, module.GetType(name, true, false)); Assert.Equal(type.AsType().GetNestedTypes(AllFlags), createdType.GetNestedTypes(AllFlags)); Assert.Equal(type.AsType().GetNestedType(name, AllFlags), createdType.GetNestedType(name, AllFlags)); // [ActiveIssue("https://github.com/dotnet/runtime/issues/18231", TestPlatforms.AnyUnix)] // Assert.Equal(createdType, module.GetType(name, true, true)); // Assert.Equal(createdType, module.GetType(name.ToLowerInvariant(), true, true)); // Assert.Equal(createdType, module.GetType(name.ToUpperInvariant(), true, true)); } } public static void VerifyConstructor(ConstructorBuilder constructor, TypeBuilder type, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) { string expectedName = (attributes & MethodAttributes.Static) != 0 ? ConstructorInfo.TypeConstructorName : ConstructorInfo.ConstructorName; Assert.Equal(expectedName, constructor.Name); Assert.Equal(attributes | MethodAttributes.SpecialName, constructor.Attributes); Assert.Equal(CallingConventions.Standard, constructor.CallingConvention); Assert.Equal(type.AsType(), constructor.DeclaringType); Assert.Equal(type.Module, constructor.Module); Assert.Equal(MethodImplAttributes.IL, constructor.MethodImplementationFlags); Assert.Throws<NotSupportedException>(() => constructor.Invoke(null)); Assert.Throws<NotSupportedException>(() => constructor.Invoke(null, null)); Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal(type.AsType().GetConstructors(AllFlags), createdType.GetConstructors(AllFlags)); Assert.Equal(type.AsType().GetConstructor(parameterTypes), createdType.GetConstructor(parameterTypes)); ConstructorInfo createdConstructor = createdType.GetConstructors(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Single(ctor => ctor.IsStatic == constructor.IsStatic); CallingConventions expectedCallingConvention = CallingConventions.Standard; if ((callingConvention & CallingConventions.VarArgs) != 0) { expectedCallingConvention = CallingConventions.VarArgs; } if ((attributes & MethodAttributes.Static) == 0) { expectedCallingConvention |= CallingConventions.HasThis; } MethodAttributes expectedAttributes = attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; expectedAttributes &= ~MethodAttributes.RequireSecObject; Assert.Equal(expectedName, constructor.Name); Assert.Equal(expectedAttributes, createdConstructor.Attributes); Assert.Equal(expectedCallingConvention, createdConstructor.CallingConvention); Assert.Equal(createdType, createdConstructor.DeclaringType); Assert.Equal(MethodImplAttributes.IL, constructor.MethodImplementationFlags); } public static string GetFullName(string name) { int nullTerminatorIndex = name.IndexOf('\0'); if (nullTerminatorIndex >= 0) { return name.Substring(0, nullTerminatorIndex); } return name; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using Xunit; namespace System.Reflection.Emit.Tests { public class EmptyNonGenericClass { } public class EmptyGenericClass<T> { } public sealed class SealedClass { } public static class StaticClass { } public struct EmptyNonGenericStruct { } public struct EmptyGenericStruct<T> { } public enum EmptyEnum { } public delegate EventHandler BasicDelegate(); public interface EmptyNonGenericInterface1 { } public interface EmptyNonGenericInterface2 { } public interface EmptyGenericInterface<T> { } public class EmptyAttribute : Attribute { } [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class IntAllAttribute : Attribute { public int _i; public IntAllAttribute(int i) { _i = i; } } public static class TypeExtensions { public static Type AsType(this Type type) { return type; } } public static class Helpers { public const BindingFlags AllFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public static AssemblyBuilder DynamicAssembly(string name = "TestAssembly", AssemblyBuilderAccess access = AssemblyBuilderAccess.Run) { AssemblyName assemblyName = new AssemblyName(name); return AssemblyBuilder.DefineDynamicAssembly(assemblyName, access); } public static ModuleBuilder DynamicModule(string assemblyName = "TestAssembly", string moduleName = "TestModule") { return DynamicAssembly(assemblyName).DefineDynamicModule(moduleName); } public static TypeBuilder DynamicType(TypeAttributes attributes, string assemblyName = "TestAssembly", string moduleName = "TestModule", string typeName = "TestType", Type? baseType = null) { if (baseType is null) { return DynamicModule(assemblyName, moduleName).DefineType(typeName, attributes); } else { return DynamicModule(assemblyName, moduleName).DefineType(typeName, attributes, baseType); } } public static EnumBuilder DynamicEnum(TypeAttributes visibility, Type underlyingType, string enumName = "TestEnum", string assemblyName = "TestAssembly", string moduleName = "TestModule") { return DynamicModule(assemblyName, moduleName).DefineEnum(enumName, visibility, underlyingType); } public static void VerifyType(TypeBuilder type, Module module, TypeBuilder declaringType, string name, TypeAttributes attributes, Type baseType, int size, PackingSize packingSize, Type[] implementedInterfaces) { Assert.Equal(module, type.Module); Assert.Equal(module.Assembly, type.Assembly); Assert.Equal(name, type.Name); if (declaringType == null) { Assert.Equal(GetFullName(name), type.FullName); } else { Assert.Equal(GetFullName(declaringType.Name) + "+" + GetFullName(type.Name), type.FullName); } Assert.Equal(attributes, type.Attributes); Assert.Equal(declaringType?.AsType(), type.DeclaringType); Assert.Equal(baseType, type.BaseType); Assert.Equal(size, type.Size); Assert.Equal(packingSize, type.PackingSize); Assert.Equal(implementedInterfaces ?? new Type[0], type.GetInterfaces()); if (declaringType == null && !type.IsInterface && (implementedInterfaces == null || implementedInterfaces.Length == 0)) { Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal(createdType, module.GetType(name, false, false)); Assert.Equal(createdType, module.GetType(name, true, false)); Assert.Equal(type.AsType().GetNestedTypes(AllFlags), createdType.GetNestedTypes(AllFlags)); Assert.Equal(type.AsType().GetNestedType(name, AllFlags), createdType.GetNestedType(name, AllFlags)); // [ActiveIssue("https://github.com/dotnet/runtime/issues/18231", TestPlatforms.AnyUnix)] // Assert.Equal(createdType, module.GetType(name, true, true)); // Assert.Equal(createdType, module.GetType(name.ToLowerInvariant(), true, true)); // Assert.Equal(createdType, module.GetType(name.ToUpperInvariant(), true, true)); } } public static void VerifyConstructor(ConstructorBuilder constructor, TypeBuilder type, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) { string expectedName = (attributes & MethodAttributes.Static) != 0 ? ConstructorInfo.TypeConstructorName : ConstructorInfo.ConstructorName; Assert.Equal(expectedName, constructor.Name); Assert.Equal(attributes | MethodAttributes.SpecialName, constructor.Attributes); Assert.Equal(CallingConventions.Standard, constructor.CallingConvention); Assert.Equal(type.AsType(), constructor.DeclaringType); Assert.Equal(type.Module, constructor.Module); Assert.Equal(MethodImplAttributes.IL, constructor.MethodImplementationFlags); Assert.Throws<NotSupportedException>(() => constructor.Invoke(null)); Assert.Throws<NotSupportedException>(() => constructor.Invoke(null, null)); Type createdType = type.CreateTypeInfo().AsType(); Assert.Equal(type.AsType().GetConstructors(AllFlags), createdType.GetConstructors(AllFlags)); Assert.Equal(type.AsType().GetConstructor(parameterTypes), createdType.GetConstructor(parameterTypes)); ConstructorInfo createdConstructor = createdType.GetConstructors(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Single(ctor => ctor.IsStatic == constructor.IsStatic); CallingConventions expectedCallingConvention = CallingConventions.Standard; if ((callingConvention & CallingConventions.VarArgs) != 0) { expectedCallingConvention = CallingConventions.VarArgs; } if ((attributes & MethodAttributes.Static) == 0) { expectedCallingConvention |= CallingConventions.HasThis; } MethodAttributes expectedAttributes = attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; expectedAttributes &= ~MethodAttributes.RequireSecObject; Assert.Equal(expectedName, constructor.Name); Assert.Equal(expectedAttributes, createdConstructor.Attributes); Assert.Equal(expectedCallingConvention, createdConstructor.CallingConvention); Assert.Equal(createdType, createdConstructor.DeclaringType); Assert.Equal(MethodImplAttributes.IL, constructor.MethodImplementationFlags); } public static string GetFullName(string name) { int nullTerminatorIndex = name.IndexOf('\0'); if (nullTerminatorIndex >= 0) { return name.Substring(0, nullTerminatorIndex); } return name; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/CodeGenBringUpTests/FPSub_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="FPSub.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="FPSub.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Net.HttpListener/tests/TrimmingTests/CookieExtensionsTest.Clone.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net; using System.Threading.Tasks; namespace CookieExtensionsTest { /// <summary> /// Tests that the System.Net.CookieExtensions.Clone() /// method works as expected when used in a trimmed application. /// </summary> internal class Program { static async Task<int> Main(string[] args) { var helper = new TestHelper(); HttpListenerResponse response = await helper.GetResponse(); var cookie = new Cookie("name", "value"); response.SetCookie(cookie); // Cookies are cloned. cookie.Value = "value3"; if (response.Cookies[0].Value != "value") { return -1; } return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Net; using System.Threading.Tasks; namespace CookieExtensionsTest { /// <summary> /// Tests that the System.Net.CookieExtensions.Clone() /// method works as expected when used in a trimmed application. /// </summary> internal class Program { static async Task<int> Main(string[] args) { var helper = new TestHelper(); HttpListenerResponse response = await helper.GetResponse(); var cookie = new Cookie("name", "value"); response.SetCookie(cookie); // Cookies are cloned. cookie.Value = "value3"; if (response.Cookies[0].Value != "value") { return -1; } return 100; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Regression/CLR-x86-JIT/V2.0-RTM/b369916/b369916.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // //((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) //permutations for ((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) //((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) //(((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) //(((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) //((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) //((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e+((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))+s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))+s.e) //(s.e+((s.a+(s.b*s.c))-(s.c*s.d))) //(s.e+(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) //(((s.a+(s.b*s.c))-(s.c*s.d))+(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) //(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) //s.e //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) //(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) //(s.g+((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.f+(s.e*s.f))-(s.g*s.h))+s.g) //s.g //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(((s.f+(s.e*s.f))-(s.g*s.h))+s.g) //(s.g+((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) //((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) //((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) //((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) //(s.a+((s.h+(s.f+s.g))-(s.p*s.q))) //(((s.h+(s.f+s.g))-(s.p*s.q))+s.a) //s.a //((s.h+(s.f+s.g))-(s.p*s.q)) //(s.h+(s.f+s.g)) //((s.f+s.g)+s.h) //s.h //(s.f+s.g) //(s.g+s.f) //s.f //s.g //(s.g+s.f) //(s.f+s.g) //(s.f+(s.g+s.h)) //(s.g+(s.f+s.h)) //(s.g+s.h) //(s.h+s.g) //s.g //s.h //(s.h+s.g) //(s.g+s.h) //(s.f+s.h) //(s.h+s.f) //s.f //s.h //(s.h+s.f) //(s.f+s.h) //((s.f+s.g)+s.h) //(s.h+(s.f+s.g)) //(s.p*s.q) //(s.q*s.p) //s.p //s.q //(s.q*s.p) //(s.p*s.q) //(s.h+(s.f+s.g)) //((s.h+(s.f+s.g))-(s.p*s.q)) //(((s.h+(s.f+s.g))-(s.p*s.q))+s.a) //(s.a+((s.h+(s.f+s.g))-(s.p*s.q))) //(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) //((s.a+s.b)+s.g) //(s.g+(s.a+s.b)) //(s.a+s.b) //(s.b+s.a) //s.a //s.b //(s.b+s.a) //(s.a+s.b) //s.g //(s.a+(s.b+s.g)) //(s.b+(s.a+s.g)) //(s.b+s.g) //(s.g+s.b) //s.b //s.g //(s.g+s.b) //(s.b+s.g) //(s.a+s.g) //(s.g+s.a) //s.a //s.g //(s.g+s.a) //(s.a+s.g) //(s.g+(s.a+s.b)) //((s.a+s.b)+s.g) //((s.c+s.b)*s.k) //(s.k*(s.c+s.b)) //(s.c+s.b) //(s.b+s.c) //s.c //s.b //(s.b+s.c) //(s.c+s.b) //s.k //(s.k*(s.c+s.b)) //((s.c+s.b)*s.k) //((s.a+s.b)+s.g) //(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) //((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) //((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) //(((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) //(((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) //(((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) //((s.b*s.b)+s.g) //(s.g+(s.b*s.b)) //(s.b*s.b) //(s.b*s.b) //s.b //s.b //(s.b*s.b) //(s.b*s.b) //s.g //(s.g+(s.b*s.b)) //((s.b*s.b)+s.g) //((s.c+s.b)*s.k) //(s.k*(s.c+s.b)) //(s.c+s.b) //(s.b+s.c) //s.c //s.b //(s.b+s.c) //(s.c+s.b) //s.k //(s.k*(s.c+s.b)) //((s.c+s.b)*s.k) //((s.b*s.b)+s.g) //(((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) //(((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) //((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) namespace CseTest { using System; public class Test_Main { static int Main() { int ret = 100; class_s s = new class_s(); s.e = return_int(false, 47); s.a = return_int(false, 16); s.b = return_int(false, -39); s.c = return_int(false, 27); s.d = return_int(false, 61); s.f = return_int(false, 32); s.g = return_int(false, 4); s.h = return_int(false, 99); s.p = return_int(false, 122); s.q = return_int(false, -14); s.k = return_int(false, 124); int v; #if LOOP do { #endif v = ((((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))) - (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != 2596789) { Console.WriteLine("test0: for ((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } v = (((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))); if (v != 2599802) { Console.WriteLine("test1: for (((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))) + ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != 2599802) { Console.WriteLine("test2: for (((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } s.d = return_int(false, 33); v = ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -94781) { Console.WriteLine("test3: for ((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))); if (v != -93637) { Console.WriteLine("test4: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -93637) { Console.WriteLine("test5: for ((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -91756) { Console.WriteLine("test6: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90616) { Console.WriteLine("test7: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90616) { Console.WriteLine("test8: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1928) { Console.WriteLine("test9: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP do { #endif v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test10: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1037) { Console.WriteLine("test11: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test12: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test13: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test14: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test15: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1037) { Console.WriteLine("test16: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test17: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test18: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test19: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test20: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test21: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test22: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v == 0); #endif v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1928) { Console.WriteLine("test23: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90616) { Console.WriteLine("test24: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90616) { Console.WriteLine("test25: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 1140) { Console.WriteLine("test26: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP do { #endif v = (s.f + (s.e * s.f)); if (v != 1536) { Console.WriteLine("test27: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1536) { Console.WriteLine("test28: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 1504) { Console.WriteLine("test29: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 1504) { Console.WriteLine("test30: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 1504) { Console.WriteLine("test31: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 1504) { Console.WriteLine("test32: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1536) { Console.WriteLine("test33: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1536) { Console.WriteLine("test34: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test35: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } #if LOOP do { #endif v = (s.h * s.g); if (v != 396) { Console.WriteLine("test36: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test37: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test38: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1536) { Console.WriteLine("test39: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 1140) { Console.WriteLine("test40: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90616) { Console.WriteLine("test41: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -91756) { Console.WriteLine("test42: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -1881) { Console.WriteLine("test43: for (s.e+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + s.e); if (v != -1881) { Console.WriteLine("test44: for (((s.a+(s.b*s.c))-(s.c*s.d))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1928) { Console.WriteLine("test45: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v==0); #endif v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test46: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v==0); #endif v = ((s.b * s.c) + s.a); if (v != -1037) { Console.WriteLine("test47: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 11); v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test48: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test49: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test50: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test51: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test52: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } #if TRY try { #endif v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test53: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test54: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test55: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test56: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test57: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } #if TRY throw new Exception("Test exception"); } catch (System.Exception) { Console.WriteLine("In catch"); #endif s.q = return_int(false, 33); #if TRY } #endif v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test58: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test59: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + s.e); if (v != -1886) { Console.WriteLine("test60: for (((s.a+(s.b*s.c))-(s.c*s.d))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -1886) { Console.WriteLine("test61: for (s.e+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + (((s.a + (s.b * s.c)) - (s.c * s.d)) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != -93877) { Console.WriteLine("test62: for (s.e+(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + (s.e + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != -93877) { Console.WriteLine("test63: for (((s.a+(s.b*s.c))-(s.c*s.d))+(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -93924) { Console.WriteLine("test64: for (((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -93924) { Console.WriteLine("test65: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test66: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test67: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test68: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test69: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test70: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test71: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test72: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test73: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test74: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test75: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test76: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test77: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test78: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } s.k = return_int(false, -3); v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test79: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test80: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -91991) { Console.WriteLine("test81: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test82: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90851) { Console.WriteLine("test83: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test84: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } s.f = return_int(false, 42); v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test85: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test86: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test87: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test88: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test89: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test90: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test91: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test92: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test93: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test94: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } s.f = return_int(false, 58); v = (s.d * s.c); if (v != 891) { Console.WriteLine("test95: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test96: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test97: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test98: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90851) { Console.WriteLine("test99: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test100: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 2388) { Console.WriteLine("test101: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test102: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 2784) { Console.WriteLine("test103: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 2726) { Console.WriteLine("test104: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 2726) { Console.WriteLine("test105: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 2726) { Console.WriteLine("test106: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 2726) { Console.WriteLine("test107: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 2784) { Console.WriteLine("test108: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test109: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test110: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test111: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test112: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test113: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test114: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 2388) { Console.WriteLine("test115: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test116: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -93239) { Console.WriteLine("test117: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -95172) { Console.WriteLine("test118: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -95172) { Console.WriteLine("test119: for (((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } s.p = return_int(false, 85); v = (s.e + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -93192) { Console.WriteLine("test120: for (s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + s.e); if (v != -93192) { Console.WriteLine("test121: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -93239) { Console.WriteLine("test122: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test123: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90851) { Console.WriteLine("test124: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } s.c = return_int(false, 95); v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -6829) { Console.WriteLine("test125: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -3694) { Console.WriteLine("test126: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -3694) { Console.WriteLine("test127: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -3705) { Console.WriteLine("test128: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -3705) { Console.WriteLine("test129: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -3705) { Console.WriteLine("test130: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -3705) { Console.WriteLine("test131: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -3694) { Console.WriteLine("test132: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -3694) { Console.WriteLine("test133: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 3135) { Console.WriteLine("test134: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 3135) { Console.WriteLine("test135: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 3135) { Console.WriteLine("test136: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 3135) { Console.WriteLine("test137: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -3694) { Console.WriteLine("test138: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -6829) { Console.WriteLine("test139: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -320963) { Console.WriteLine("test140: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -320963) { Console.WriteLine("test141: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 2388) { Console.WriteLine("test142: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } s.q = return_int(false, 53); v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test143: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 2784) { Console.WriteLine("test144: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 2726) { Console.WriteLine("test145: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } s.f = return_int(false, 21); v = (s.f * s.e); if (v != 987) { Console.WriteLine("test146: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 987) { Console.WriteLine("test147: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 987) { Console.WriteLine("test148: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1008) { Console.WriteLine("test149: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test150: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test151: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test152: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test153: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test154: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test155: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 612) { Console.WriteLine("test156: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -320963) { Console.WriteLine("test157: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -321575) { Console.WriteLine("test158: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + s.e); if (v != -321528) { Console.WriteLine("test159: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -321528) { Console.WriteLine("test160: for (s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -328357) { Console.WriteLine("test161: for ((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))); if (v != -328357) { Console.WriteLine("test162: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != 616) { Console.WriteLine("test163: for (s.g+((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.f + (s.e * s.f)) - (s.g * s.h)) + s.g); if (v != 616) { Console.WriteLine("test164: for (((s.f+(s.e*s.f))-(s.g*s.h))+s.g) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 612) { Console.WriteLine("test165: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test166: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1008) { Console.WriteLine("test167: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 987) { Console.WriteLine("test168: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 987) { Console.WriteLine("test169: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 987) { Console.WriteLine("test170: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 56); v = (s.e * s.f); if (v != 987) { Console.WriteLine("test171: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1008) { Console.WriteLine("test172: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test173: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test174: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test175: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test176: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test177: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 95); v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test178: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 612) { Console.WriteLine("test179: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.f + (s.e * s.f)) - (s.g * s.h)) + s.g); if (v != 616) { Console.WriteLine("test180: for (((s.f+(s.e*s.f))-(s.g*s.h))+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != 616) { Console.WriteLine("test181: for (s.g+((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))); if (v != -324325) { Console.WriteLine("test182: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) failed actual value {0} ", v); ret = ret + 1; } v = ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -324941) { Console.WriteLine("test183: for ((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != -977208) { Console.WriteLine("test184: for ((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } v = ((((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)) * (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q)))); if (v != -977208) { Console.WriteLine("test185: for ((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) failed actual value {0} ", v); ret = ret + 1; } s.b = return_int(false, 19); s.d = return_int(false, -10); v = (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))); if (v != -4286) { Console.WriteLine("test186: for (s.a+((s.h+(s.f+s.g))-(s.p*s.q))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.h + (s.f + s.g)) - (s.p * s.q)) + s.a); if (v != -4286) { Console.WriteLine("test187: for (((s.h+(s.f+s.g))-(s.p*s.q))+s.a) failed actual value {0} ", v); ret = ret + 1; } v = ((s.h + (s.f + s.g)) - (s.p * s.q)); if (v != -4381) { Console.WriteLine("test188: for ((s.h+(s.f+s.g))-(s.p*s.q)) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + (s.f + s.g)); if (v != 124) { Console.WriteLine("test189: for (s.h+(s.f+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + s.g) + s.h); if (v != 124) { Console.WriteLine("test190: for ((s.f+s.g)+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.g); if (v != 25) { Console.WriteLine("test191: for (s.f+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.f); if (v != 25) { Console.WriteLine("test192: for (s.g+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.f); if (v != 25) { Console.WriteLine("test193: for (s.g+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.g); if (v != 25) { Console.WriteLine("test194: for (s.f+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.g + s.h)); if (v != 124) { Console.WriteLine("test195: for (s.f+(s.g+s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.f + s.h)); if (v != 124) { Console.WriteLine("test196: for (s.g+(s.f+s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.h); if (v != 103) { Console.WriteLine("test197: for (s.g+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.g); if (v != 103) { Console.WriteLine("test198: for (s.h+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.g); if (v != 103) { Console.WriteLine("test199: for (s.h+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.h); if (v != 103) { Console.WriteLine("test200: for (s.g+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.h); if (v != 120) { Console.WriteLine("test201: for (s.f+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.f); if (v != 120) { Console.WriteLine("test202: for (s.h+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.f); if (v != 120) { Console.WriteLine("test203: for (s.h+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.h); if (v != 120) { Console.WriteLine("test204: for (s.f+s.h) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + s.g) + s.h); if (v != 124) { Console.WriteLine("test205: for ((s.f+s.g)+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + (s.f + s.g)); if (v != 124) { Console.WriteLine("test206: for (s.h+(s.f+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = (s.p * s.q); if (v != 4505) { Console.WriteLine("test207: for (s.p*s.q) failed actual value {0} ", v); ret = ret + 1; } v = (s.q * s.p); if (v != 4505) { Console.WriteLine("test208: for (s.q*s.p) failed actual value {0} ", v); ret = ret + 1; } v = (s.q * s.p); if (v != 4505) { Console.WriteLine("test209: for (s.q*s.p) failed actual value {0} ", v); ret = ret + 1; } v = (s.p * s.q); if (v != 4505) { Console.WriteLine("test210: for (s.p*s.q) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + (s.f + s.g)); if (v != 124) { Console.WriteLine("test211: for (s.h+(s.f+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.h + (s.f + s.g)) - (s.p * s.q)); if (v != -4381) { Console.WriteLine("test212: for ((s.h+(s.f+s.g))-(s.p*s.q)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.h + (s.f + s.g)) - (s.p * s.q)) + s.a); if (v != -4286) { Console.WriteLine("test213: for (((s.h+(s.f+s.g))-(s.p*s.q))+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))); if (v != -4286) { Console.WriteLine("test214: for (s.a+((s.h+(s.f+s.g))-(s.p*s.q))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != 460) { Console.WriteLine("test215: for (((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } s.c = return_int(false, -33); v = ((s.a + s.b) + s.g); if (v != 118) { Console.WriteLine("test216: for ((s.a+s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.a + s.b)); if (v != 118) { Console.WriteLine("test217: for (s.g+(s.a+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + s.b); if (v != 114) { Console.WriteLine("test218: for (s.a+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.a); if (v != 114) { Console.WriteLine("test219: for (s.b+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.a); if (v != 114) { Console.WriteLine("test220: for (s.b+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + s.b); if (v != 114) { Console.WriteLine("test221: for (s.a+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b + s.g)); if (v != 118) { Console.WriteLine("test222: for (s.a+(s.b+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + (s.a + s.g)); if (v != 118) { Console.WriteLine("test223: for (s.b+(s.a+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.g); if (v != 23) { Console.WriteLine("test224: for (s.b+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.b); if (v != 23) { Console.WriteLine("test225: for (s.g+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.b); if (v != 23) { Console.WriteLine("test226: for (s.g+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.g); if (v != 23) { Console.WriteLine("test227: for (s.b+s.g) failed actual value {0} ", v); ret = ret + 1; } s.p = return_int(false, 13); s.g = return_int(false, 69); v = (s.a + s.g); if (v != 164) { Console.WriteLine("test228: for (s.a+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.a); if (v != 164) { Console.WriteLine("test229: for (s.g+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.a); if (v != 164) { Console.WriteLine("test230: for (s.g+s.a) failed actual value {0} ", v); ret = ret + 1; } s.h = return_int(false, 130); v = (s.a + s.g); if (v != 164) { Console.WriteLine("test231: for (s.a+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.a + s.b)); if (v != 183) { Console.WriteLine("test232: for (s.g+(s.a+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + s.b) + s.g); if (v != 183) { Console.WriteLine("test233: for ((s.a+s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != 42) { Console.WriteLine("test234: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } v = (s.k * (s.c + s.b)); if (v != 42) { Console.WriteLine("test235: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } s.p = return_int(false, 72); s.h = return_int(false, -13); v = (s.c + s.b); if (v != -14) { Console.WriteLine("test236: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } s.b = return_int(false, 2); v = (s.b + s.c); if (v != -31) { Console.WriteLine("test237: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.c); if (v != -31) { Console.WriteLine("test238: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c + s.b); if (v != -31) { Console.WriteLine("test239: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.k * (s.c + s.b)); if (v != 93) { Console.WriteLine("test240: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != 93) { Console.WriteLine("test241: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + s.b) + s.g); if (v != 166) { Console.WriteLine("test242: for ((s.a+s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != 73) { Console.WriteLine("test243: for (((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } v = ((((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)) * (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q)))); if (v != -266012) { Console.WriteLine("test244: for ((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != -266012) { Console.WriteLine("test245: for ((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))) + ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != -284292) { Console.WriteLine("test246: for (((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } v = (((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))); if (v != -284292) { Console.WriteLine("test247: for (((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != -20) { Console.WriteLine("test248: for (((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.b) + s.g); if (v != 73) { Console.WriteLine("test249: for ((s.b*s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.b * s.b)); if (v != 73) { Console.WriteLine("test250: for (s.g+(s.b*s.b)) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test251: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test252: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test253: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test254: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.b * s.b)); if (v != 73) { Console.WriteLine("test255: for (s.g+(s.b*s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.b) + s.g); if (v != 73) { Console.WriteLine("test256: for ((s.b*s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != 93) { Console.WriteLine("test257: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } s.k = return_int(false, 125); v = (s.k * (s.c + s.b)); if (v != -3875) { Console.WriteLine("test258: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c + s.b); if (v != -31) { Console.WriteLine("test259: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.c); if (v != -31) { Console.WriteLine("test260: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.c); if (v != -31) { Console.WriteLine("test261: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c + s.b); if (v != -31) { Console.WriteLine("test262: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.k * (s.c + s.b)); if (v != -3875) { Console.WriteLine("test263: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != -3875) { Console.WriteLine("test264: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.b) + s.g); if (v != 73) { Console.WriteLine("test265: for ((s.b*s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != 3948) { Console.WriteLine("test266: for (((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 105); v = (((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))); if (v != -14739134) { Console.WriteLine("test267: for (((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) failed actual value {0} ", v); ret = ret + 1; } v = ((((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))) - (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != -14743082) { Console.WriteLine("test268: for ((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v == 0); #endif Console.WriteLine(ret); if (ret == 100) Console.WriteLine("Test SUCCESS"); else Console.WriteLine("Test FAILURE"); return ret; } private static int return_int(bool verbose, int input) { int ans; try { ans = input; } finally { if (verbose) { Console.WriteLine("returning : ans"); } } return ans; } } public class class_s { public int e; public int a; public int b; public int c; public int d; public int f; public int g; public int h; public int p; public int q; public int k; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // //((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) //permutations for ((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) //((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) //(((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) //(((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) //((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) //((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e+((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))+s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))+s.e) //(s.e+((s.a+(s.b*s.c))-(s.c*s.d))) //(s.e+(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) //(((s.a+(s.b*s.c))-(s.c*s.d))+(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) //(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) //s.e //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //s.e //((s.a+(s.b*s.c))-(s.c*s.d)) //(s.a+(s.b*s.c)) //((s.b*s.c)+s.a) //s.a //(s.b*s.c) //(s.c*s.b) //s.b //s.c //(s.c*s.b) //(s.b*s.c) //((s.b*s.c)+s.a) //(s.a+(s.b*s.c)) //(s.c*s.d) //(s.d*s.c) //s.c //s.d //(s.d*s.c) //(s.c*s.d) //(s.a+(s.b*s.c)) //((s.a+(s.b*s.c))-(s.c*s.d)) //(((s.a+(s.b*s.c))-(s.c*s.d))*s.e) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.e*((s.a+(s.b*s.c))-(s.c*s.d))) //((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) //(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) //(s.g+((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.f+(s.e*s.f))-(s.g*s.h))+s.g) //s.g //((s.f+(s.e*s.f))-(s.g*s.h)) //(s.f+(s.e*s.f)) //((s.e*s.f)+s.f) //s.f //(s.e*s.f) //(s.f*s.e) //s.e //s.f //(s.f*s.e) //(s.e*s.f) //((s.e*s.f)+s.f) //(s.f+(s.e*s.f)) //(s.g*s.h) //(s.h*s.g) //s.g //s.h //(s.h*s.g) //(s.g*s.h) //(s.f+(s.e*s.f)) //((s.f+(s.e*s.f))-(s.g*s.h)) //(((s.f+(s.e*s.f))-(s.g*s.h))+s.g) //(s.g+((s.f+(s.e*s.f))-(s.g*s.h))) //(((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) //((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) //((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) //((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) //(s.a+((s.h+(s.f+s.g))-(s.p*s.q))) //(((s.h+(s.f+s.g))-(s.p*s.q))+s.a) //s.a //((s.h+(s.f+s.g))-(s.p*s.q)) //(s.h+(s.f+s.g)) //((s.f+s.g)+s.h) //s.h //(s.f+s.g) //(s.g+s.f) //s.f //s.g //(s.g+s.f) //(s.f+s.g) //(s.f+(s.g+s.h)) //(s.g+(s.f+s.h)) //(s.g+s.h) //(s.h+s.g) //s.g //s.h //(s.h+s.g) //(s.g+s.h) //(s.f+s.h) //(s.h+s.f) //s.f //s.h //(s.h+s.f) //(s.f+s.h) //((s.f+s.g)+s.h) //(s.h+(s.f+s.g)) //(s.p*s.q) //(s.q*s.p) //s.p //s.q //(s.q*s.p) //(s.p*s.q) //(s.h+(s.f+s.g)) //((s.h+(s.f+s.g))-(s.p*s.q)) //(((s.h+(s.f+s.g))-(s.p*s.q))+s.a) //(s.a+((s.h+(s.f+s.g))-(s.p*s.q))) //(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) //((s.a+s.b)+s.g) //(s.g+(s.a+s.b)) //(s.a+s.b) //(s.b+s.a) //s.a //s.b //(s.b+s.a) //(s.a+s.b) //s.g //(s.a+(s.b+s.g)) //(s.b+(s.a+s.g)) //(s.b+s.g) //(s.g+s.b) //s.b //s.g //(s.g+s.b) //(s.b+s.g) //(s.a+s.g) //(s.g+s.a) //s.a //s.g //(s.g+s.a) //(s.a+s.g) //(s.g+(s.a+s.b)) //((s.a+s.b)+s.g) //((s.c+s.b)*s.k) //(s.k*(s.c+s.b)) //(s.c+s.b) //(s.b+s.c) //s.c //s.b //(s.b+s.c) //(s.c+s.b) //s.k //(s.k*(s.c+s.b)) //((s.c+s.b)*s.k) //((s.a+s.b)+s.g) //(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) //((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) //((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) //(((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) //(((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) //(((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) //((s.b*s.b)+s.g) //(s.g+(s.b*s.b)) //(s.b*s.b) //(s.b*s.b) //s.b //s.b //(s.b*s.b) //(s.b*s.b) //s.g //(s.g+(s.b*s.b)) //((s.b*s.b)+s.g) //((s.c+s.b)*s.k) //(s.k*(s.c+s.b)) //(s.c+s.b) //(s.b+s.c) //s.c //s.b //(s.b+s.c) //(s.c+s.b) //s.k //(s.k*(s.c+s.b)) //((s.c+s.b)*s.k) //((s.b*s.b)+s.g) //(((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) //(((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) //((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) namespace CseTest { using System; public class Test_Main { static int Main() { int ret = 100; class_s s = new class_s(); s.e = return_int(false, 47); s.a = return_int(false, 16); s.b = return_int(false, -39); s.c = return_int(false, 27); s.d = return_int(false, 61); s.f = return_int(false, 32); s.g = return_int(false, 4); s.h = return_int(false, 99); s.p = return_int(false, 122); s.q = return_int(false, -14); s.k = return_int(false, 124); int v; #if LOOP do { #endif v = ((((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))) - (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != 2596789) { Console.WriteLine("test0: for ((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } v = (((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))); if (v != 2599802) { Console.WriteLine("test1: for (((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))) + ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != 2599802) { Console.WriteLine("test2: for (((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } s.d = return_int(false, 33); v = ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -94781) { Console.WriteLine("test3: for ((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))); if (v != -93637) { Console.WriteLine("test4: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -93637) { Console.WriteLine("test5: for ((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -91756) { Console.WriteLine("test6: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90616) { Console.WriteLine("test7: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90616) { Console.WriteLine("test8: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1928) { Console.WriteLine("test9: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP do { #endif v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test10: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1037) { Console.WriteLine("test11: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test12: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test13: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test14: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test15: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1037) { Console.WriteLine("test16: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test17: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test18: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test19: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test20: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test21: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test22: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v == 0); #endif v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1928) { Console.WriteLine("test23: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90616) { Console.WriteLine("test24: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90616) { Console.WriteLine("test25: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 1140) { Console.WriteLine("test26: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP do { #endif v = (s.f + (s.e * s.f)); if (v != 1536) { Console.WriteLine("test27: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1536) { Console.WriteLine("test28: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 1504) { Console.WriteLine("test29: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 1504) { Console.WriteLine("test30: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 1504) { Console.WriteLine("test31: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 1504) { Console.WriteLine("test32: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1536) { Console.WriteLine("test33: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1536) { Console.WriteLine("test34: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test35: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } #if LOOP do { #endif v = (s.h * s.g); if (v != 396) { Console.WriteLine("test36: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test37: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test38: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1536) { Console.WriteLine("test39: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 1140) { Console.WriteLine("test40: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90616) { Console.WriteLine("test41: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -91756) { Console.WriteLine("test42: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -1881) { Console.WriteLine("test43: for (s.e+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + s.e); if (v != -1881) { Console.WriteLine("test44: for (((s.a+(s.b*s.c))-(s.c*s.d))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1928) { Console.WriteLine("test45: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v==0); #endif v = (s.a + (s.b * s.c)); if (v != -1037) { Console.WriteLine("test46: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v==0); #endif v = ((s.b * s.c) + s.a); if (v != -1037) { Console.WriteLine("test47: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 11); v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test48: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test49: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test50: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test51: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test52: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } #if TRY try { #endif v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test53: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test54: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test55: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test56: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test57: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } #if TRY throw new Exception("Test exception"); } catch (System.Exception) { Console.WriteLine("In catch"); #endif s.q = return_int(false, 33); #if TRY } #endif v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test58: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test59: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + s.e); if (v != -1886) { Console.WriteLine("test60: for (((s.a+(s.b*s.c))-(s.c*s.d))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -1886) { Console.WriteLine("test61: for (s.e+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + (((s.a + (s.b * s.c)) - (s.c * s.d)) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != -93877) { Console.WriteLine("test62: for (s.e+(((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + (s.e + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != -93877) { Console.WriteLine("test63: for (((s.a+(s.b*s.c))-(s.c*s.d))+(s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -93924) { Console.WriteLine("test64: for (((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -93924) { Console.WriteLine("test65: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test66: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test67: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test68: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test69: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test70: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test71: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test72: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test73: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test74: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test75: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test76: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test77: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test78: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } s.k = return_int(false, -3); v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test79: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test80: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -91991) { Console.WriteLine("test81: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test82: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90851) { Console.WriteLine("test83: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test84: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } s.f = return_int(false, 42); v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test85: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test86: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test87: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test88: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -1053) { Console.WriteLine("test89: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -1053) { Console.WriteLine("test90: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -1042) { Console.WriteLine("test91: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test92: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test93: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 891) { Console.WriteLine("test94: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } s.f = return_int(false, 58); v = (s.d * s.c); if (v != 891) { Console.WriteLine("test95: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 891) { Console.WriteLine("test96: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -1042) { Console.WriteLine("test97: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -1933) { Console.WriteLine("test98: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90851) { Console.WriteLine("test99: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test100: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 2388) { Console.WriteLine("test101: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test102: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 2784) { Console.WriteLine("test103: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 2726) { Console.WriteLine("test104: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 2726) { Console.WriteLine("test105: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 2726) { Console.WriteLine("test106: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 2726) { Console.WriteLine("test107: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 2784) { Console.WriteLine("test108: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test109: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test110: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test111: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test112: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test113: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test114: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 2388) { Console.WriteLine("test115: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test116: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -93239) { Console.WriteLine("test117: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -95172) { Console.WriteLine("test118: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -95172) { Console.WriteLine("test119: for (((s.a+(s.b*s.c))-(s.c*s.d))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } s.p = return_int(false, 85); v = (s.e + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -93192) { Console.WriteLine("test120: for (s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + s.e); if (v != -93192) { Console.WriteLine("test121: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -93239) { Console.WriteLine("test122: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -90851) { Console.WriteLine("test123: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -90851) { Console.WriteLine("test124: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } s.c = return_int(false, 95); v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -6829) { Console.WriteLine("test125: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -3694) { Console.WriteLine("test126: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -3694) { Console.WriteLine("test127: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -3705) { Console.WriteLine("test128: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -3705) { Console.WriteLine("test129: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.b); if (v != -3705) { Console.WriteLine("test130: for (s.c*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.c); if (v != -3705) { Console.WriteLine("test131: for (s.b*s.c) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.c) + s.a); if (v != -3694) { Console.WriteLine("test132: for ((s.b*s.c)+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -3694) { Console.WriteLine("test133: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 3135) { Console.WriteLine("test134: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 3135) { Console.WriteLine("test135: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.d * s.c); if (v != 3135) { Console.WriteLine("test136: for (s.d*s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c * s.d); if (v != 3135) { Console.WriteLine("test137: for (s.c*s.d) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b * s.c)); if (v != -3694) { Console.WriteLine("test138: for (s.a+(s.b*s.c)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + (s.b * s.c)) - (s.c * s.d)); if (v != -6829) { Console.WriteLine("test139: for ((s.a+(s.b*s.c))-(s.c*s.d)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + (s.b * s.c)) - (s.c * s.d)) * s.e); if (v != -320963) { Console.WriteLine("test140: for (((s.a+(s.b*s.c))-(s.c*s.d))*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -320963) { Console.WriteLine("test141: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 2388) { Console.WriteLine("test142: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } s.q = return_int(false, 53); v = (s.f + (s.e * s.f)); if (v != 2784) { Console.WriteLine("test143: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 2784) { Console.WriteLine("test144: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 2726) { Console.WriteLine("test145: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } s.f = return_int(false, 21); v = (s.f * s.e); if (v != 987) { Console.WriteLine("test146: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 987) { Console.WriteLine("test147: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 987) { Console.WriteLine("test148: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1008) { Console.WriteLine("test149: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test150: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test151: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test152: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test153: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test154: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test155: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 612) { Console.WriteLine("test156: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))); if (v != -320963) { Console.WriteLine("test157: for (s.e*((s.a+(s.b*s.c))-(s.c*s.d))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != -321575) { Console.WriteLine("test158: for ((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + s.e); if (v != -321528) { Console.WriteLine("test159: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.e + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -321528) { Console.WriteLine("test160: for (s.e+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e + ((s.a + (s.b * s.c)) - (s.c * s.d))) + ((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -328357) { Console.WriteLine("test161: for ((s.e+((s.a+(s.b*s.c))-(s.c*s.d)))+((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))); if (v != -328357) { Console.WriteLine("test162: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != 616) { Console.WriteLine("test163: for (s.g+((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.f + (s.e * s.f)) - (s.g * s.h)) + s.g); if (v != 616) { Console.WriteLine("test164: for (((s.f+(s.e*s.f))-(s.g*s.h))+s.g) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 612) { Console.WriteLine("test165: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test166: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1008) { Console.WriteLine("test167: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.e * s.f); if (v != 987) { Console.WriteLine("test168: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 987) { Console.WriteLine("test169: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } v = (s.f * s.e); if (v != 987) { Console.WriteLine("test170: for (s.f*s.e) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 56); v = (s.e * s.f); if (v != 987) { Console.WriteLine("test171: for (s.e*s.f) failed actual value {0} ", v); ret = ret + 1; } v = ((s.e * s.f) + s.f); if (v != 1008) { Console.WriteLine("test172: for ((s.e*s.f)+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test173: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test174: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test175: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h * s.g); if (v != 396) { Console.WriteLine("test176: for (s.h*s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g * s.h); if (v != 396) { Console.WriteLine("test177: for (s.g*s.h) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 95); v = (s.f + (s.e * s.f)); if (v != 1008) { Console.WriteLine("test178: for (s.f+(s.e*s.f)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + (s.e * s.f)) - (s.g * s.h)); if (v != 612) { Console.WriteLine("test179: for ((s.f+(s.e*s.f))-(s.g*s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.f + (s.e * s.f)) - (s.g * s.h)) + s.g); if (v != 616) { Console.WriteLine("test180: for (((s.f+(s.e*s.f))-(s.g*s.h))+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))); if (v != 616) { Console.WriteLine("test181: for (s.g+((s.f+(s.e*s.f))-(s.g*s.h))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))); if (v != -324325) { Console.WriteLine("test182: for (((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d)))) failed actual value {0} ", v); ret = ret + 1; } v = ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))); if (v != -324941) { Console.WriteLine("test183: for ((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != -977208) { Console.WriteLine("test184: for ((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } v = ((((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)) * (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q)))); if (v != -977208) { Console.WriteLine("test185: for ((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) failed actual value {0} ", v); ret = ret + 1; } s.b = return_int(false, 19); s.d = return_int(false, -10); v = (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))); if (v != -4286) { Console.WriteLine("test186: for (s.a+((s.h+(s.f+s.g))-(s.p*s.q))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.h + (s.f + s.g)) - (s.p * s.q)) + s.a); if (v != -4286) { Console.WriteLine("test187: for (((s.h+(s.f+s.g))-(s.p*s.q))+s.a) failed actual value {0} ", v); ret = ret + 1; } v = ((s.h + (s.f + s.g)) - (s.p * s.q)); if (v != -4381) { Console.WriteLine("test188: for ((s.h+(s.f+s.g))-(s.p*s.q)) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + (s.f + s.g)); if (v != 124) { Console.WriteLine("test189: for (s.h+(s.f+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + s.g) + s.h); if (v != 124) { Console.WriteLine("test190: for ((s.f+s.g)+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.g); if (v != 25) { Console.WriteLine("test191: for (s.f+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.f); if (v != 25) { Console.WriteLine("test192: for (s.g+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.f); if (v != 25) { Console.WriteLine("test193: for (s.g+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.g); if (v != 25) { Console.WriteLine("test194: for (s.f+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + (s.g + s.h)); if (v != 124) { Console.WriteLine("test195: for (s.f+(s.g+s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.f + s.h)); if (v != 124) { Console.WriteLine("test196: for (s.g+(s.f+s.h)) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.h); if (v != 103) { Console.WriteLine("test197: for (s.g+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.g); if (v != 103) { Console.WriteLine("test198: for (s.h+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.g); if (v != 103) { Console.WriteLine("test199: for (s.h+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.h); if (v != 103) { Console.WriteLine("test200: for (s.g+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.h); if (v != 120) { Console.WriteLine("test201: for (s.f+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.f); if (v != 120) { Console.WriteLine("test202: for (s.h+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + s.f); if (v != 120) { Console.WriteLine("test203: for (s.h+s.f) failed actual value {0} ", v); ret = ret + 1; } v = (s.f + s.h); if (v != 120) { Console.WriteLine("test204: for (s.f+s.h) failed actual value {0} ", v); ret = ret + 1; } v = ((s.f + s.g) + s.h); if (v != 124) { Console.WriteLine("test205: for ((s.f+s.g)+s.h) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + (s.f + s.g)); if (v != 124) { Console.WriteLine("test206: for (s.h+(s.f+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = (s.p * s.q); if (v != 4505) { Console.WriteLine("test207: for (s.p*s.q) failed actual value {0} ", v); ret = ret + 1; } v = (s.q * s.p); if (v != 4505) { Console.WriteLine("test208: for (s.q*s.p) failed actual value {0} ", v); ret = ret + 1; } v = (s.q * s.p); if (v != 4505) { Console.WriteLine("test209: for (s.q*s.p) failed actual value {0} ", v); ret = ret + 1; } v = (s.p * s.q); if (v != 4505) { Console.WriteLine("test210: for (s.p*s.q) failed actual value {0} ", v); ret = ret + 1; } v = (s.h + (s.f + s.g)); if (v != 124) { Console.WriteLine("test211: for (s.h+(s.f+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.h + (s.f + s.g)) - (s.p * s.q)); if (v != -4381) { Console.WriteLine("test212: for ((s.h+(s.f+s.g))-(s.p*s.q)) failed actual value {0} ", v); ret = ret + 1; } v = (((s.h + (s.f + s.g)) - (s.p * s.q)) + s.a); if (v != -4286) { Console.WriteLine("test213: for (((s.h+(s.f+s.g))-(s.p*s.q))+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))); if (v != -4286) { Console.WriteLine("test214: for (s.a+((s.h+(s.f+s.g))-(s.p*s.q))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != 460) { Console.WriteLine("test215: for (((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } s.c = return_int(false, -33); v = ((s.a + s.b) + s.g); if (v != 118) { Console.WriteLine("test216: for ((s.a+s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.a + s.b)); if (v != 118) { Console.WriteLine("test217: for (s.g+(s.a+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + s.b); if (v != 114) { Console.WriteLine("test218: for (s.a+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.a); if (v != 114) { Console.WriteLine("test219: for (s.b+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.a); if (v != 114) { Console.WriteLine("test220: for (s.b+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + s.b); if (v != 114) { Console.WriteLine("test221: for (s.a+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.a + (s.b + s.g)); if (v != 118) { Console.WriteLine("test222: for (s.a+(s.b+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + (s.a + s.g)); if (v != 118) { Console.WriteLine("test223: for (s.b+(s.a+s.g)) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.g); if (v != 23) { Console.WriteLine("test224: for (s.b+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.b); if (v != 23) { Console.WriteLine("test225: for (s.g+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.b); if (v != 23) { Console.WriteLine("test226: for (s.g+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.g); if (v != 23) { Console.WriteLine("test227: for (s.b+s.g) failed actual value {0} ", v); ret = ret + 1; } s.p = return_int(false, 13); s.g = return_int(false, 69); v = (s.a + s.g); if (v != 164) { Console.WriteLine("test228: for (s.a+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.a); if (v != 164) { Console.WriteLine("test229: for (s.g+s.a) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + s.a); if (v != 164) { Console.WriteLine("test230: for (s.g+s.a) failed actual value {0} ", v); ret = ret + 1; } s.h = return_int(false, 130); v = (s.a + s.g); if (v != 164) { Console.WriteLine("test231: for (s.a+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.a + s.b)); if (v != 183) { Console.WriteLine("test232: for (s.g+(s.a+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + s.b) + s.g); if (v != 183) { Console.WriteLine("test233: for ((s.a+s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != 42) { Console.WriteLine("test234: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } v = (s.k * (s.c + s.b)); if (v != 42) { Console.WriteLine("test235: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } s.p = return_int(false, 72); s.h = return_int(false, -13); v = (s.c + s.b); if (v != -14) { Console.WriteLine("test236: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } s.b = return_int(false, 2); v = (s.b + s.c); if (v != -31) { Console.WriteLine("test237: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.c); if (v != -31) { Console.WriteLine("test238: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c + s.b); if (v != -31) { Console.WriteLine("test239: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.k * (s.c + s.b)); if (v != 93) { Console.WriteLine("test240: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != 93) { Console.WriteLine("test241: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + s.b) + s.g); if (v != 166) { Console.WriteLine("test242: for ((s.a+s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != 73) { Console.WriteLine("test243: for (((s.a+s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } v = ((((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)) * (s.a + ((s.h + (s.f + s.g)) - (s.p * s.q)))); if (v != -266012) { Console.WriteLine("test244: for ((((s.a+s.b)+s.g)-((s.c+s.b)*s.k))*(s.a+((s.h+(s.f+s.g))-(s.p*s.q)))) failed actual value {0} ", v); ret = ret + 1; } v = ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != -266012) { Console.WriteLine("test245: for ((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k))) + ((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h))))); if (v != -284292) { Console.WriteLine("test246: for (((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))+((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))) failed actual value {0} ", v); ret = ret + 1; } v = (((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))); if (v != -284292) { Console.WriteLine("test247: for (((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) failed actual value {0} ", v); ret = ret + 1; } v = (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != -20) { Console.WriteLine("test248: for (((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.b) + s.g); if (v != 73) { Console.WriteLine("test249: for ((s.b*s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.b * s.b)); if (v != 73) { Console.WriteLine("test250: for (s.g+(s.b*s.b)) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test251: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test252: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test253: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b * s.b); if (v != 4) { Console.WriteLine("test254: for (s.b*s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.g + (s.b * s.b)); if (v != 73) { Console.WriteLine("test255: for (s.g+(s.b*s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.b) + s.g); if (v != 73) { Console.WriteLine("test256: for ((s.b*s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != 93) { Console.WriteLine("test257: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } s.k = return_int(false, 125); v = (s.k * (s.c + s.b)); if (v != -3875) { Console.WriteLine("test258: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = (s.c + s.b); if (v != -31) { Console.WriteLine("test259: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.c); if (v != -31) { Console.WriteLine("test260: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.b + s.c); if (v != -31) { Console.WriteLine("test261: for (s.b+s.c) failed actual value {0} ", v); ret = ret + 1; } v = (s.c + s.b); if (v != -31) { Console.WriteLine("test262: for (s.c+s.b) failed actual value {0} ", v); ret = ret + 1; } v = (s.k * (s.c + s.b)); if (v != -3875) { Console.WriteLine("test263: for (s.k*(s.c+s.b)) failed actual value {0} ", v); ret = ret + 1; } v = ((s.c + s.b) * s.k); if (v != -3875) { Console.WriteLine("test264: for ((s.c+s.b)*s.k) failed actual value {0} ", v); ret = ret + 1; } v = ((s.b * s.b) + s.g); if (v != 73) { Console.WriteLine("test265: for ((s.b*s.b)+s.g) failed actual value {0} ", v); ret = ret + 1; } v = (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k)); if (v != 3948) { Console.WriteLine("test266: for (((s.b*s.b)+s.g)-((s.c+s.b)*s.k)) failed actual value {0} ", v); ret = ret + 1; } s.a = return_int(false, 105); v = (((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))); if (v != -14739134) { Console.WriteLine("test267: for (((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k)))) failed actual value {0} ", v); ret = ret + 1; } v = ((((((s.e * ((s.a + (s.b * s.c)) - (s.c * s.d))) - ((s.f + (s.e * s.f)) - (s.g * s.h))) + (s.e + ((s.a + (s.b * s.c)) - (s.c * s.d)))) - (s.g + ((s.f + (s.e * s.f)) - (s.g * s.h)))) + ((s.a + ((s.h + (s.f + s.g)) - (s.p * s.q))) * (((s.a + s.b) + s.g) - ((s.c + s.b) * s.k)))) - (((s.b * s.b) + s.g) - ((s.c + s.b) * s.k))); if (v != -14743082) { Console.WriteLine("test268: for ((((((s.e*((s.a+(s.b*s.c))-(s.c*s.d)))-((s.f+(s.e*s.f))-(s.g*s.h)))+(s.e+((s.a+(s.b*s.c))-(s.c*s.d))))-(s.g+((s.f+(s.e*s.f))-(s.g*s.h))))+((s.a+((s.h+(s.f+s.g))-(s.p*s.q)))*(((s.a+s.b)+s.g)-((s.c+s.b)*s.k))))-(((s.b*s.b)+s.g)-((s.c+s.b)*s.k))) failed actual value {0} ", v); ret = ret + 1; } #if LOOP } while (v == 0); #endif Console.WriteLine(ret); if (ret == 100) Console.WriteLine("Test SUCCESS"); else Console.WriteLine("Test FAILURE"); return ret; } private static int return_int(bool verbose, int input) { int ans; try { ans = input; } finally { if (verbose) { Console.WriteLine("returning : ans"); } } return ans; } } public class class_s { public int e; public int a; public int b; public int c; public int d; public int f; public int g; public int h; public int p; public int q; public int k; } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Drawing.Common/src/System/Drawing/Text/HotkeyPrefix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Drawing.Text { /// <summary> /// Specifies the type of display for hotkey prefixes for text. /// </summary> public enum HotkeyPrefix { /// <summary> /// No hotkey prefix. /// </summary> None = 0, /// <summary> /// Display the hotkey prefix. /// </summary> Show = 1, /// <summary> /// Do not display the hotkey prefix. /// </summary> Hide = 2 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Drawing.Text { /// <summary> /// Specifies the type of display for hotkey prefixes for text. /// </summary> public enum HotkeyPrefix { /// <summary> /// No hotkey prefix. /// </summary> None = 0, /// <summary> /// Display the hotkey prefix. /// </summary> Show = 1, /// <summary> /// Do not display the hotkey prefix. /// </summary> Hide = 2 } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Data.Common/src/System/Data/PrimaryKeyTypeConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Data { internal sealed class PrimaryKeyTypeConverter : ReferenceConverter { // converter classes should have public ctor public PrimaryKeyTypeConverter() : base(typeof(DataColumn[])) { } public override bool GetPropertiesSupported(ITypeDescriptorContext? context) => false; public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType) => destinationType == typeof(string) || base.CanConvertTo(context, destinationType); public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) { return destinationType == typeof(string) ? Array.Empty<DataColumn>().GetType().Name : base.ConvertTo(context, culture, value, destinationType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.Data { internal sealed class PrimaryKeyTypeConverter : ReferenceConverter { // converter classes should have public ctor public PrimaryKeyTypeConverter() : base(typeof(DataColumn[])) { } public override bool GetPropertiesSupported(ITypeDescriptorContext? context) => false; public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen(true)] Type? destinationType) => destinationType == typeof(string) || base.CanConvertTo(context, destinationType); public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType!!) { return destinationType == typeof(string) ? Array.Empty<DataColumn>().GetType().Name : base.ConvertTo(context, culture, value, destinationType); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/jit64/hfa/main/testB/hfa_nd0B_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType /> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testB.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f64_common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f64_managed.csproj" /> <ProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType /> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testB.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f64_common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f64_managed.csproj" /> <ProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/Microsoft.Extensions.Hosting/tests/FunctionalTests/IntegrationTesting/src/Common/RuntimeArchitecture.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.Hosting.IntegrationTesting { public enum RuntimeArchitecture { x64, x86 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.Hosting.IntegrationTesting { public enum RuntimeArchitecture { x64, x86 } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/HardwareIntrinsics/General/Vector256/LessThan.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void LessThanByte() { var test = new VectorBinaryOpTest__LessThanByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__LessThanByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Byte> _fld1; public Vector256<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__LessThanByte testClass) { var result = Vector256.LessThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__LessThanByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public VectorBinaryOpTest__LessThanByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.LessThan( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.LessThan), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.LessThan), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.LessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Vector256.LessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__LessThanByte(); var result = Vector256.LessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.LessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.LessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < right[0]) ? byte.MaxValue : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < right[i]) ? byte.MaxValue : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.LessThan)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void LessThanByte() { var test = new VectorBinaryOpTest__LessThanByte(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__LessThanByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Byte> _fld1; public Vector256<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__LessThanByte testClass) { var result = Vector256.LessThan(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__LessThanByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public VectorBinaryOpTest__LessThanByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.LessThan( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.LessThan), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.LessThan), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Byte)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.LessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Vector256.LessThan(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__LessThanByte(); var result = Vector256.LessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.LessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.LessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < right[0]) ? byte.MaxValue : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < right[i]) ? byte.MaxValue : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.LessThan)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/jit64/hfa/main/testC/hfa_nf2C_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testC.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_interop_cpp.csproj" /> <ProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testC.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_interop_cpp.csproj" /> <ProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/baseservices/exceptions/regressions/V1/SEH/VJ/UnmanagedToManaged.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; public class UnmanagedToManaged { ///** @dll.import("Unmanaged.dll")*/ [System.Runtime.InteropServices.DllImport("unmanaged.dll")] public static extern void UnmanagedCode( int i) ; public static int Main(String []args){ String s = "Done"; int retVal = 0; try { Console.WriteLine("Calling unmanaged code..."); UnmanagedCode(0); Console.WriteLine("...Returned from unmanaged code"); } catch (DivideByZeroException ) { Console.WriteLine("Caught a div-by-zero exception."); retVal = 100; } catch (Exception ) { Console.WriteLine("Caught a general exception"); } Console.WriteLine(s); return retVal; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; public class UnmanagedToManaged { ///** @dll.import("Unmanaged.dll")*/ [System.Runtime.InteropServices.DllImport("unmanaged.dll")] public static extern void UnmanagedCode( int i) ; public static int Main(String []args){ String s = "Done"; int retVal = 0; try { Console.WriteLine("Calling unmanaged code..."); UnmanagedCode(0); Console.WriteLine("...Returned from unmanaged code"); } catch (DivideByZeroException ) { Console.WriteLine("Caught a div-by-zero exception."); retVal = 100; } catch (Exception ) { Console.WriteLine("Caught a general exception"); } Console.WriteLine(s); return retVal; } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/jit64/valuetypes/nullable/castclass/null/castclass-null045.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - CastClass </Area> // <Title> Nullable type with castclass expr </Title> // <Description> // checking type of MixedAllStruct using cast expr // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((ValueType)(object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)(object)(ValueType)o) == null; } private static bool BoxUnboxToNQ(object o) { return ((ValueType)o) == null; } private static bool BoxUnboxToQ(object o) { return ((MixedAllStruct?)(ValueType)o) == null; } private static int Main() { MixedAllStruct? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - CastClass </Area> // <Title> Nullable type with castclass expr </Title> // <Description> // checking type of MixedAllStruct using cast expr // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((ValueType)(object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)(object)(ValueType)o) == null; } private static bool BoxUnboxToNQ(object o) { return ((ValueType)o) == null; } private static bool BoxUnboxToQ(object o) { return ((MixedAllStruct?)(ValueType)o) == null; } private static int Main() { MixedAllStruct? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Configuration.Provider; using System.Xml; namespace System.Configuration { public abstract class ProtectedConfigurationProvider : ProviderBase { public abstract XmlNode Encrypt(XmlNode node); public abstract XmlNode Decrypt(XmlNode encryptedNode); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Configuration.Provider; using System.Xml; namespace System.Configuration { public abstract class ProtectedConfigurationProvider : ProviderBase { public abstract XmlNode Encrypt(XmlNode node); public abstract XmlNode Decrypt(XmlNode encryptedNode); } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/AddHighNarrowingUpper.Vector128.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddHighNarrowingUpper_Vector128_Int32() { var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int64[] inArray2, Int64[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int64, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int64> _fld2; public Vector128<Int64> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32 testClass) { var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) fixed (Vector128<Int64>* pFld3 = &_fld3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), AdvSimd.LoadVector128((Int64*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Int64[] _data3 = new Int64[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int64> _clsVar2; private static Vector128<Int64> _clsVar3; private Vector64<Int32> _fld1; private Vector128<Int64> _fld2; private Vector128<Int64> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.AddHighNarrowingUpper( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AddHighNarrowingUpper( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) fixed (Vector128<Int64>* pClsVar3 = &_clsVar3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(pClsVar2)), AdvSimd.LoadVector128((Int64*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr); var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)); var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32(); var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) fixed (Vector128<Int64>* pFld3 = &test._fld3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), AdvSimd.LoadVector128((Int64*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) fixed (Vector128<Int64>* pFld3 = &_fld3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), AdvSimd.LoadVector128((Int64*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&test._fld2)), AdvSimd.LoadVector128((Int64*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector128<Int64> op2, Vector128<Int64> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int64[] secondOp, Int64[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddHighNarrowingUpper(firstOp, secondOp, thirdOp, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddHighNarrowingUpper)}<Int32>(Vector64<Int32>, Vector128<Int64>, Vector128<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddHighNarrowingUpper_Vector128_Int32() { var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int64[] inArray2, Int64[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int64, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int64, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int64> _fld2; public Vector128<Int64> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32 testClass) { var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) fixed (Vector128<Int64>* pFld3 = &_fld3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), AdvSimd.LoadVector128((Int64*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Int64[] _data3 = new Int64[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int64> _clsVar2; private static Vector128<Int64> _clsVar3; private Vector64<Int32> _fld1; private Vector128<Int64> _fld2; private Vector128<Int64> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.AddHighNarrowingUpper( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddHighNarrowingUpper), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AddHighNarrowingUpper( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar2 = &_clsVar2) fixed (Vector128<Int64>* pClsVar3 = &_clsVar3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int64*)(pClsVar2)), AdvSimd.LoadVector128((Int64*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr); var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)); var result = AdvSimd.AddHighNarrowingUpper(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32(); var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__AddHighNarrowingUpper_Vector128_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld2) fixed (Vector128<Int64>* pFld3 = &test._fld3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), AdvSimd.LoadVector128((Int64*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AddHighNarrowingUpper(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld2) fixed (Vector128<Int64>* pFld3 = &_fld3) { var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int64*)(pFld2)), AdvSimd.LoadVector128((Int64*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.AddHighNarrowingUpper(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.AddHighNarrowingUpper( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int64*)(&test._fld2)), AdvSimd.LoadVector128((Int64*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector128<Int64> op2, Vector128<Int64> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int64[] secondOp, Int64[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.AddHighNarrowingUpper(firstOp, secondOp, thirdOp, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddHighNarrowingUpper)}<Int32>(Vector64<Int32>, Vector128<Int64>, Vector128<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.IsValidSid.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)] internal static partial bool IsValidSid(IntPtr sid); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Advapi32 { [GeneratedDllImport(Libraries.Advapi32, SetLastError = true)] internal static partial bool IsValidSid(IntPtr sid); } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/Microsoft.CSharp/tests/Microsoft.CSharp.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>$(NetCoreAppCurrent);net48</TargetFrameworks> <!-- We wish to test operations that would result in "Operator '-' cannot be applied to operands of type 'ushort' and 'EnumArithmeticTests.UInt16Enum'" --> <Features>$(Features.Replace('strict', '')</Features> <DebuggerSupport Condition="'$(DebuggerSupport)' == '' and '$(TargetOS)' == 'Browser'">true</DebuggerSupport> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)System\Runtime\CompilerServices\IsExternalInit.cs" Link="Common\System\Runtime\CompilerServices\IsExternalInit.cs" /> <Compile Include="AccessTests.cs" /> <Compile Include="ArrayHandling.cs" /> <Compile Include="AssignmentTests.cs" /> <Compile Include="BindingErrors.cs" /> <Compile Include="DynamicDebuggerProxyTests.cs" /> <Compile Include="EnumUnaryOperationTests.cs" /> <Compile Include="ExplicitConversionTests.cs" /> <Compile Include="Helpers.cs" /> <Compile Include="ImplicitConversionTests.cs" /> <Compile Include="CSharpArgumentInfoTests.cs" /> <Compile Include="DefaultParameterTests.cs" /> <Compile Include="DelegateInDynamicTests.cs" /> <Compile Include="EnumArithmeticTests.cs" /> <Compile Include="IndexingTests.cs" /> <Compile Include="IntegerBinaryOperationTests.cs" /> <Compile Include="IntegerUnaryOperationTests.cs" /> <Compile Include="IsEventTests.cs" /> <Compile Include="NamedArgumentTests.cs" /> <Compile Include="NullableEnumUnaryOperationTest.cs" /> <Compile Include="RuntimeBinderExceptionTests.cs" /> <Compile Include="RuntimeBinderInternalCompilerExceptionTests.cs" /> <Compile Include="RuntimeBinderTests.cs" /> <Compile Include="UserDefinedShortCircuitOperators.cs" /> <Compile Include="VarArgsTests.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == '$(NetCoreAppCurrent)'"> <Compile Include="AccessTests.netcoreapp.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net48'"> <Reference Include="Microsoft.CSharp" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>$(NetCoreAppCurrent);net48</TargetFrameworks> <!-- We wish to test operations that would result in "Operator '-' cannot be applied to operands of type 'ushort' and 'EnumArithmeticTests.UInt16Enum'" --> <Features>$(Features.Replace('strict', '')</Features> <DebuggerSupport Condition="'$(DebuggerSupport)' == '' and '$(TargetOS)' == 'Browser'">true</DebuggerSupport> </PropertyGroup> <ItemGroup> <Compile Include="$(CommonPath)System\Runtime\CompilerServices\IsExternalInit.cs" Link="Common\System\Runtime\CompilerServices\IsExternalInit.cs" /> <Compile Include="AccessTests.cs" /> <Compile Include="ArrayHandling.cs" /> <Compile Include="AssignmentTests.cs" /> <Compile Include="BindingErrors.cs" /> <Compile Include="DynamicDebuggerProxyTests.cs" /> <Compile Include="EnumUnaryOperationTests.cs" /> <Compile Include="ExplicitConversionTests.cs" /> <Compile Include="Helpers.cs" /> <Compile Include="ImplicitConversionTests.cs" /> <Compile Include="CSharpArgumentInfoTests.cs" /> <Compile Include="DefaultParameterTests.cs" /> <Compile Include="DelegateInDynamicTests.cs" /> <Compile Include="EnumArithmeticTests.cs" /> <Compile Include="IndexingTests.cs" /> <Compile Include="IntegerBinaryOperationTests.cs" /> <Compile Include="IntegerUnaryOperationTests.cs" /> <Compile Include="IsEventTests.cs" /> <Compile Include="NamedArgumentTests.cs" /> <Compile Include="NullableEnumUnaryOperationTest.cs" /> <Compile Include="RuntimeBinderExceptionTests.cs" /> <Compile Include="RuntimeBinderInternalCompilerExceptionTests.cs" /> <Compile Include="RuntimeBinderTests.cs" /> <Compile Include="UserDefinedShortCircuitOperators.cs" /> <Compile Include="VarArgsTests.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == '$(NetCoreAppCurrent)'"> <Compile Include="AccessTests.netcoreapp.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetFramework)' == 'net48'"> <Reference Include="Microsoft.CSharp" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Mangling.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Internal.TypeSystem.Interop { partial class PInvokeDelegateWrapper : IPrefixMangledType { TypeDesc IPrefixMangledType.BaseType { get { return DelegateType; } } string IPrefixMangledType.Prefix { get { return "PInvokeDelegateWrapper"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Internal.TypeSystem.Interop { partial class PInvokeDelegateWrapper : IPrefixMangledType { TypeDesc IPrefixMangledType.BaseType { get { return DelegateType; } } string IPrefixMangledType.Prefix { get { return "PInvokeDelegateWrapper"; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Net.Sockets/tests/FunctionalTests/SendReceive/SendReceiveTcpClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public sealed class SendReceiveTcpClient : MemberDatas { [OuterLoop] [Theory] [MemberData(nameof(Loopbacks))] public async Task SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 10; const int TestTimeout = 30000; var listener = new TcpListener(listenAt, 0); listener.Start(ListenBacklog); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); Task serverTask = Task.Run(async () => { using (TcpClient remote = await listener.AcceptTcpClientAsync()) using (NetworkStream stream = remote.GetStream()) { var recvBuffer = new byte[256]; while (true) { int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } }); int bytesSent = 0; var sentChecksum = new Fletcher32(); Task clientTask = Task.Run(async () => { var clientEndpoint = (IPEndPoint)listener.LocalEndpoint; using (var client = new TcpClient(clientEndpoint.AddressFamily)) { await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port); using (NetworkStream stream = client.GetStream()) { var random = new Random(); var sendBuffer = new byte[512]; for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); sent = Math.Min(sendBuffer.Length, remaining); await stream.WriteAsync(sendBuffer, 0, sent); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } client.LingerState = new LingerOption(true, LingerTime); } } }); await (new[] { serverTask, clientTask }).WhenAllOrAnyFailed(TestTimeout); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public sealed class SendReceiveTcpClient : MemberDatas { [OuterLoop] [Theory] [MemberData(nameof(Loopbacks))] public async Task SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 10; const int TestTimeout = 30000; var listener = new TcpListener(listenAt, 0); listener.Start(ListenBacklog); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); Task serverTask = Task.Run(async () => { using (TcpClient remote = await listener.AcceptTcpClientAsync()) using (NetworkStream stream = remote.GetStream()) { var recvBuffer = new byte[256]; while (true) { int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } }); int bytesSent = 0; var sentChecksum = new Fletcher32(); Task clientTask = Task.Run(async () => { var clientEndpoint = (IPEndPoint)listener.LocalEndpoint; using (var client = new TcpClient(clientEndpoint.AddressFamily)) { await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port); using (NetworkStream stream = client.GetStream()) { var random = new Random(); var sendBuffer = new byte[512]; for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); sent = Math.Min(sendBuffer.Length, remaining); await stream.WriteAsync(sendBuffer, 0, sent); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } client.LingerState = new LingerOption(true, LingerTime); } } }); await (new[] { serverTask, clientTask }).WhenAllOrAnyFailed(TestTimeout); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b16895/b16895.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ILGEN_0x38e6c42a {} .class ILGEN_0x38e6c42a { .field static unsigned int16 field_0x1 .field static unsigned int32 field_0x2 .field static int8 field_0x4 .field static int64 field_0x7 .method static int32 main() { .entrypoint .maxstack 18 .locals (int16[] local_0x5,float64[] local_0x9,int16 local_0xd,int32 local_0xe,float32 local_0x10,float64 local_0x11, int32 ecode) ldnull stloc.0 ldnull stloc.1 ldc.i4.0 stloc.2 ldc.i4.0 stloc.3 ldc.r4 0 stloc 4 ldc.r8 0 stloc 5 ldc.i4.0 stloc 6 .try { ldc.i4.1 stloc ecode ldc.i4 255 newarr [mscorlib]System.Int16 stloc local_0x5 ldc.i4 255 newarr [mscorlib]System.Double stloc local_0x9 ldc.i4 0x4bc42265 stloc local_0xd ldc.i4 0x9526a86 stloc local_0xe ldc.r4 float32(0x224f76bb) stloc local_0x10 ldc.r8 float64(0x2b9a63004fb5cba) stloc local_0x11 ldc.i4 0x4e7d532c stsfld unsigned int16 ILGEN_0x38e6c42a::field_0x1 ldc.i4 0x3fd3428 stsfld unsigned int32 ILGEN_0x38e6c42a::field_0x2 ldc.i4 0x5a84dd2 stsfld int8 ILGEN_0x38e6c42a::field_0x4 ldc.i8 0x391a74984ba7c02 stsfld int64 ILGEN_0x38e6c42a::field_0x7 ldloc local_0x10 conv.ovf.i4 ldc.r4 float32(0x26693fb0) conv.ovf.u2.un ldloc local_0x5 ldlen conv.ovf.u4 rem conv.ovf.u4 ldloc local_0x10 conv.ovf.i4.un ldloc local_0x9 ldloca local_0xe ldind.i4 ldelema [mscorlib]System.Double ldind.r8 ldloc local_0x11 //conv.r.un Start_Orphan_28: ldsfld int8 ILGEN_0x38e6c42a::field_0x4 conv.u1 newarr [mscorlib]System.Int64 ldsfld unsigned int16 ILGEN_0x38e6c42a::field_0x1 ldelema [mscorlib]System.Int64 ldsfld unsigned int32 ILGEN_0x38e6c42a::field_0x2 conv.ovf.i8 ldloc local_0xd conv.u8 mul.ovf stind.i8 End_Orphan_28: ceq rem ceq clt pop leave xx } catch [mscorlib]System.IndexOutOfRangeException { pop ldc.i4.0 stloc ecode leave xx } xx: ldloc ecode ldc.i4 100 add ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern legacy library mscorlib {} .assembly extern System.Console { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } .assembly ILGEN_0x38e6c42a {} .class ILGEN_0x38e6c42a { .field static unsigned int16 field_0x1 .field static unsigned int32 field_0x2 .field static int8 field_0x4 .field static int64 field_0x7 .method static int32 main() { .entrypoint .maxstack 18 .locals (int16[] local_0x5,float64[] local_0x9,int16 local_0xd,int32 local_0xe,float32 local_0x10,float64 local_0x11, int32 ecode) ldnull stloc.0 ldnull stloc.1 ldc.i4.0 stloc.2 ldc.i4.0 stloc.3 ldc.r4 0 stloc 4 ldc.r8 0 stloc 5 ldc.i4.0 stloc 6 .try { ldc.i4.1 stloc ecode ldc.i4 255 newarr [mscorlib]System.Int16 stloc local_0x5 ldc.i4 255 newarr [mscorlib]System.Double stloc local_0x9 ldc.i4 0x4bc42265 stloc local_0xd ldc.i4 0x9526a86 stloc local_0xe ldc.r4 float32(0x224f76bb) stloc local_0x10 ldc.r8 float64(0x2b9a63004fb5cba) stloc local_0x11 ldc.i4 0x4e7d532c stsfld unsigned int16 ILGEN_0x38e6c42a::field_0x1 ldc.i4 0x3fd3428 stsfld unsigned int32 ILGEN_0x38e6c42a::field_0x2 ldc.i4 0x5a84dd2 stsfld int8 ILGEN_0x38e6c42a::field_0x4 ldc.i8 0x391a74984ba7c02 stsfld int64 ILGEN_0x38e6c42a::field_0x7 ldloc local_0x10 conv.ovf.i4 ldc.r4 float32(0x26693fb0) conv.ovf.u2.un ldloc local_0x5 ldlen conv.ovf.u4 rem conv.ovf.u4 ldloc local_0x10 conv.ovf.i4.un ldloc local_0x9 ldloca local_0xe ldind.i4 ldelema [mscorlib]System.Double ldind.r8 ldloc local_0x11 //conv.r.un Start_Orphan_28: ldsfld int8 ILGEN_0x38e6c42a::field_0x4 conv.u1 newarr [mscorlib]System.Int64 ldsfld unsigned int16 ILGEN_0x38e6c42a::field_0x1 ldelema [mscorlib]System.Int64 ldsfld unsigned int32 ILGEN_0x38e6c42a::field_0x2 conv.ovf.i8 ldloc local_0xd conv.u8 mul.ovf stind.i8 End_Orphan_28: ceq rem ceq clt pop leave xx } catch [mscorlib]System.IndexOutOfRangeException { pop ldc.i4.0 stloc ecode leave xx } xx: ldloc ecode ldc.i4 100 add ret } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/HardwareIntrinsics/Arm/Aes/Decrypt.Vector128.Byte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Decrypt_Vector128_Byte() { var test = new AesBinaryOpTest__Decrypt_Vector128_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AesBinaryOpTest__Decrypt_Vector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(AesBinaryOpTest__Decrypt_Vector128_Byte testClass) { var result = Aes.Decrypt(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AesBinaryOpTest__Decrypt_Vector128_Byte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[16] {0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88}; private static Byte[] _data2 = new Byte[16] {0xFF, 0xDD, 0xBB, 0x99, 0x77, 0x55, 0x33, 0x11, 0xEE, 0xCC, 0xAA, 0x88, 0x66, 0x44, 0x22, 0x00}; private static Byte[] _expectedRet = new Byte[16] {0x7C, 0x99, 0x02, 0x7C, 0x7C, 0x7C, 0xFE, 0x86, 0xE3, 0x7C, 0x7C, 0x97, 0xC9, 0x94, 0x7C, 0x7C}; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static AesBinaryOpTest__Decrypt_Vector128_Byte() { Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public AesBinaryOpTest__Decrypt_Vector128_Byte() { Succeeded = true; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Aes.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Aes.Decrypt( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Aes).GetMethod(nameof(Aes.Decrypt), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Aes).GetMethod(nameof(Aes.Decrypt), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Aes.Decrypt( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Aes.Decrypt(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var right = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Aes.Decrypt(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AesBinaryOpTest__Decrypt_Vector128_Byte(); var result = Aes.Decrypt(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AesBinaryOpTest__Decrypt_Vector128_Byte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Aes.Decrypt(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Aes.Decrypt(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* result, [CallerMemberName] string method = "") { Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(outArray, method); } private void ValidateResult(Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < result.Length; i++) { if (result[i] != _expectedRet[i] ) { succeeded = false; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Aes)}.{nameof(Aes.Decrypt)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Decrypt_Vector128_Byte() { var test = new AesBinaryOpTest__Decrypt_Vector128_Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AesBinaryOpTest__Decrypt_Vector128_Byte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(AesBinaryOpTest__Decrypt_Vector128_Byte testClass) { var result = Aes.Decrypt(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AesBinaryOpTest__Decrypt_Vector128_Byte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[16] {0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88}; private static Byte[] _data2 = new Byte[16] {0xFF, 0xDD, 0xBB, 0x99, 0x77, 0x55, 0x33, 0x11, 0xEE, 0xCC, 0xAA, 0x88, 0x66, 0x44, 0x22, 0x00}; private static Byte[] _expectedRet = new Byte[16] {0x7C, 0x99, 0x02, 0x7C, 0x7C, 0x7C, 0xFE, 0x86, 0xE3, 0x7C, 0x7C, 0x97, 0xC9, 0x94, 0x7C, 0x7C}; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static AesBinaryOpTest__Decrypt_Vector128_Byte() { Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public AesBinaryOpTest__Decrypt_Vector128_Byte() { Succeeded = true; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Aes.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Aes.Decrypt( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Aes).GetMethod(nameof(Aes.Decrypt), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Aes).GetMethod(nameof(Aes.Decrypt), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Aes.Decrypt( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Aes.Decrypt(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var right = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Aes.Decrypt(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AesBinaryOpTest__Decrypt_Vector128_Byte(); var result = Aes.Decrypt(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AesBinaryOpTest__Decrypt_Vector128_Byte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Aes.Decrypt(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Aes.Decrypt(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Aes.Decrypt( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* result, [CallerMemberName] string method = "") { Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(outArray, method); } private void ValidateResult(Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < result.Length; i++) { if (result[i] != _expectedRet[i] ) { succeeded = false; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Aes)}.{nameof(Aes.Decrypt)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" expectedRet: ({string.Join(", ", _expectedRet)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Regression/JitBlue/GitHub_18291/GitHub_18291.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./eng/common/post-build/check-channel-consistency.ps1
param( [Parameter(Mandatory=$true)][string] $PromoteToChannels, # List of channels that the build should be promoted to [Parameter(Mandatory=$true)][array] $AvailableChannelIds # List of channel IDs available in the YAML implementation ) try { . $PSScriptRoot\post-build-utils.ps1 if ($PromoteToChannels -eq "") { Write-PipelineTaskError -Type 'warning' -Message "This build won't publish assets as it's not configured to any Maestro channel. If that wasn't intended use Darc to configure a default channel using add-default-channel for this branch or to promote it to a channel using add-build-to-channel. See https://github.com/dotnet/arcade/blob/master/Documentation/Darc.md#assigning-an-individual-build-to-a-channel for more info." ExitWithExitCode 0 } # Check that every channel that Maestro told to promote the build to # is available in YAML $PromoteToChannelsIds = $PromoteToChannels -split "\D" | Where-Object { $_ } $hasErrors = $false foreach ($id in $PromoteToChannelsIds) { if (($id -ne 0) -and ($id -notin $AvailableChannelIds)) { Write-PipelineTaskError -Message "Channel $id is not present in the post-build YAML configuration! This is an error scenario. Please contact @dnceng." $hasErrors = $true } } # The `Write-PipelineTaskError` doesn't error the script and we might report several errors # in the previous lines. The check below makes sure that we return an error state from the # script if we reported any validation error if ($hasErrors) { ExitWithExitCode 1 } Write-Host 'done.' } catch { Write-Host $_ Write-PipelineTelemetryError -Category 'CheckChannelConsistency' -Message "There was an error while trying to check consistency of Maestro default channels for the build and post-build YAML configuration." ExitWithExitCode 1 }
param( [Parameter(Mandatory=$true)][string] $PromoteToChannels, # List of channels that the build should be promoted to [Parameter(Mandatory=$true)][array] $AvailableChannelIds # List of channel IDs available in the YAML implementation ) try { . $PSScriptRoot\post-build-utils.ps1 if ($PromoteToChannels -eq "") { Write-PipelineTaskError -Type 'warning' -Message "This build won't publish assets as it's not configured to any Maestro channel. If that wasn't intended use Darc to configure a default channel using add-default-channel for this branch or to promote it to a channel using add-build-to-channel. See https://github.com/dotnet/arcade/blob/master/Documentation/Darc.md#assigning-an-individual-build-to-a-channel for more info." ExitWithExitCode 0 } # Check that every channel that Maestro told to promote the build to # is available in YAML $PromoteToChannelsIds = $PromoteToChannels -split "\D" | Where-Object { $_ } $hasErrors = $false foreach ($id in $PromoteToChannelsIds) { if (($id -ne 0) -and ($id -notin $AvailableChannelIds)) { Write-PipelineTaskError -Message "Channel $id is not present in the post-build YAML configuration! This is an error scenario. Please contact @dnceng." $hasErrors = $true } } # The `Write-PipelineTaskError` doesn't error the script and we might report several errors # in the previous lines. The check below makes sure that we return an error state from the # script if we reported any validation error if ($hasErrors) { ExitWithExitCode 1 } Write-Host 'done.' } catch { Write-Host $_ Write-PipelineTelemetryError -Category 'CheckChannelConsistency' -Message "There was an error while trying to check consistency of Maestro default channels for the build and post-build YAML configuration." ExitWithExitCode 1 }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Contains all GC static fields for a particular MethodTable. /// Fields that have preinitialized data are pointer reloc pointing to frozen objects. /// Other fields are initialized with 0. /// We simply memcpy these over the GC static MethodTable object. /// </summary> public class GCStaticsPreInitDataNode : ObjectNode, ISymbolDefinitionNode { private TypePreinit.PreinitializationInfo _preinitializationInfo; public GCStaticsPreInitDataNode(TypePreinit.PreinitializationInfo preinitializationInfo) { Debug.Assert(!preinitializationInfo.Type.IsCanonicalSubtype(CanonicalFormKind.Specific)); _preinitializationInfo = preinitializationInfo; } protected override string GetName(NodeFactory factory) => GetMangledName(_preinitializationInfo.Type, factory.NameMangler); public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(GetMangledName(_preinitializationInfo.Type, nameMangler)); } public int Offset => 0; public MetadataType Type => _preinitializationInfo.Type; public static string GetMangledName(TypeDesc type, NameMangler nameMangler) { return nameMangler.NodeMangler.GCStatics(type) + "__PreInitData"; } public override bool StaticDependenciesAreComputed => true; public override ObjectNodeSection Section { get { if (Type.Context.Target.IsWindows) return ObjectNodeSection.ReadOnlyDataSection; else return ObjectNodeSection.DataSection; } } public override bool IsShareable => EETypeNode.IsTypeNodeShareable(_preinitializationInfo.Type); public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); MetadataType type = _preinitializationInfo.Type; builder.RequireInitialAlignment(factory.Target.PointerSize); // GC static fields don't begin at offset 0, need to subtract that. int initialOffset = CompilerMetadataFieldLayoutAlgorithm.GetGCStaticFieldOffset(factory.TypeSystemContext).AsInt; foreach (FieldDesc field in type.GetFields()) { if (!field.IsStatic || field.HasRva || field.IsLiteral || field.IsThreadStatic || !field.HasGCStaticBase) continue; int padding = field.Offset.AsInt - initialOffset - builder.CountBytes; Debug.Assert(padding >= 0); builder.EmitZeros(padding); TypePreinit.ISerializableValue val = _preinitializationInfo.GetFieldValue(field); int currentOffset = builder.CountBytes; if (val != null) val.WriteFieldData(ref builder, field, factory); else builder.EmitZeroPointer(); Debug.Assert(builder.CountBytes - currentOffset == field.FieldType.GetElementSize().AsInt); } int pad = _preinitializationInfo.Type.GCStaticFieldSize.AsInt - builder.CountBytes - initialOffset; Debug.Assert(pad >= 0); builder.EmitZeros(pad); builder.AddSymbol(this); return builder.ToObjectData(); } public override int ClassCode => 1148300665; public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_preinitializationInfo.Type, ((GCStaticsPreInitDataNode)other)._preinitializationInfo.Type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Contains all GC static fields for a particular MethodTable. /// Fields that have preinitialized data are pointer reloc pointing to frozen objects. /// Other fields are initialized with 0. /// We simply memcpy these over the GC static MethodTable object. /// </summary> public class GCStaticsPreInitDataNode : ObjectNode, ISymbolDefinitionNode { private TypePreinit.PreinitializationInfo _preinitializationInfo; public GCStaticsPreInitDataNode(TypePreinit.PreinitializationInfo preinitializationInfo) { Debug.Assert(!preinitializationInfo.Type.IsCanonicalSubtype(CanonicalFormKind.Specific)); _preinitializationInfo = preinitializationInfo; } protected override string GetName(NodeFactory factory) => GetMangledName(_preinitializationInfo.Type, factory.NameMangler); public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(GetMangledName(_preinitializationInfo.Type, nameMangler)); } public int Offset => 0; public MetadataType Type => _preinitializationInfo.Type; public static string GetMangledName(TypeDesc type, NameMangler nameMangler) { return nameMangler.NodeMangler.GCStatics(type) + "__PreInitData"; } public override bool StaticDependenciesAreComputed => true; public override ObjectNodeSection Section { get { if (Type.Context.Target.IsWindows) return ObjectNodeSection.ReadOnlyDataSection; else return ObjectNodeSection.DataSection; } } public override bool IsShareable => EETypeNode.IsTypeNodeShareable(_preinitializationInfo.Type); public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); MetadataType type = _preinitializationInfo.Type; builder.RequireInitialAlignment(factory.Target.PointerSize); // GC static fields don't begin at offset 0, need to subtract that. int initialOffset = CompilerMetadataFieldLayoutAlgorithm.GetGCStaticFieldOffset(factory.TypeSystemContext).AsInt; foreach (FieldDesc field in type.GetFields()) { if (!field.IsStatic || field.HasRva || field.IsLiteral || field.IsThreadStatic || !field.HasGCStaticBase) continue; int padding = field.Offset.AsInt - initialOffset - builder.CountBytes; Debug.Assert(padding >= 0); builder.EmitZeros(padding); TypePreinit.ISerializableValue val = _preinitializationInfo.GetFieldValue(field); int currentOffset = builder.CountBytes; if (val != null) val.WriteFieldData(ref builder, field, factory); else builder.EmitZeroPointer(); Debug.Assert(builder.CountBytes - currentOffset == field.FieldType.GetElementSize().AsInt); } int pad = _preinitializationInfo.Type.GCStaticFieldSize.AsInt - builder.CountBytes - initialOffset; Debug.Assert(pad >= 0); builder.EmitZeros(pad); builder.AddSymbol(this); return builder.ToObjectData(); } public override int ClassCode => 1148300665; public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { return comparer.Compare(_preinitializationInfo.Type, ((GCStaticsPreInitDataNode)other)._preinitializationInfo.Type); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Runtime/tests/System/UInt16Tests.GenericMath.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Runtime.Versioning; using Xunit; namespace System.Tests { [RequiresPreviewFeaturesAttribute] public class UInt16Tests_GenericMath { [Fact] public static void AdditiveIdentityTest() { Assert.Equal((ushort)0x0000, AdditiveIdentityHelper<ushort, ushort>.AdditiveIdentity); } [Fact] public static void MinValueTest() { Assert.Equal((ushort)0x0000, MinMaxValueHelper<ushort>.MinValue); } [Fact] public static void MaxValueTest() { Assert.Equal((ushort)0xFFFF, MinMaxValueHelper<ushort>.MaxValue); } [Fact] public static void MultiplicativeIdentityTest() { Assert.Equal((ushort)0x0001, MultiplicativeIdentityHelper<ushort, ushort>.MultiplicativeIdentity); } [Fact] public static void OneTest() { Assert.Equal((ushort)0x0001, NumberHelper<ushort>.One); } [Fact] public static void ZeroTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Zero); } [Fact] public static void op_AdditionTest() { Assert.Equal((ushort)0x0001, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0002, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x8000, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8001, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0x0000, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0xFFFF, (ushort)1)); } [Fact] public static void LeadingZeroCountTest() { Assert.Equal((ushort)0x0010, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x0000)); Assert.Equal((ushort)0x000F, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x0001)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x7FFF)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x8000)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0xFFFF)); } [Fact] public static void PopCountTest() { Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.PopCount((ushort)0x0000)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.PopCount((ushort)0x0001)); Assert.Equal((ushort)0x000F, BinaryIntegerHelper<ushort>.PopCount((ushort)0x7FFF)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.PopCount((ushort)0x8000)); Assert.Equal((ushort)0x0010, BinaryIntegerHelper<ushort>.PopCount((ushort)0xFFFF)); } [Fact] public static void RotateLeftTest() { Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x0000, 1)); Assert.Equal((ushort)0x0002, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x0001, 1)); Assert.Equal((ushort)0xFFFE, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x8000, 1)); Assert.Equal((ushort)0xFFFF, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0xFFFF, 1)); } [Fact] public static void RotateRightTest() { Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x0000, 1)); Assert.Equal((ushort)0x8000, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x0001, 1)); Assert.Equal((ushort)0xBFFF, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x4000, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x8000, 1)); Assert.Equal((ushort)0xFFFF, BinaryIntegerHelper<ushort>.RotateRight((ushort)0xFFFF, 1)); } [Fact] public static void TrailingZeroCountTest() { Assert.Equal((ushort)0x0010, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x0000)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x0001)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x7FFF)); Assert.Equal((ushort)0x000F, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x8000)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0xFFFF)); } [Fact] public static void IsPow2Test() { Assert.False(BinaryNumberHelper<ushort>.IsPow2((ushort)0x0000)); Assert.True(BinaryNumberHelper<ushort>.IsPow2((ushort)0x0001)); Assert.False(BinaryNumberHelper<ushort>.IsPow2((ushort)0x7FFF)); Assert.True(BinaryNumberHelper<ushort>.IsPow2((ushort)0x8000)); Assert.False(BinaryNumberHelper<ushort>.IsPow2((ushort)0xFFFF)); } [Fact] public static void Log2Test() { Assert.Equal((ushort)0x0000, BinaryNumberHelper<ushort>.Log2((ushort)0x0000)); Assert.Equal((ushort)0x0000, BinaryNumberHelper<ushort>.Log2((ushort)0x0001)); Assert.Equal((ushort)0x000E, BinaryNumberHelper<ushort>.Log2((ushort)0x7FFF)); Assert.Equal((ushort)0x000F, BinaryNumberHelper<ushort>.Log2((ushort)0x8000)); Assert.Equal((ushort)0x000F, BinaryNumberHelper<ushort>.Log2((ushort)0xFFFF)); } [Fact] public static void op_BitwiseAndTest() { Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_BitwiseOrTest() { Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_ExclusiveOrTest() { Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFE, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFE, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_OnesComplementTest() { Assert.Equal((ushort)0xFFFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x0000)); Assert.Equal((ushort)0xFFFE, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x0001)); Assert.Equal((ushort)0x8000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x7FFF)); Assert.Equal((ushort)0x7FFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x8000)); Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0xFFFF)); } [Fact] public static void op_LessThanTest() { Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x0000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x0001, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x7FFF, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x8000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_LessThanOrEqualTest() { Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x0000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x0001, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x7FFF, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x8000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_GreaterThanTest() { Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x0000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x0001, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x7FFF, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x8000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_GreaterThanOrEqualTest() { Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x0000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x0001, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x7FFF, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x8000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_DecrementTest() { Assert.Equal((ushort)0xFFFF, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x0000)); Assert.Equal((ushort)0x0000, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x0001)); Assert.Equal((ushort)0x7FFE, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x7FFF)); Assert.Equal((ushort)0x7FFF, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x8000)); Assert.Equal((ushort)0xFFFE, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0xFFFF)); } [Fact] public static void op_DivisionTest() { Assert.Equal((ushort)0x0000, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x0000, (ushort)2)); Assert.Equal((ushort)0x0000, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x0001, (ushort)2)); Assert.Equal((ushort)0x3FFF, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x7FFF, (ushort)2)); Assert.Equal((ushort)0x4000, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x8000, (ushort)2)); Assert.Equal((ushort)0x7FFF, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0xFFFF, (ushort)2)); } [Fact] public static void op_EqualityTest() { Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x0000, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x0001, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x7FFF, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x8000, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_InequalityTest() { Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x0000, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x0001, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x7FFF, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x8000, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_IncrementTest() { Assert.Equal((ushort)0x0001, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x0000)); Assert.Equal((ushort)0x0002, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x0001)); Assert.Equal((ushort)0x8000, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x7FFF)); Assert.Equal((ushort)0x8001, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x8000)); Assert.Equal((ushort)0x0000, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0xFFFF)); } [Fact] public static void op_ModulusTest() { Assert.Equal((ushort)0x0000, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x0000, (ushort)2)); Assert.Equal((ushort)0x0001, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x0001, (ushort)2)); Assert.Equal((ushort)0x0001, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x7FFF, (ushort)2)); Assert.Equal((ushort)0x0000, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x8000, (ushort)2)); Assert.Equal((ushort)0x0001, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0xFFFF, (ushort)2)); } [Fact] public static void op_MultiplyTest() { Assert.Equal((ushort)0x0000, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x0000, (ushort)2)); Assert.Equal((ushort)0x0002, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x0001, (ushort)2)); Assert.Equal((ushort)0xFFFE, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x7FFF, (ushort)2)); Assert.Equal((ushort)0x0000, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x8000, (ushort)2)); Assert.Equal((ushort)0xFFFE, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0xFFFF, (ushort)2)); } [Fact] public static void AbsTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Abs((ushort)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Abs((ushort)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Abs((ushort)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Abs((ushort)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Abs((ushort)0xFFFF)); } [Fact] public static void ClampTest() { Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Clamp((ushort)0x0000, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Clamp((ushort)0x0001, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x003F, NumberHelper<ushort>.Clamp((ushort)0x7FFF, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x003F, NumberHelper<ushort>.Clamp((ushort)0x8000, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x003F, NumberHelper<ushort>.Clamp((ushort)0xFFFF, (ushort)0x0001, (ushort)0x003F)); } [Fact] public static void CreateFromByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<byte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<byte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.Create<byte>(0x7F)); Assert.Equal((ushort)0x0080, NumberHelper<ushort>.Create<byte>(0x80)); Assert.Equal((ushort)0x00FF, NumberHelper<ushort>.Create<byte>(0xFF)); } [Fact] public static void CreateFromCharTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<char>((char)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<char>((char)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Create<char>((char)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Create<char>((char)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Create<char>((char)0xFFFF)); } [Fact] public static void CreateFromInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<short>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<short>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Create<short>(0x7FFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<short>(unchecked((short)0x8000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<short>(unchecked((short)0xFFFF))); } [Fact] public static void CreateFromInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<int>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<int>(0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<int>(0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<int>(unchecked((int)0x80000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<int>(unchecked((int)0xFFFFFFFF))); } [Fact] public static void CreateFromInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<long>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<long>(0x0000000000000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<long>(0x7FFFFFFFFFFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<long>(unchecked((long)0x8000000000000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<long>(unchecked((long)0xFFFFFFFFFFFFFFFF))); } [Fact] public static void CreateFromIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nint>(unchecked((nint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nint>(unchecked((nint)0x0000000000000001))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0x8000000000000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nint>((nint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nint>((nint)0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>((nint)0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0x80000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0xFFFFFFFF))); } } [Fact] public static void CreateFromSByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<sbyte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<sbyte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.Create<sbyte>(0x7F)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<sbyte>(unchecked((sbyte)0x80))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<sbyte>(unchecked((sbyte)0xFF))); } [Fact] public static void CreateFromUInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<ushort>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<ushort>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Create<ushort>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Create<ushort>(0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Create<ushort>(0xFFFF)); } [Fact] public static void CreateFromUInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<uint>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<uint>(0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<uint>(0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<uint>(0x80000000)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<uint>(0xFFFFFFFF)); } [Fact] public static void CreateFromUInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<ulong>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<ulong>(0x0000000000000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<ulong>(0x7FFFFFFFFFFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<ulong>(0x8000000000000000)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<ulong>(0xFFFFFFFFFFFFFFFF)); } [Fact] public static void CreateFromUIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x0000000000000001))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x8000000000000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nuint>((nuint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nuint>((nuint)0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>((nuint)0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>((nuint)0x80000000)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>((nuint)0xFFFFFFFF)); } } [Fact] public static void CreateSaturatingFromByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<byte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<byte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateSaturating<byte>(0x7F)); Assert.Equal((ushort)0x0080, NumberHelper<ushort>.CreateSaturating<byte>(0x80)); Assert.Equal((ushort)0x00FF, NumberHelper<ushort>.CreateSaturating<byte>(0xFF)); } [Fact] public static void CreateSaturatingFromCharTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<char>((char)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<char>((char)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateSaturating<char>((char)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateSaturating<char>((char)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<char>((char)0xFFFF)); } [Fact] public static void CreateSaturatingFromInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<short>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<short>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateSaturating<short>(0x7FFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<short>(unchecked((short)0x8000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<short>(unchecked((short)0xFFFF))); } [Fact] public static void CreateSaturatingFromInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<int>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<int>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<int>(0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<int>(unchecked((int)0x80000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<int>(unchecked((int)0xFFFFFFFF))); } [Fact] public static void CreateSaturatingFromInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<long>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<long>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<long>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<long>(unchecked((long)0x8000000000000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<long>(unchecked((long)0xFFFFFFFFFFFFFFFF))); } [Fact] public static void CreateSaturatingFromIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x8000000000000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>((nint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nint>((nint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nint>((nint)0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x80000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0xFFFFFFFF))); } } [Fact] public static void CreateSaturatingFromSByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<sbyte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<sbyte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateSaturating<sbyte>(0x7F)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<sbyte>(unchecked((sbyte)0x80))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<sbyte>(unchecked((sbyte)0xFF))); } [Fact] public static void CreateSaturatingFromUInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<ushort>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<ushort>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateSaturating<ushort>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateSaturating<ushort>(0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ushort>(0xFFFF)); } [Fact] public static void CreateSaturatingFromUInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<uint>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<uint>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<uint>(0x7FFFFFFF)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<uint>(0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<uint>(0xFFFFFFFF)); } [Fact] public static void CreateSaturatingFromUInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<ulong>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<ulong>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ulong>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ulong>(0x8000000000000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ulong>(0xFFFFFFFFFFFFFFFF)); } [Fact] public static void CreateSaturatingFromUIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x7FFFFFFF)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0xFFFFFFFF)); } } [Fact] public static void CreateTruncatingFromByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<byte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<byte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateTruncating<byte>(0x7F)); Assert.Equal((ushort)0x0080, NumberHelper<ushort>.CreateTruncating<byte>(0x80)); Assert.Equal((ushort)0x00FF, NumberHelper<ushort>.CreateTruncating<byte>(0xFF)); } [Fact] public static void CreateTruncatingFromCharTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<char>((char)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<char>((char)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateTruncating<char>((char)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateTruncating<char>((char)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<char>((char)0xFFFF)); } [Fact] public static void CreateTruncatingFromInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<short>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<short>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateTruncating<short>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateTruncating<short>(unchecked((short)0x8000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<short>(unchecked((short)0xFFFF))); } [Fact] public static void CreateTruncatingFromInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<int>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<int>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<int>(0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<int>(unchecked((int)0x80000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<int>(unchecked((int)0xFFFFFFFF))); } [Fact] public static void CreateTruncatingFromInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<long>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<long>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<long>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<long>(unchecked((long)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<long>(unchecked((long)0xFFFFFFFFFFFFFFFF))); } [Fact] public static void CreateTruncatingFromIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>((nint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nint>((nint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>((nint)0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x80000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0xFFFFFFFF))); } } [Fact] public static void CreateTruncatingFromSByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<sbyte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<sbyte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateTruncating<sbyte>(0x7F)); Assert.Equal((ushort)0xFF80, NumberHelper<ushort>.CreateTruncating<sbyte>(unchecked((sbyte)0x80))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<sbyte>(unchecked((sbyte)0xFF))); } [Fact] public static void CreateTruncatingFromUInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<ushort>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<ushort>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateTruncating<ushort>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateTruncating<ushort>(0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<ushort>(0xFFFF)); } [Fact] public static void CreateTruncatingFromUInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<uint>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<uint>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<uint>(0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<uint>(0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<uint>(0xFFFFFFFF)); } [Fact] public static void CreateTruncatingFromUInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<ulong>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<ulong>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<ulong>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<ulong>(0x8000000000000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<ulong>(0xFFFFFFFFFFFFFFFF)); } [Fact] public static void CreateTruncatingFromUIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0xFFFFFFFF)); } } [Fact] public static void DivRemTest() { Assert.Equal(((ushort)0x0000, (ushort)0x0000), NumberHelper<ushort>.DivRem((ushort)0x0000, (ushort)2)); Assert.Equal(((ushort)0x0000, (ushort)0x0001), NumberHelper<ushort>.DivRem((ushort)0x0001, (ushort)2)); Assert.Equal(((ushort)0x3FFF, (ushort)0x0001), NumberHelper<ushort>.DivRem((ushort)0x7FFF, (ushort)2)); Assert.Equal(((ushort)0x4000, (ushort)0x0000), NumberHelper<ushort>.DivRem((ushort)0x8000, (ushort)2)); Assert.Equal(((ushort)0x7FFF, (ushort)0x0001), NumberHelper<ushort>.DivRem((ushort)0xFFFF, (ushort)2)); } [Fact] public static void MaxTest() { Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Max((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Max((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Max((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Max((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Max((ushort)0xFFFF, (ushort)1)); } [Fact] public static void MinTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Min((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0xFFFF, (ushort)1)); } [Fact] public static void SignTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Sign((ushort)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0x0001)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0x7FFF)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0x8000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0xFFFF)); } [Fact] public static void TryCreateFromByteTest() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x00, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x01, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x7F, out result)); Assert.Equal((ushort)0x007F, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x80, out result)); Assert.Equal((ushort)0x0080, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0xFF, out result)); Assert.Equal((ushort)0x00FF, result); } [Fact] public static void TryCreateFromCharTest() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x0000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x0001, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x7FFF, out result)); Assert.Equal((ushort)0x7FFF, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x8000, out result)); Assert.Equal((ushort)0x8000, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0xFFFF, out result)); Assert.Equal((ushort)0xFFFF, result); } [Fact] public static void TryCreateFromInt16Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<short>(0x0000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<short>(0x0001, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<short>(0x7FFF, out result)); Assert.Equal((ushort)0x7FFF, result); Assert.False(NumberHelper<ushort>.TryCreate<short>(unchecked((short)0x8000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<short>(unchecked((short)0xFFFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromInt32Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<int>(0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<int>(0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<int>(0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<int>(unchecked((int)0x80000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<int>(unchecked((int)0xFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromInt64Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<long>(0x0000000000000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<long>(0x0000000000000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<long>(0x7FFFFFFFFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<long>(unchecked((long)0x8000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<long>(unchecked((long)0xFFFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromIntPtrTest() { ushort result; if (Environment.Is64BitProcess) { Assert.True(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x0000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x0000000000000001), out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x8000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } else { Assert.True(NumberHelper<ushort>.TryCreate<nint>((nint)0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nint>((nint)0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>((nint)0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x80000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0xFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } } [Fact] public static void TryCreateFromSByteTest() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<sbyte>(0x00, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<sbyte>(0x01, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<sbyte>(0x7F, out result)); Assert.Equal((ushort)0x007F, result); Assert.False(NumberHelper<ushort>.TryCreate<sbyte>(unchecked((sbyte)0x80), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<sbyte>(unchecked((sbyte)0xFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromUInt16Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x0000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x0001, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x7FFF, out result)); Assert.Equal((ushort)0x7FFF, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x8000, out result)); Assert.Equal((ushort)0x8000, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0xFFFF, out result)); Assert.Equal((ushort)0xFFFF, result); } [Fact] public static void TryCreateFromUInt32Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<uint>(0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<uint>(0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<uint>(0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<uint>(0x80000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<uint>(0xFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromUInt64Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<ulong>(0x0000000000000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<ulong>(0x0000000000000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<ulong>(0x7FFFFFFFFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<ulong>(0x8000000000000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<ulong>(0xFFFFFFFFFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromUIntPtrTest() { ushort result; if (Environment.Is64BitProcess) { Assert.True(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x0000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x0000000000000001), out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x8000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } else { Assert.True(NumberHelper<ushort>.TryCreate<nuint>((nuint)0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nuint>((nuint)0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>((nuint)0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x80000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0xFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } } [Fact] public static void op_LeftShiftTest() { Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x0000, 1)); Assert.Equal((ushort)0x0002, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x0001, 1)); Assert.Equal((ushort)0xFFFE, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x8000, 1)); Assert.Equal((ushort)0xFFFE, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0xFFFF, 1)); } [Fact] public static void op_RightShiftTest() { Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x0000, 1)); Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x0001, 1)); Assert.Equal((ushort)0x3FFF, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x4000, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x8000, 1)); Assert.Equal((ushort)0x7FFF, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0xFFFF, 1)); } [Fact] public static void op_SubtractionTest() { Assert.Equal((ushort)0xFFFF, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0000, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFE, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x7FFF, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFE, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_UnaryNegationTest() { Assert.Equal((ushort)0x0000, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x0000)); Assert.Equal((ushort)0xFFFF, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x0001)); Assert.Equal((ushort)0x8001, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x7FFF)); Assert.Equal((ushort)0x8000, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x8000)); Assert.Equal((ushort)0x0001, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0xFFFF)); } [Fact] public static void op_UnaryPlusTest() { Assert.Equal((ushort)0x0000, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x0000)); Assert.Equal((ushort)0x0001, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x0001)); Assert.Equal((ushort)0x7FFF, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x7FFF)); Assert.Equal((ushort)0x8000, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x8000)); Assert.Equal((ushort)0xFFFF, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0xFFFF)); } [Theory] [MemberData(nameof(UInt16Tests.Parse_Valid_TestData), MemberType = typeof(UInt16Tests))] public static void ParseValidStringTest(string value, NumberStyles style, IFormatProvider provider, ushort expected) { ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.True(ParseableHelper<ushort>.TryParse(value, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, ParseableHelper<ushort>.Parse(value, provider)); } // Default provider if (provider is null) { Assert.Equal(expected, NumberHelper<ushort>.Parse(value, style, provider)); // Substitute default NumberFormatInfo Assert.True(NumberHelper<ushort>.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<ushort>.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Equal(expected, ParseableHelper<ushort>.Parse(value, provider)); } // Full overloads Assert.True(NumberHelper<ushort>.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<ushort>.Parse(value, style, provider)); } [Theory] [MemberData(nameof(UInt16Tests.Parse_Invalid_TestData), MemberType = typeof(UInt16Tests))] public static void ParseInvalidStringTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.False(ParseableHelper<ushort>.TryParse(value, provider, out result)); Assert.Equal(default(ushort), result); Assert.Throws(exceptionType, () => ParseableHelper<ushort>.Parse(value, provider)); } // Default provider if (provider is null) { Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value, style, provider)); // Substitute default NumberFormatInfo Assert.False(NumberHelper<ushort>.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(default(ushort), result); Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Throws(exceptionType, () => ParseableHelper<ushort>.Parse(value, provider)); } // Full overloads Assert.False(NumberHelper<ushort>.TryParse(value, style, provider, out result)); Assert.Equal(default(ushort), result); Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value, style, provider)); } [Theory] [MemberData(nameof(UInt16Tests.Parse_ValidWithOffsetCount_TestData), MemberType = typeof(UInt16Tests))] public static void ParseValidSpanTest(string value, int offset, int count, NumberStyles style, IFormatProvider provider, ushort expected) { ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.True(SpanParseableHelper<ushort>.TryParse(value.AsSpan(offset, count), provider, out result)); Assert.Equal(expected, result); } Assert.Equal(expected, NumberHelper<ushort>.Parse(value.AsSpan(offset, count), style, provider)); Assert.True(NumberHelper<ushort>.TryParse(value.AsSpan(offset, count), style, provider, out result)); Assert.Equal(expected, result); } [Theory] [MemberData(nameof(UInt16Tests.Parse_Invalid_TestData), MemberType = typeof(UInt16Tests))] public static void ParseInvalidSpanTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (value is null) { return; } ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.False(SpanParseableHelper<ushort>.TryParse(value.AsSpan(), provider, out result)); Assert.Equal(default(ushort), result); } Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value.AsSpan(), style, provider)); Assert.False(NumberHelper<ushort>.TryParse(value.AsSpan(), style, provider, out result)); Assert.Equal(default(ushort), result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.Runtime.Versioning; using Xunit; namespace System.Tests { [RequiresPreviewFeaturesAttribute] public class UInt16Tests_GenericMath { [Fact] public static void AdditiveIdentityTest() { Assert.Equal((ushort)0x0000, AdditiveIdentityHelper<ushort, ushort>.AdditiveIdentity); } [Fact] public static void MinValueTest() { Assert.Equal((ushort)0x0000, MinMaxValueHelper<ushort>.MinValue); } [Fact] public static void MaxValueTest() { Assert.Equal((ushort)0xFFFF, MinMaxValueHelper<ushort>.MaxValue); } [Fact] public static void MultiplicativeIdentityTest() { Assert.Equal((ushort)0x0001, MultiplicativeIdentityHelper<ushort, ushort>.MultiplicativeIdentity); } [Fact] public static void OneTest() { Assert.Equal((ushort)0x0001, NumberHelper<ushort>.One); } [Fact] public static void ZeroTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Zero); } [Fact] public static void op_AdditionTest() { Assert.Equal((ushort)0x0001, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0002, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x8000, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8001, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0x0000, AdditionOperatorsHelper<ushort, ushort, ushort>.op_Addition((ushort)0xFFFF, (ushort)1)); } [Fact] public static void LeadingZeroCountTest() { Assert.Equal((ushort)0x0010, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x0000)); Assert.Equal((ushort)0x000F, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x0001)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x7FFF)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0x8000)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.LeadingZeroCount((ushort)0xFFFF)); } [Fact] public static void PopCountTest() { Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.PopCount((ushort)0x0000)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.PopCount((ushort)0x0001)); Assert.Equal((ushort)0x000F, BinaryIntegerHelper<ushort>.PopCount((ushort)0x7FFF)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.PopCount((ushort)0x8000)); Assert.Equal((ushort)0x0010, BinaryIntegerHelper<ushort>.PopCount((ushort)0xFFFF)); } [Fact] public static void RotateLeftTest() { Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x0000, 1)); Assert.Equal((ushort)0x0002, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x0001, 1)); Assert.Equal((ushort)0xFFFE, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x0001, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0x8000, 1)); Assert.Equal((ushort)0xFFFF, BinaryIntegerHelper<ushort>.RotateLeft((ushort)0xFFFF, 1)); } [Fact] public static void RotateRightTest() { Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x0000, 1)); Assert.Equal((ushort)0x8000, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x0001, 1)); Assert.Equal((ushort)0xBFFF, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x4000, BinaryIntegerHelper<ushort>.RotateRight((ushort)0x8000, 1)); Assert.Equal((ushort)0xFFFF, BinaryIntegerHelper<ushort>.RotateRight((ushort)0xFFFF, 1)); } [Fact] public static void TrailingZeroCountTest() { Assert.Equal((ushort)0x0010, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x0000)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x0001)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x7FFF)); Assert.Equal((ushort)0x000F, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0x8000)); Assert.Equal((ushort)0x0000, BinaryIntegerHelper<ushort>.TrailingZeroCount((ushort)0xFFFF)); } [Fact] public static void IsPow2Test() { Assert.False(BinaryNumberHelper<ushort>.IsPow2((ushort)0x0000)); Assert.True(BinaryNumberHelper<ushort>.IsPow2((ushort)0x0001)); Assert.False(BinaryNumberHelper<ushort>.IsPow2((ushort)0x7FFF)); Assert.True(BinaryNumberHelper<ushort>.IsPow2((ushort)0x8000)); Assert.False(BinaryNumberHelper<ushort>.IsPow2((ushort)0xFFFF)); } [Fact] public static void Log2Test() { Assert.Equal((ushort)0x0000, BinaryNumberHelper<ushort>.Log2((ushort)0x0000)); Assert.Equal((ushort)0x0000, BinaryNumberHelper<ushort>.Log2((ushort)0x0001)); Assert.Equal((ushort)0x000E, BinaryNumberHelper<ushort>.Log2((ushort)0x7FFF)); Assert.Equal((ushort)0x000F, BinaryNumberHelper<ushort>.Log2((ushort)0x8000)); Assert.Equal((ushort)0x000F, BinaryNumberHelper<ushort>.Log2((ushort)0xFFFF)); } [Fact] public static void op_BitwiseAndTest() { Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseAnd((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_BitwiseOrTest() { Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_BitwiseOr((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_ExclusiveOrTest() { Assert.Equal((ushort)0x0001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFE, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8001, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFE, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_ExclusiveOr((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_OnesComplementTest() { Assert.Equal((ushort)0xFFFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x0000)); Assert.Equal((ushort)0xFFFE, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x0001)); Assert.Equal((ushort)0x8000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x7FFF)); Assert.Equal((ushort)0x7FFF, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0x8000)); Assert.Equal((ushort)0x0000, BitwiseOperatorsHelper<ushort, ushort, ushort>.op_OnesComplement((ushort)0xFFFF)); } [Fact] public static void op_LessThanTest() { Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x0000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x0001, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x7FFF, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0x8000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThan((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_LessThanOrEqualTest() { Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x0000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x0001, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x7FFF, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0x8000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_LessThanOrEqual((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_GreaterThanTest() { Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x0000, (ushort)1)); Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x0001, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x7FFF, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0x8000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThan((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_GreaterThanOrEqualTest() { Assert.False(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x0000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x0001, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x7FFF, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0x8000, (ushort)1)); Assert.True(ComparisonOperatorsHelper<ushort, ushort>.op_GreaterThanOrEqual((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_DecrementTest() { Assert.Equal((ushort)0xFFFF, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x0000)); Assert.Equal((ushort)0x0000, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x0001)); Assert.Equal((ushort)0x7FFE, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x7FFF)); Assert.Equal((ushort)0x7FFF, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0x8000)); Assert.Equal((ushort)0xFFFE, DecrementOperatorsHelper<ushort>.op_Decrement((ushort)0xFFFF)); } [Fact] public static void op_DivisionTest() { Assert.Equal((ushort)0x0000, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x0000, (ushort)2)); Assert.Equal((ushort)0x0000, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x0001, (ushort)2)); Assert.Equal((ushort)0x3FFF, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x7FFF, (ushort)2)); Assert.Equal((ushort)0x4000, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0x8000, (ushort)2)); Assert.Equal((ushort)0x7FFF, DivisionOperatorsHelper<ushort, ushort, ushort>.op_Division((ushort)0xFFFF, (ushort)2)); } [Fact] public static void op_EqualityTest() { Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x0000, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x0001, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x7FFF, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0x8000, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Equality((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_InequalityTest() { Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x0000, (ushort)1)); Assert.False(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x0001, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x7FFF, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0x8000, (ushort)1)); Assert.True(EqualityOperatorsHelper<ushort, ushort>.op_Inequality((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_IncrementTest() { Assert.Equal((ushort)0x0001, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x0000)); Assert.Equal((ushort)0x0002, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x0001)); Assert.Equal((ushort)0x8000, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x7FFF)); Assert.Equal((ushort)0x8001, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0x8000)); Assert.Equal((ushort)0x0000, IncrementOperatorsHelper<ushort>.op_Increment((ushort)0xFFFF)); } [Fact] public static void op_ModulusTest() { Assert.Equal((ushort)0x0000, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x0000, (ushort)2)); Assert.Equal((ushort)0x0001, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x0001, (ushort)2)); Assert.Equal((ushort)0x0001, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x7FFF, (ushort)2)); Assert.Equal((ushort)0x0000, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0x8000, (ushort)2)); Assert.Equal((ushort)0x0001, ModulusOperatorsHelper<ushort, ushort, ushort>.op_Modulus((ushort)0xFFFF, (ushort)2)); } [Fact] public static void op_MultiplyTest() { Assert.Equal((ushort)0x0000, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x0000, (ushort)2)); Assert.Equal((ushort)0x0002, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x0001, (ushort)2)); Assert.Equal((ushort)0xFFFE, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x7FFF, (ushort)2)); Assert.Equal((ushort)0x0000, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0x8000, (ushort)2)); Assert.Equal((ushort)0xFFFE, MultiplyOperatorsHelper<ushort, ushort, ushort>.op_Multiply((ushort)0xFFFF, (ushort)2)); } [Fact] public static void AbsTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Abs((ushort)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Abs((ushort)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Abs((ushort)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Abs((ushort)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Abs((ushort)0xFFFF)); } [Fact] public static void ClampTest() { Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Clamp((ushort)0x0000, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Clamp((ushort)0x0001, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x003F, NumberHelper<ushort>.Clamp((ushort)0x7FFF, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x003F, NumberHelper<ushort>.Clamp((ushort)0x8000, (ushort)0x0001, (ushort)0x003F)); Assert.Equal((ushort)0x003F, NumberHelper<ushort>.Clamp((ushort)0xFFFF, (ushort)0x0001, (ushort)0x003F)); } [Fact] public static void CreateFromByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<byte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<byte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.Create<byte>(0x7F)); Assert.Equal((ushort)0x0080, NumberHelper<ushort>.Create<byte>(0x80)); Assert.Equal((ushort)0x00FF, NumberHelper<ushort>.Create<byte>(0xFF)); } [Fact] public static void CreateFromCharTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<char>((char)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<char>((char)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Create<char>((char)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Create<char>((char)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Create<char>((char)0xFFFF)); } [Fact] public static void CreateFromInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<short>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<short>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Create<short>(0x7FFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<short>(unchecked((short)0x8000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<short>(unchecked((short)0xFFFF))); } [Fact] public static void CreateFromInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<int>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<int>(0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<int>(0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<int>(unchecked((int)0x80000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<int>(unchecked((int)0xFFFFFFFF))); } [Fact] public static void CreateFromInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<long>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<long>(0x0000000000000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<long>(0x7FFFFFFFFFFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<long>(unchecked((long)0x8000000000000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<long>(unchecked((long)0xFFFFFFFFFFFFFFFF))); } [Fact] public static void CreateFromIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nint>(unchecked((nint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nint>(unchecked((nint)0x0000000000000001))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0x8000000000000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nint>((nint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nint>((nint)0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>((nint)0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0x80000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nint>(unchecked((nint)0xFFFFFFFF))); } } [Fact] public static void CreateFromSByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<sbyte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<sbyte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.Create<sbyte>(0x7F)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<sbyte>(unchecked((sbyte)0x80))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<sbyte>(unchecked((sbyte)0xFF))); } [Fact] public static void CreateFromUInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<ushort>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<ushort>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Create<ushort>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Create<ushort>(0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Create<ushort>(0xFFFF)); } [Fact] public static void CreateFromUInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<uint>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<uint>(0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<uint>(0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<uint>(0x80000000)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<uint>(0xFFFFFFFF)); } [Fact] public static void CreateFromUInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<ulong>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<ulong>(0x0000000000000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<ulong>(0x7FFFFFFFFFFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<ulong>(0x8000000000000000)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<ulong>(0xFFFFFFFFFFFFFFFF)); } [Fact] public static void CreateFromUIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x0000000000000001))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0x8000000000000000))); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Create<nuint>((nuint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Create<nuint>((nuint)0x00000001)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>((nuint)0x7FFFFFFF)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>((nuint)0x80000000)); Assert.Throws<OverflowException>(() => NumberHelper<ushort>.Create<nuint>((nuint)0xFFFFFFFF)); } } [Fact] public static void CreateSaturatingFromByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<byte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<byte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateSaturating<byte>(0x7F)); Assert.Equal((ushort)0x0080, NumberHelper<ushort>.CreateSaturating<byte>(0x80)); Assert.Equal((ushort)0x00FF, NumberHelper<ushort>.CreateSaturating<byte>(0xFF)); } [Fact] public static void CreateSaturatingFromCharTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<char>((char)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<char>((char)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateSaturating<char>((char)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateSaturating<char>((char)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<char>((char)0xFFFF)); } [Fact] public static void CreateSaturatingFromInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<short>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<short>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateSaturating<short>(0x7FFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<short>(unchecked((short)0x8000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<short>(unchecked((short)0xFFFF))); } [Fact] public static void CreateSaturatingFromInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<int>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<int>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<int>(0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<int>(unchecked((int)0x80000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<int>(unchecked((int)0xFFFFFFFF))); } [Fact] public static void CreateSaturatingFromInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<long>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<long>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<long>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<long>(unchecked((long)0x8000000000000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<long>(unchecked((long)0xFFFFFFFFFFFFFFFF))); } [Fact] public static void CreateSaturatingFromIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x8000000000000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>((nint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nint>((nint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nint>((nint)0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0x80000000))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nint>(unchecked((nint)0xFFFFFFFF))); } } [Fact] public static void CreateSaturatingFromSByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<sbyte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<sbyte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateSaturating<sbyte>(0x7F)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<sbyte>(unchecked((sbyte)0x80))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<sbyte>(unchecked((sbyte)0xFF))); } [Fact] public static void CreateSaturatingFromUInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<ushort>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<ushort>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateSaturating<ushort>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateSaturating<ushort>(0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ushort>(0xFFFF)); } [Fact] public static void CreateSaturatingFromUInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<uint>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<uint>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<uint>(0x7FFFFFFF)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<uint>(0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<uint>(0xFFFFFFFF)); } [Fact] public static void CreateSaturatingFromUInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<ulong>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<ulong>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ulong>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ulong>(0x8000000000000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<ulong>(0xFFFFFFFFFFFFFFFF)); } [Fact] public static void CreateSaturatingFromUIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x7FFFFFFF)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateSaturating<nuint>((nuint)0xFFFFFFFF)); } } [Fact] public static void CreateTruncatingFromByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<byte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<byte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateTruncating<byte>(0x7F)); Assert.Equal((ushort)0x0080, NumberHelper<ushort>.CreateTruncating<byte>(0x80)); Assert.Equal((ushort)0x00FF, NumberHelper<ushort>.CreateTruncating<byte>(0xFF)); } [Fact] public static void CreateTruncatingFromCharTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<char>((char)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<char>((char)0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateTruncating<char>((char)0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateTruncating<char>((char)0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<char>((char)0xFFFF)); } [Fact] public static void CreateTruncatingFromInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<short>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<short>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateTruncating<short>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateTruncating<short>(unchecked((short)0x8000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<short>(unchecked((short)0xFFFF))); } [Fact] public static void CreateTruncatingFromInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<int>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<int>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<int>(0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<int>(unchecked((int)0x80000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<int>(unchecked((int)0xFFFFFFFF))); } [Fact] public static void CreateTruncatingFromInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<long>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<long>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<long>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<long>(unchecked((long)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<long>(unchecked((long)0xFFFFFFFFFFFFFFFF))); } [Fact] public static void CreateTruncatingFromIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>((nint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nint>((nint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>((nint)0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0x80000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nint>(unchecked((nint)0xFFFFFFFF))); } } [Fact] public static void CreateTruncatingFromSByteTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<sbyte>(0x00)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<sbyte>(0x01)); Assert.Equal((ushort)0x007F, NumberHelper<ushort>.CreateTruncating<sbyte>(0x7F)); Assert.Equal((ushort)0xFF80, NumberHelper<ushort>.CreateTruncating<sbyte>(unchecked((sbyte)0x80))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<sbyte>(unchecked((sbyte)0xFF))); } [Fact] public static void CreateTruncatingFromUInt16Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<ushort>(0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<ushort>(0x0001)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.CreateTruncating<ushort>(0x7FFF)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.CreateTruncating<ushort>(0x8000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<ushort>(0xFFFF)); } [Fact] public static void CreateTruncatingFromUInt32Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<uint>(0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<uint>(0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<uint>(0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<uint>(0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<uint>(0xFFFFFFFF)); } [Fact] public static void CreateTruncatingFromUInt64Test() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<ulong>(0x0000000000000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<ulong>(0x0000000000000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<ulong>(0x7FFFFFFFFFFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<ulong>(0x8000000000000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<ulong>(0xFFFFFFFFFFFFFFFF)); } [Fact] public static void CreateTruncatingFromUIntPtrTest() { if (Environment.Is64BitProcess) { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x0000000000000000))); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x0000000000000001))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF))); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0x8000000000000000))); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF))); } else { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x00000000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x00000001)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x7FFFFFFF)); Assert.Equal((ushort)0x0000, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0x80000000)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.CreateTruncating<nuint>((nuint)0xFFFFFFFF)); } } [Fact] public static void DivRemTest() { Assert.Equal(((ushort)0x0000, (ushort)0x0000), NumberHelper<ushort>.DivRem((ushort)0x0000, (ushort)2)); Assert.Equal(((ushort)0x0000, (ushort)0x0001), NumberHelper<ushort>.DivRem((ushort)0x0001, (ushort)2)); Assert.Equal(((ushort)0x3FFF, (ushort)0x0001), NumberHelper<ushort>.DivRem((ushort)0x7FFF, (ushort)2)); Assert.Equal(((ushort)0x4000, (ushort)0x0000), NumberHelper<ushort>.DivRem((ushort)0x8000, (ushort)2)); Assert.Equal(((ushort)0x7FFF, (ushort)0x0001), NumberHelper<ushort>.DivRem((ushort)0xFFFF, (ushort)2)); } [Fact] public static void MaxTest() { Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Max((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Max((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFF, NumberHelper<ushort>.Max((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x8000, NumberHelper<ushort>.Max((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFF, NumberHelper<ushort>.Max((ushort)0xFFFF, (ushort)1)); } [Fact] public static void MinTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Min((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Min((ushort)0xFFFF, (ushort)1)); } [Fact] public static void SignTest() { Assert.Equal((ushort)0x0000, NumberHelper<ushort>.Sign((ushort)0x0000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0x0001)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0x7FFF)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0x8000)); Assert.Equal((ushort)0x0001, NumberHelper<ushort>.Sign((ushort)0xFFFF)); } [Fact] public static void TryCreateFromByteTest() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x00, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x01, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x7F, out result)); Assert.Equal((ushort)0x007F, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0x80, out result)); Assert.Equal((ushort)0x0080, result); Assert.True(NumberHelper<ushort>.TryCreate<byte>(0xFF, out result)); Assert.Equal((ushort)0x00FF, result); } [Fact] public static void TryCreateFromCharTest() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x0000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x0001, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x7FFF, out result)); Assert.Equal((ushort)0x7FFF, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0x8000, out result)); Assert.Equal((ushort)0x8000, result); Assert.True(NumberHelper<ushort>.TryCreate<char>((char)0xFFFF, out result)); Assert.Equal((ushort)0xFFFF, result); } [Fact] public static void TryCreateFromInt16Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<short>(0x0000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<short>(0x0001, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<short>(0x7FFF, out result)); Assert.Equal((ushort)0x7FFF, result); Assert.False(NumberHelper<ushort>.TryCreate<short>(unchecked((short)0x8000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<short>(unchecked((short)0xFFFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromInt32Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<int>(0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<int>(0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<int>(0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<int>(unchecked((int)0x80000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<int>(unchecked((int)0xFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromInt64Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<long>(0x0000000000000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<long>(0x0000000000000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<long>(0x7FFFFFFFFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<long>(unchecked((long)0x8000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<long>(unchecked((long)0xFFFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromIntPtrTest() { ushort result; if (Environment.Is64BitProcess) { Assert.True(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x0000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x0000000000000001), out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x7FFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x8000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0xFFFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } else { Assert.True(NumberHelper<ushort>.TryCreate<nint>((nint)0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nint>((nint)0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>((nint)0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0x80000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nint>(unchecked((nint)0xFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } } [Fact] public static void TryCreateFromSByteTest() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<sbyte>(0x00, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<sbyte>(0x01, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<sbyte>(0x7F, out result)); Assert.Equal((ushort)0x007F, result); Assert.False(NumberHelper<ushort>.TryCreate<sbyte>(unchecked((sbyte)0x80), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<sbyte>(unchecked((sbyte)0xFF), out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromUInt16Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x0000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x0001, out result)); Assert.Equal((ushort)0x0001, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x7FFF, out result)); Assert.Equal((ushort)0x7FFF, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0x8000, out result)); Assert.Equal((ushort)0x8000, result); Assert.True(NumberHelper<ushort>.TryCreate<ushort>(0xFFFF, out result)); Assert.Equal((ushort)0xFFFF, result); } [Fact] public static void TryCreateFromUInt32Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<uint>(0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<uint>(0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<uint>(0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<uint>(0x80000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<uint>(0xFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromUInt64Test() { ushort result; Assert.True(NumberHelper<ushort>.TryCreate<ulong>(0x0000000000000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<ulong>(0x0000000000000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<ulong>(0x7FFFFFFFFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<ulong>(0x8000000000000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<ulong>(0xFFFFFFFFFFFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); } [Fact] public static void TryCreateFromUIntPtrTest() { ushort result; if (Environment.Is64BitProcess) { Assert.True(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x0000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x0000000000000001), out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x7FFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x8000000000000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0xFFFFFFFFFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } else { Assert.True(NumberHelper<ushort>.TryCreate<nuint>((nuint)0x00000000, out result)); Assert.Equal((ushort)0x0000, result); Assert.True(NumberHelper<ushort>.TryCreate<nuint>((nuint)0x00000001, out result)); Assert.Equal((ushort)0x0001, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>((nuint)0x7FFFFFFF, out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0x80000000), out result)); Assert.Equal((ushort)0x0000, result); Assert.False(NumberHelper<ushort>.TryCreate<nuint>(unchecked((nuint)0xFFFFFFFF), out result)); Assert.Equal((ushort)0x0000, result); } } [Fact] public static void op_LeftShiftTest() { Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x0000, 1)); Assert.Equal((ushort)0x0002, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x0001, 1)); Assert.Equal((ushort)0xFFFE, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0x8000, 1)); Assert.Equal((ushort)0xFFFE, ShiftOperatorsHelper<ushort, ushort>.op_LeftShift((ushort)0xFFFF, 1)); } [Fact] public static void op_RightShiftTest() { Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x0000, 1)); Assert.Equal((ushort)0x0000, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x0001, 1)); Assert.Equal((ushort)0x3FFF, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x7FFF, 1)); Assert.Equal((ushort)0x4000, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0x8000, 1)); Assert.Equal((ushort)0x7FFF, ShiftOperatorsHelper<ushort, ushort>.op_RightShift((ushort)0xFFFF, 1)); } [Fact] public static void op_SubtractionTest() { Assert.Equal((ushort)0xFFFF, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x0000, (ushort)1)); Assert.Equal((ushort)0x0000, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x0001, (ushort)1)); Assert.Equal((ushort)0x7FFE, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x7FFF, (ushort)1)); Assert.Equal((ushort)0x7FFF, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0x8000, (ushort)1)); Assert.Equal((ushort)0xFFFE, SubtractionOperatorsHelper<ushort, ushort, ushort>.op_Subtraction((ushort)0xFFFF, (ushort)1)); } [Fact] public static void op_UnaryNegationTest() { Assert.Equal((ushort)0x0000, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x0000)); Assert.Equal((ushort)0xFFFF, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x0001)); Assert.Equal((ushort)0x8001, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x7FFF)); Assert.Equal((ushort)0x8000, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0x8000)); Assert.Equal((ushort)0x0001, UnaryNegationOperatorsHelper<ushort, ushort>.op_UnaryNegation((ushort)0xFFFF)); } [Fact] public static void op_UnaryPlusTest() { Assert.Equal((ushort)0x0000, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x0000)); Assert.Equal((ushort)0x0001, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x0001)); Assert.Equal((ushort)0x7FFF, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x7FFF)); Assert.Equal((ushort)0x8000, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0x8000)); Assert.Equal((ushort)0xFFFF, UnaryPlusOperatorsHelper<ushort, ushort>.op_UnaryPlus((ushort)0xFFFF)); } [Theory] [MemberData(nameof(UInt16Tests.Parse_Valid_TestData), MemberType = typeof(UInt16Tests))] public static void ParseValidStringTest(string value, NumberStyles style, IFormatProvider provider, ushort expected) { ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.True(ParseableHelper<ushort>.TryParse(value, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, ParseableHelper<ushort>.Parse(value, provider)); } // Default provider if (provider is null) { Assert.Equal(expected, NumberHelper<ushort>.Parse(value, style, provider)); // Substitute default NumberFormatInfo Assert.True(NumberHelper<ushort>.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<ushort>.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Equal(expected, ParseableHelper<ushort>.Parse(value, provider)); } // Full overloads Assert.True(NumberHelper<ushort>.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, NumberHelper<ushort>.Parse(value, style, provider)); } [Theory] [MemberData(nameof(UInt16Tests.Parse_Invalid_TestData), MemberType = typeof(UInt16Tests))] public static void ParseInvalidStringTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.False(ParseableHelper<ushort>.TryParse(value, provider, out result)); Assert.Equal(default(ushort), result); Assert.Throws(exceptionType, () => ParseableHelper<ushort>.Parse(value, provider)); } // Default provider if (provider is null) { Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value, style, provider)); // Substitute default NumberFormatInfo Assert.False(NumberHelper<ushort>.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(default(ushort), result); Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Throws(exceptionType, () => ParseableHelper<ushort>.Parse(value, provider)); } // Full overloads Assert.False(NumberHelper<ushort>.TryParse(value, style, provider, out result)); Assert.Equal(default(ushort), result); Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value, style, provider)); } [Theory] [MemberData(nameof(UInt16Tests.Parse_ValidWithOffsetCount_TestData), MemberType = typeof(UInt16Tests))] public static void ParseValidSpanTest(string value, int offset, int count, NumberStyles style, IFormatProvider provider, ushort expected) { ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.True(SpanParseableHelper<ushort>.TryParse(value.AsSpan(offset, count), provider, out result)); Assert.Equal(expected, result); } Assert.Equal(expected, NumberHelper<ushort>.Parse(value.AsSpan(offset, count), style, provider)); Assert.True(NumberHelper<ushort>.TryParse(value.AsSpan(offset, count), style, provider, out result)); Assert.Equal(expected, result); } [Theory] [MemberData(nameof(UInt16Tests.Parse_Invalid_TestData), MemberType = typeof(UInt16Tests))] public static void ParseInvalidSpanTest(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { if (value is null) { return; } ushort result; // Default style and provider if ((style == NumberStyles.Integer) && (provider is null)) { Assert.False(SpanParseableHelper<ushort>.TryParse(value.AsSpan(), provider, out result)); Assert.Equal(default(ushort), result); } Assert.Throws(exceptionType, () => NumberHelper<ushort>.Parse(value.AsSpan(), style, provider)); Assert.False(NumberHelper<ushort>.TryParse(value.AsSpan(), style, provider, out result)); Assert.Equal(default(ushort), result); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryValueOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.Win32 { [Flags] public enum RegistryValueOptions { None = 0, DoNotExpandEnvironmentNames = 1 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.Win32 { [Flags] public enum RegistryValueOptions { None = 0, DoNotExpandEnvironmentNames = 1 } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Methodical/explicit/misc/refarg_box_val_il_r.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="refarg_box_val.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="refarg_box_val.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/SqlUtils.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers.Binary; using System.Collections; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; namespace System.Xml { // This is mostly just a copy of code in SqlTypes.SqlDecimal internal struct BinXmlSqlDecimal { internal byte m_bLen; internal byte m_bPrec; internal byte m_bScale; internal byte m_bSign; internal uint m_data1; internal uint m_data2; internal uint m_data3; internal uint m_data4; public bool IsPositive { get { return (m_bSign == 0); } } private const byte s_NUMERIC_MAX_PRECISION = 38; // Maximum precision of numeric private const byte s_maxPrecision = s_NUMERIC_MAX_PRECISION; // max SS precision private const int s_cNumeMax = 4; internal const ulong x_llMax = long.MaxValue; // Max of Int64 public BinXmlSqlDecimal(byte[] data, int offset, bool trim) { byte b = data[offset]; m_bLen = b switch { 7 => 1, 11 => 2, 15 => 3, 19 => 4, _ => throw new XmlException(SR.XmlBinary_InvalidSqlDecimal, (string[]?)null), }; m_bPrec = data[offset + 1]; m_bScale = data[offset + 2]; m_bSign = 0 == data[offset + 3] ? (byte)1 : (byte)0; m_data1 = UIntFromByteArray(data, offset + 4); m_data2 = (m_bLen > 1) ? UIntFromByteArray(data, offset + 8) : 0; m_data3 = (m_bLen > 2) ? UIntFromByteArray(data, offset + 12) : 0; m_data4 = (m_bLen > 3) ? UIntFromByteArray(data, offset + 16) : 0; if (m_bLen == 4 && m_data4 == 0) m_bLen = 3; if (m_bLen == 3 && m_data3 == 0) m_bLen = 2; if (m_bLen == 2 && m_data2 == 0) m_bLen = 1; AssertValid(); if (trim) { TrimTrailingZeros(); AssertValid(); } } private static uint UIntFromByteArray(byte[] data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(offset)); // Multi-precision one super-digit divide in place. // U = U / D, // R = U % D // Length of U can decrease private static void MpDiv1(uint[] rgulU, // InOut| U ref int ciulU, // InOut| # of digits in U uint iulD, // In | D out uint iulR // Out | R ) { Debug.Assert(rgulU.Length == s_cNumeMax); uint ulCarry = 0; ulong dwlAccum; ulong ulD = (ulong)iulD; int idU = ciulU; Debug.Assert(iulD != 0, "iulD != 0", "Divided by zero!"); Debug.Assert(iulD > 0, "iulD > 0", "Invalid data: less than zero"); Debug.Assert(ciulU > 0, "ciulU > 0", "No data in the array"); while (idU > 0) { idU--; dwlAccum = (((ulong)ulCarry) << 32) + (ulong)(rgulU[idU]); rgulU[idU] = (uint)(dwlAccum / ulD); ulCarry = (uint)(dwlAccum - (ulong)rgulU[idU] * ulD); // (ULONG) (dwlAccum % iulD) } iulR = ulCarry; MpNormalize(rgulU, ref ciulU); } // Normalize multi-precision number - remove leading zeroes private static void MpNormalize(uint[] rgulU, // In | Number ref int ciulU // InOut| # of digits ) { while (ciulU > 1 && rgulU[ciulU - 1] == 0) ciulU--; } //Determine the number of uints needed for a numeric given a precision //Precision Length // 0 invalid // 1-9 1 // 10-19 2 // 20-28 3 // 29-38 4 // The array in Shiloh. Listed here for comparison. //private static readonly byte[] rgCLenFromPrec = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9, // 9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17}; private static ReadOnlySpan<byte> RgCLenFromPrec => new byte[] { // rely on C# compiler optimization to eliminate allocation 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; private static byte CLenFromPrec(byte bPrec) { Debug.Assert(bPrec <= s_maxPrecision && bPrec > 0, "bPrec <= MaxPrecision && bPrec > 0", "Invalid numeric precision"); return RgCLenFromPrec[bPrec - 1]; } private static char ChFromDigit(uint uiDigit) { Debug.Assert(uiDigit < 10); return (char)(uiDigit + '0'); } public decimal ToDecimal() { if ((int)m_data4 != 0 || m_bScale > 28) throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); return new decimal((int)m_data1, (int)m_data2, (int)m_data3, !IsPositive, m_bScale); } private void TrimTrailingZeros() { uint[] rgulNumeric = new uint[4] { m_data1, m_data2, m_data3, m_data4 }; int culLen = m_bLen; uint ulRem; //Remainder of a division by x_ulBase10, i.e.,least significant digit // special-case 0 if (culLen == 1 && rgulNumeric[0] == 0) { m_bScale = 0; return; } while (m_bScale > 0 && (culLen > 1 || rgulNumeric[0] != 0)) { MpDiv1(rgulNumeric, ref culLen, 10, out ulRem); if (ulRem == 0) { m_data1 = rgulNumeric[0]; m_data2 = rgulNumeric[1]; m_data3 = rgulNumeric[2]; m_data4 = rgulNumeric[3]; m_bScale--; } else { break; } } if (m_bLen == 4 && m_data4 == 0) m_bLen = 3; if (m_bLen == 3 && m_data3 == 0) m_bLen = 2; if (m_bLen == 2 && m_data2 == 0) m_bLen = 1; } public override string ToString() { AssertValid(); // Make local copy of data to avoid modifying input. uint[] rgulNumeric = new uint[4] { m_data1, m_data2, m_data3, m_data4 }; int culLen = m_bLen; char[] pszTmp = new char[s_NUMERIC_MAX_PRECISION + 1]; //Local Character buffer to hold //the decimal digits, from the //lowest significant to highest significant int iDigits = 0; //Number of significant digits uint ulRem; //Remainder of a division by x_ulBase10, i.e.,least significant digit // Build the final numeric string by inserting the sign, reversing // the order and inserting the decimal number at the correct position //Retrieve each digit from the lowest significant digit while (culLen > 1 || rgulNumeric[0] != 0) { MpDiv1(rgulNumeric, ref culLen, 10, out ulRem); //modulo x_ulBase10 is the lowest significant digit pszTmp[iDigits++] = ChFromDigit(ulRem); } // if scale of the number has not been // reached pad remaining number with zeros. while (iDigits <= m_bScale) { pszTmp[iDigits++] = ChFromDigit(0); } bool fPositive = IsPositive; // Increment the result length if negative (need to add '-') int uiResultLen = fPositive ? iDigits : iDigits + 1; // Increment the result length if scale > 0 (need to add '.') if (m_bScale > 0) uiResultLen++; char[] szResult = new char[uiResultLen]; int iCurChar = 0; if (!fPositive) szResult[iCurChar++] = '-'; while (iDigits > 0) { if (iDigits-- == m_bScale) szResult[iCurChar++] = '.'; szResult[iCurChar++] = pszTmp[iDigits]; } AssertValid(); return new string(szResult); } // Is this RE numeric valid? [System.Diagnostics.Conditional("DEBUG")] private void AssertValid() { // Scale,Prec in range Debug.Assert(m_bScale <= s_NUMERIC_MAX_PRECISION, "m_bScale <= NUMERIC_MAX_PRECISION", "In AssertValid"); Debug.Assert(m_bScale <= m_bPrec, "m_bScale <= m_bPrec", "In AssertValid"); Debug.Assert(m_bScale >= 0, "m_bScale >= 0", "In AssertValid"); Debug.Assert(m_bPrec > 0, "m_bPrec > 0", "In AssertValid"); Debug.Assert(CLenFromPrec(m_bPrec) >= m_bLen, "CLenFromPrec(m_bPrec) >= m_bLen", "In AssertValid"); Debug.Assert(m_bLen <= s_cNumeMax, "m_bLen <= x_cNumeMax", "In AssertValid"); uint[] rglData = new uint[4] { m_data1, m_data2, m_data3, m_data4 }; // highest UI4 is non-0 unless value "zero" if (rglData[m_bLen - 1] == 0) { Debug.Assert(m_bLen == 1, "m_bLen == 1", "In AssertValid"); } // All UI4s from length to end are 0 for (int iulData = m_bLen; iulData < s_cNumeMax; iulData++) Debug.Assert(rglData[iulData] == 0, "rglData[iulData] == 0", "In AssertValid"); } } internal struct BinXmlSqlMoney { private readonly long _data; public BinXmlSqlMoney(int v) { _data = v; } public BinXmlSqlMoney(long v) { _data = v; } public decimal ToDecimal() { bool neg; ulong v; if (_data < 0) { neg = true; v = (ulong)unchecked(-_data); } else { neg = false; v = (ulong)_data; } // SQL Server stores money8 as ticks of 1/10000. const byte MoneyScale = 4; return new decimal(unchecked((int)v), unchecked((int)(v >> 32)), 0, neg, MoneyScale); } public override string ToString() { decimal money = ToDecimal(); // Formatting of SqlMoney: At least two digits after decimal point return money.ToString("#0.00##", CultureInfo.InvariantCulture); } } internal abstract class BinXmlDateTime { private const int MaxFractionDigits = 7; internal static int[] KatmaiTimeScaleMultiplicator = new int[8] { 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, }; private static void Write2Dig(StringBuilder sb, int val) { Debug.Assert(val >= 0 && val < 100); sb.Append((char)('0' + (val / 10))); sb.Append((char)('0' + (val % 10))); } private static void Write4DigNeg(StringBuilder sb, int val) { Debug.Assert(val > -10000 && val < 10000); if (val < 0) { val = -val; sb.Append('-'); } Write2Dig(sb, val / 100); Write2Dig(sb, val % 100); } private static void Write3Dec(StringBuilder sb, int val) { Debug.Assert(val >= 0 && val < 1000); int c3 = val % 10; val /= 10; int c2 = val % 10; val /= 10; int c1 = val; sb.Append('.'); sb.Append((char)('0' + c1)); sb.Append((char)('0' + c2)); sb.Append((char)('0' + c3)); } private static void WriteDate(StringBuilder sb, int yr, int mnth, int day) { Write4DigNeg(sb, yr); sb.Append('-'); Write2Dig(sb, mnth); sb.Append('-'); Write2Dig(sb, day); } private static void WriteTime(StringBuilder sb, int hr, int min, int sec, int ms) { Write2Dig(sb, hr); sb.Append(':'); Write2Dig(sb, min); sb.Append(':'); Write2Dig(sb, sec); if (ms != 0) { Write3Dec(sb, ms); } } private static void WriteTimeFullPrecision(StringBuilder sb, int hr, int min, int sec, int fraction) { Write2Dig(sb, hr); sb.Append(':'); Write2Dig(sb, min); sb.Append(':'); Write2Dig(sb, sec); if (fraction != 0) { int fractionDigits = MaxFractionDigits; while (fraction % 10 == 0) { fractionDigits--; fraction /= 10; } char[] charArray = new char[fractionDigits]; while (fractionDigits > 0) { fractionDigits--; charArray[fractionDigits] = (char)(fraction % 10 + '0'); fraction /= 10; } sb.Append('.'); sb.Append(charArray); } } private static void WriteTimeZone(StringBuilder sb, TimeSpan zone) { bool negTimeZone = true; if (zone.Ticks < 0) { negTimeZone = false; zone = zone.Negate(); } WriteTimeZone(sb, negTimeZone, zone.Hours, zone.Minutes); } private static void WriteTimeZone(StringBuilder sb, bool negTimeZone, int hr, int min) { if (hr == 0 && min == 0) { sb.Append('Z'); } else { sb.Append(negTimeZone ? '+' : '-'); Write2Dig(sb, hr); sb.Append(':'); Write2Dig(sb, min); } } private static void BreakDownXsdDateTime(long val, out int yr, out int mnth, out int day, out int hr, out int min, out int sec, out int ms) { if (val < 0) goto Error; long date = val / 4; // trim indicator bits ms = (int)(date % 1000); date /= 1000; sec = (int)(date % 60); date /= 60; min = (int)(date % 60); date /= 60; hr = (int)(date % 24); date /= 24; day = (int)(date % 31) + 1; date /= 31; mnth = (int)(date % 12) + 1; date /= 12; yr = (int)(date - 9999); if (yr < -9999 || yr > 9999) goto Error; return; Error: throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } private static void BreakDownXsdDate(long val, out int yr, out int mnth, out int day, out bool negTimeZone, out int hr, out int min) { if (val < 0) goto Error; val = val / 4; // trim indicator bits int totalMin = (int)(val % (29 * 60)) - 60 * 14; long totalDays = val / (29 * 60); if (negTimeZone = (totalMin < 0)) totalMin = -totalMin; min = totalMin % 60; hr = totalMin / 60; day = (int)(totalDays % 31) + 1; totalDays /= 31; mnth = (int)(totalDays % 12) + 1; yr = (int)(totalDays / 12) - 9999; if (yr < -9999 || yr > 9999) goto Error; return; Error: throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } private static void BreakDownXsdTime(long val, out int hr, out int min, out int sec, out int ms) { if (val < 0) goto Error; val = val / 4; // trim indicator bits ms = (int)(val % 1000); val /= 1000; sec = (int)(val % 60); val /= 60; min = (int)(val % 60); hr = (int)(val / 60); if (0 > hr || hr > 23) goto Error; return; Error: throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } public static string XsdDateTimeToString(long val) { int yr; int mnth; int day; int hr; int min; int sec; int ms; BreakDownXsdDateTime(val, out yr, out mnth, out day, out hr, out min, out sec, out ms); StringBuilder sb = new StringBuilder(20); WriteDate(sb, yr, mnth, day); sb.Append('T'); WriteTime(sb, hr, min, sec, ms); sb.Append('Z'); return sb.ToString(); } public static DateTime XsdDateTimeToDateTime(long val) { int yr; int mnth; int day; int hr; int min; int sec; int ms; BreakDownXsdDateTime(val, out yr, out mnth, out day, out hr, out min, out sec, out ms); return new DateTime(yr, mnth, day, hr, min, sec, ms, DateTimeKind.Utc); } public static string XsdDateToString(long val) { int yr; int mnth; int day; int hr; int min; bool negTimeZ; BreakDownXsdDate(val, out yr, out mnth, out day, out negTimeZ, out hr, out min); StringBuilder sb = new StringBuilder(20); WriteDate(sb, yr, mnth, day); WriteTimeZone(sb, negTimeZ, hr, min); return sb.ToString(); } public static DateTime XsdDateToDateTime(long val) { int yr; int mnth; int day; int hr; int min; bool negTimeZ; BreakDownXsdDate(val, out yr, out mnth, out day, out negTimeZ, out hr, out min); DateTime d = new DateTime(yr, mnth, day, 0, 0, 0, DateTimeKind.Utc); // adjust for timezone int adj = (negTimeZ ? -1 : 1) * ((hr * 60) + min); return TimeZoneInfo.ConvertTime(d.AddMinutes(adj), TimeZoneInfo.Local); } public static string XsdTimeToString(long val) { int hr; int min; int sec; int ms; BreakDownXsdTime(val, out hr, out min, out sec, out ms); StringBuilder sb = new StringBuilder(16); WriteTime(sb, hr, min, sec, ms); sb.Append('Z'); return sb.ToString(); } public static DateTime XsdTimeToDateTime(long val) { int hr; int min; int sec; int ms; BreakDownXsdTime(val, out hr, out min, out sec, out ms); return new DateTime(1, 1, 1, hr, min, sec, ms, DateTimeKind.Utc); } public static string SqlDateTimeToString(int dateticks, uint timeticks) { DateTime dateTime = SqlDateTimeToDateTime(dateticks, timeticks); string format = (dateTime.Millisecond != 0) ? "yyyy/MM/dd\\THH:mm:ss.ffff" : "yyyy/MM/dd\\THH:mm:ss"; return dateTime.ToString(format, CultureInfo.InvariantCulture); } public static DateTime SqlDateTimeToDateTime(int dateticks, uint timeticks) { DateTime SQLBaseDate = new DateTime(1900, 1, 1); //long millisecond = (long)(((ulong)timeticks * 20 + (ulong)3) / (ulong)6); long millisecond = (long)(timeticks / s_SQLTicksPerMillisecond + 0.5); return SQLBaseDate.Add(new TimeSpan(dateticks * TimeSpan.TicksPerDay + millisecond * TimeSpan.TicksPerMillisecond)); } // Number of (100ns) ticks per time unit private const double s_SQLTicksPerMillisecond = 0.3; internal const int SQLTicksPerSecond = 300; internal const int SQLTicksPerMinute = SQLTicksPerSecond * 60; internal const int SQLTicksPerHour = SQLTicksPerMinute * 60; public static string SqlSmallDateTimeToString(short dateticks, ushort timeticks) { DateTime dateTime = SqlSmallDateTimeToDateTime(dateticks, timeticks); return dateTime.ToString("yyyy/MM/dd\\THH:mm:ss", CultureInfo.InvariantCulture); } public static DateTime SqlSmallDateTimeToDateTime(short dateticks, ushort timeticks) { return SqlDateTimeToDateTime((int)dateticks, (uint)(timeticks * SQLTicksPerMinute)); } // Conversions of the Katmai date & time types to DateTime public static DateTime XsdKatmaiDateToDateTime(byte[] data, int offset) { // Katmai SQL type "DATE" long dateTicks = GetKatmaiDateTicks(data, ref offset); DateTime dt = new DateTime(dateTicks); return dt; } public static DateTime XsdKatmaiDateTimeToDateTime(byte[] data, int offset) { // Katmai SQL type "DATETIME2" long timeTicks = GetKatmaiTimeTicks(data, ref offset); long dateTicks = GetKatmaiDateTicks(data, ref offset); DateTime dt = new DateTime(dateTicks + timeTicks); return dt; } public static DateTime XsdKatmaiTimeToDateTime(byte[] data, int offset) { // TIME without zone is stored as DATETIME2 return XsdKatmaiDateTimeToDateTime(data, offset); } public static DateTime XsdKatmaiDateOffsetToDateTime(byte[] data, int offset) { // read the timezoned value into DateTimeOffset and then convert to local time return XsdKatmaiDateOffsetToDateTimeOffset(data, offset).LocalDateTime; } public static DateTime XsdKatmaiDateTimeOffsetToDateTime(byte[] data, int offset) { // read the timezoned value into DateTimeOffset and then convert to local time return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset).LocalDateTime; } public static DateTime XsdKatmaiTimeOffsetToDateTime(byte[] data, int offset) { // read the timezoned value into DateTimeOffset and then convert to local time return XsdKatmaiTimeOffsetToDateTimeOffset(data, offset).LocalDateTime; } public static DateTimeOffset XsdKatmaiDateOffsetToDateTimeOffset(byte[] data, int offset) { // DATE with zone is stored as DATETIMEOFFSET return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset); } public static DateTimeOffset XsdKatmaiDateTimeOffsetToDateTimeOffset(byte[] data, int offset) { // Katmai SQL type "DATETIMEOFFSET" long timeTicks = GetKatmaiTimeTicks(data, ref offset); long dateTicks = GetKatmaiDateTicks(data, ref offset); long zoneTicks = GetKatmaiTimeZoneTicks(data, offset); // The DATETIMEOFFSET values are serialized in UTC, but DateTimeOffset takes adjusted time -> we need to add zoneTicks DateTimeOffset dto = new DateTimeOffset(dateTicks + timeTicks + zoneTicks, new TimeSpan(zoneTicks)); return dto; } public static DateTimeOffset XsdKatmaiTimeOffsetToDateTimeOffset(byte[] data, int offset) { // TIME with zone is stored as DATETIMEOFFSET return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset); } // Conversions of the Katmai date & time types to string public static string XsdKatmaiDateToString(byte[] data, int offset) { DateTime dt = XsdKatmaiDateToDateTime(data, offset); StringBuilder sb = new StringBuilder(10); WriteDate(sb, dt.Year, dt.Month, dt.Day); return sb.ToString(); } public static string XsdKatmaiDateTimeToString(byte[] data, int offset) { DateTime dt = XsdKatmaiDateTimeToDateTime(data, offset); StringBuilder sb = new StringBuilder(33); WriteDate(sb, dt.Year, dt.Month, dt.Day); sb.Append('T'); WriteTimeFullPrecision(sb, dt.Hour, dt.Minute, dt.Second, GetFractions(dt)); return sb.ToString(); } public static string XsdKatmaiTimeToString(byte[] data, int offset) { DateTime dt = XsdKatmaiTimeToDateTime(data, offset); StringBuilder sb = new StringBuilder(16); WriteTimeFullPrecision(sb, dt.Hour, dt.Minute, dt.Second, GetFractions(dt)); return sb.ToString(); } public static string XsdKatmaiDateOffsetToString(byte[] data, int offset) { DateTimeOffset dto = XsdKatmaiDateOffsetToDateTimeOffset(data, offset); StringBuilder sb = new StringBuilder(16); WriteDate(sb, dto.Year, dto.Month, dto.Day); WriteTimeZone(sb, dto.Offset); return sb.ToString(); } public static string XsdKatmaiDateTimeOffsetToString(byte[] data, int offset) { DateTimeOffset dto = XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset); StringBuilder sb = new StringBuilder(39); WriteDate(sb, dto.Year, dto.Month, dto.Day); sb.Append('T'); WriteTimeFullPrecision(sb, dto.Hour, dto.Minute, dto.Second, GetFractions(dto)); WriteTimeZone(sb, dto.Offset); return sb.ToString(); } public static string XsdKatmaiTimeOffsetToString(byte[] data, int offset) { DateTimeOffset dto = XsdKatmaiTimeOffsetToDateTimeOffset(data, offset); StringBuilder sb = new StringBuilder(22); WriteTimeFullPrecision(sb, dto.Hour, dto.Minute, dto.Second, GetFractions(dto)); WriteTimeZone(sb, dto.Offset); return sb.ToString(); } // Helper methods for the Katmai date & time types private static long GetKatmaiDateTicks(byte[] data, ref int pos) { int p = pos; pos = p + 3; return (data[p] | data[p + 1] << 8 | data[p + 2] << 16) * TimeSpan.TicksPerDay; } private static long GetKatmaiTimeTicks(byte[] data, ref int pos) { int p = pos; byte scale = data[p]; long timeTicks; p++; if (scale <= 2) { timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16); pos = p + 3; } else if (scale <= 4) { timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16); timeTicks |= ((long)data[p + 3] << 24); pos = p + 4; } else if (scale <= 7) { timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16); timeTicks |= ((long)data[p + 3] << 24) | ((long)data[p + 4] << 32); pos = p + 5; } else { throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } return timeTicks * KatmaiTimeScaleMultiplicator[scale]; } private static long GetKatmaiTimeZoneTicks(byte[] data, int pos) { return (short)(data[pos] | data[pos + 1] << 8) * TimeSpan.TicksPerMinute; } private static int GetFractions(DateTime dt) { return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks); } private static int GetFractions(DateTimeOffset dt) { return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers.Binary; using System.Collections; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; namespace System.Xml { // This is mostly just a copy of code in SqlTypes.SqlDecimal internal struct BinXmlSqlDecimal { internal byte m_bLen; internal byte m_bPrec; internal byte m_bScale; internal byte m_bSign; internal uint m_data1; internal uint m_data2; internal uint m_data3; internal uint m_data4; public bool IsPositive { get { return (m_bSign == 0); } } private const byte s_NUMERIC_MAX_PRECISION = 38; // Maximum precision of numeric private const byte s_maxPrecision = s_NUMERIC_MAX_PRECISION; // max SS precision private const int s_cNumeMax = 4; internal const ulong x_llMax = long.MaxValue; // Max of Int64 public BinXmlSqlDecimal(byte[] data, int offset, bool trim) { byte b = data[offset]; m_bLen = b switch { 7 => 1, 11 => 2, 15 => 3, 19 => 4, _ => throw new XmlException(SR.XmlBinary_InvalidSqlDecimal, (string[]?)null), }; m_bPrec = data[offset + 1]; m_bScale = data[offset + 2]; m_bSign = 0 == data[offset + 3] ? (byte)1 : (byte)0; m_data1 = UIntFromByteArray(data, offset + 4); m_data2 = (m_bLen > 1) ? UIntFromByteArray(data, offset + 8) : 0; m_data3 = (m_bLen > 2) ? UIntFromByteArray(data, offset + 12) : 0; m_data4 = (m_bLen > 3) ? UIntFromByteArray(data, offset + 16) : 0; if (m_bLen == 4 && m_data4 == 0) m_bLen = 3; if (m_bLen == 3 && m_data3 == 0) m_bLen = 2; if (m_bLen == 2 && m_data2 == 0) m_bLen = 1; AssertValid(); if (trim) { TrimTrailingZeros(); AssertValid(); } } private static uint UIntFromByteArray(byte[] data, int offset) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(offset)); // Multi-precision one super-digit divide in place. // U = U / D, // R = U % D // Length of U can decrease private static void MpDiv1(uint[] rgulU, // InOut| U ref int ciulU, // InOut| # of digits in U uint iulD, // In | D out uint iulR // Out | R ) { Debug.Assert(rgulU.Length == s_cNumeMax); uint ulCarry = 0; ulong dwlAccum; ulong ulD = (ulong)iulD; int idU = ciulU; Debug.Assert(iulD != 0, "iulD != 0", "Divided by zero!"); Debug.Assert(iulD > 0, "iulD > 0", "Invalid data: less than zero"); Debug.Assert(ciulU > 0, "ciulU > 0", "No data in the array"); while (idU > 0) { idU--; dwlAccum = (((ulong)ulCarry) << 32) + (ulong)(rgulU[idU]); rgulU[idU] = (uint)(dwlAccum / ulD); ulCarry = (uint)(dwlAccum - (ulong)rgulU[idU] * ulD); // (ULONG) (dwlAccum % iulD) } iulR = ulCarry; MpNormalize(rgulU, ref ciulU); } // Normalize multi-precision number - remove leading zeroes private static void MpNormalize(uint[] rgulU, // In | Number ref int ciulU // InOut| # of digits ) { while (ciulU > 1 && rgulU[ciulU - 1] == 0) ciulU--; } //Determine the number of uints needed for a numeric given a precision //Precision Length // 0 invalid // 1-9 1 // 10-19 2 // 20-28 3 // 29-38 4 // The array in Shiloh. Listed here for comparison. //private static readonly byte[] rgCLenFromPrec = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9, // 9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17}; private static ReadOnlySpan<byte> RgCLenFromPrec => new byte[] { // rely on C# compiler optimization to eliminate allocation 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; private static byte CLenFromPrec(byte bPrec) { Debug.Assert(bPrec <= s_maxPrecision && bPrec > 0, "bPrec <= MaxPrecision && bPrec > 0", "Invalid numeric precision"); return RgCLenFromPrec[bPrec - 1]; } private static char ChFromDigit(uint uiDigit) { Debug.Assert(uiDigit < 10); return (char)(uiDigit + '0'); } public decimal ToDecimal() { if ((int)m_data4 != 0 || m_bScale > 28) throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); return new decimal((int)m_data1, (int)m_data2, (int)m_data3, !IsPositive, m_bScale); } private void TrimTrailingZeros() { uint[] rgulNumeric = new uint[4] { m_data1, m_data2, m_data3, m_data4 }; int culLen = m_bLen; uint ulRem; //Remainder of a division by x_ulBase10, i.e.,least significant digit // special-case 0 if (culLen == 1 && rgulNumeric[0] == 0) { m_bScale = 0; return; } while (m_bScale > 0 && (culLen > 1 || rgulNumeric[0] != 0)) { MpDiv1(rgulNumeric, ref culLen, 10, out ulRem); if (ulRem == 0) { m_data1 = rgulNumeric[0]; m_data2 = rgulNumeric[1]; m_data3 = rgulNumeric[2]; m_data4 = rgulNumeric[3]; m_bScale--; } else { break; } } if (m_bLen == 4 && m_data4 == 0) m_bLen = 3; if (m_bLen == 3 && m_data3 == 0) m_bLen = 2; if (m_bLen == 2 && m_data2 == 0) m_bLen = 1; } public override string ToString() { AssertValid(); // Make local copy of data to avoid modifying input. uint[] rgulNumeric = new uint[4] { m_data1, m_data2, m_data3, m_data4 }; int culLen = m_bLen; char[] pszTmp = new char[s_NUMERIC_MAX_PRECISION + 1]; //Local Character buffer to hold //the decimal digits, from the //lowest significant to highest significant int iDigits = 0; //Number of significant digits uint ulRem; //Remainder of a division by x_ulBase10, i.e.,least significant digit // Build the final numeric string by inserting the sign, reversing // the order and inserting the decimal number at the correct position //Retrieve each digit from the lowest significant digit while (culLen > 1 || rgulNumeric[0] != 0) { MpDiv1(rgulNumeric, ref culLen, 10, out ulRem); //modulo x_ulBase10 is the lowest significant digit pszTmp[iDigits++] = ChFromDigit(ulRem); } // if scale of the number has not been // reached pad remaining number with zeros. while (iDigits <= m_bScale) { pszTmp[iDigits++] = ChFromDigit(0); } bool fPositive = IsPositive; // Increment the result length if negative (need to add '-') int uiResultLen = fPositive ? iDigits : iDigits + 1; // Increment the result length if scale > 0 (need to add '.') if (m_bScale > 0) uiResultLen++; char[] szResult = new char[uiResultLen]; int iCurChar = 0; if (!fPositive) szResult[iCurChar++] = '-'; while (iDigits > 0) { if (iDigits-- == m_bScale) szResult[iCurChar++] = '.'; szResult[iCurChar++] = pszTmp[iDigits]; } AssertValid(); return new string(szResult); } // Is this RE numeric valid? [System.Diagnostics.Conditional("DEBUG")] private void AssertValid() { // Scale,Prec in range Debug.Assert(m_bScale <= s_NUMERIC_MAX_PRECISION, "m_bScale <= NUMERIC_MAX_PRECISION", "In AssertValid"); Debug.Assert(m_bScale <= m_bPrec, "m_bScale <= m_bPrec", "In AssertValid"); Debug.Assert(m_bScale >= 0, "m_bScale >= 0", "In AssertValid"); Debug.Assert(m_bPrec > 0, "m_bPrec > 0", "In AssertValid"); Debug.Assert(CLenFromPrec(m_bPrec) >= m_bLen, "CLenFromPrec(m_bPrec) >= m_bLen", "In AssertValid"); Debug.Assert(m_bLen <= s_cNumeMax, "m_bLen <= x_cNumeMax", "In AssertValid"); uint[] rglData = new uint[4] { m_data1, m_data2, m_data3, m_data4 }; // highest UI4 is non-0 unless value "zero" if (rglData[m_bLen - 1] == 0) { Debug.Assert(m_bLen == 1, "m_bLen == 1", "In AssertValid"); } // All UI4s from length to end are 0 for (int iulData = m_bLen; iulData < s_cNumeMax; iulData++) Debug.Assert(rglData[iulData] == 0, "rglData[iulData] == 0", "In AssertValid"); } } internal struct BinXmlSqlMoney { private readonly long _data; public BinXmlSqlMoney(int v) { _data = v; } public BinXmlSqlMoney(long v) { _data = v; } public decimal ToDecimal() { bool neg; ulong v; if (_data < 0) { neg = true; v = (ulong)unchecked(-_data); } else { neg = false; v = (ulong)_data; } // SQL Server stores money8 as ticks of 1/10000. const byte MoneyScale = 4; return new decimal(unchecked((int)v), unchecked((int)(v >> 32)), 0, neg, MoneyScale); } public override string ToString() { decimal money = ToDecimal(); // Formatting of SqlMoney: At least two digits after decimal point return money.ToString("#0.00##", CultureInfo.InvariantCulture); } } internal abstract class BinXmlDateTime { private const int MaxFractionDigits = 7; internal static int[] KatmaiTimeScaleMultiplicator = new int[8] { 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, }; private static void Write2Dig(StringBuilder sb, int val) { Debug.Assert(val >= 0 && val < 100); sb.Append((char)('0' + (val / 10))); sb.Append((char)('0' + (val % 10))); } private static void Write4DigNeg(StringBuilder sb, int val) { Debug.Assert(val > -10000 && val < 10000); if (val < 0) { val = -val; sb.Append('-'); } Write2Dig(sb, val / 100); Write2Dig(sb, val % 100); } private static void Write3Dec(StringBuilder sb, int val) { Debug.Assert(val >= 0 && val < 1000); int c3 = val % 10; val /= 10; int c2 = val % 10; val /= 10; int c1 = val; sb.Append('.'); sb.Append((char)('0' + c1)); sb.Append((char)('0' + c2)); sb.Append((char)('0' + c3)); } private static void WriteDate(StringBuilder sb, int yr, int mnth, int day) { Write4DigNeg(sb, yr); sb.Append('-'); Write2Dig(sb, mnth); sb.Append('-'); Write2Dig(sb, day); } private static void WriteTime(StringBuilder sb, int hr, int min, int sec, int ms) { Write2Dig(sb, hr); sb.Append(':'); Write2Dig(sb, min); sb.Append(':'); Write2Dig(sb, sec); if (ms != 0) { Write3Dec(sb, ms); } } private static void WriteTimeFullPrecision(StringBuilder sb, int hr, int min, int sec, int fraction) { Write2Dig(sb, hr); sb.Append(':'); Write2Dig(sb, min); sb.Append(':'); Write2Dig(sb, sec); if (fraction != 0) { int fractionDigits = MaxFractionDigits; while (fraction % 10 == 0) { fractionDigits--; fraction /= 10; } char[] charArray = new char[fractionDigits]; while (fractionDigits > 0) { fractionDigits--; charArray[fractionDigits] = (char)(fraction % 10 + '0'); fraction /= 10; } sb.Append('.'); sb.Append(charArray); } } private static void WriteTimeZone(StringBuilder sb, TimeSpan zone) { bool negTimeZone = true; if (zone.Ticks < 0) { negTimeZone = false; zone = zone.Negate(); } WriteTimeZone(sb, negTimeZone, zone.Hours, zone.Minutes); } private static void WriteTimeZone(StringBuilder sb, bool negTimeZone, int hr, int min) { if (hr == 0 && min == 0) { sb.Append('Z'); } else { sb.Append(negTimeZone ? '+' : '-'); Write2Dig(sb, hr); sb.Append(':'); Write2Dig(sb, min); } } private static void BreakDownXsdDateTime(long val, out int yr, out int mnth, out int day, out int hr, out int min, out int sec, out int ms) { if (val < 0) goto Error; long date = val / 4; // trim indicator bits ms = (int)(date % 1000); date /= 1000; sec = (int)(date % 60); date /= 60; min = (int)(date % 60); date /= 60; hr = (int)(date % 24); date /= 24; day = (int)(date % 31) + 1; date /= 31; mnth = (int)(date % 12) + 1; date /= 12; yr = (int)(date - 9999); if (yr < -9999 || yr > 9999) goto Error; return; Error: throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } private static void BreakDownXsdDate(long val, out int yr, out int mnth, out int day, out bool negTimeZone, out int hr, out int min) { if (val < 0) goto Error; val = val / 4; // trim indicator bits int totalMin = (int)(val % (29 * 60)) - 60 * 14; long totalDays = val / (29 * 60); if (negTimeZone = (totalMin < 0)) totalMin = -totalMin; min = totalMin % 60; hr = totalMin / 60; day = (int)(totalDays % 31) + 1; totalDays /= 31; mnth = (int)(totalDays % 12) + 1; yr = (int)(totalDays / 12) - 9999; if (yr < -9999 || yr > 9999) goto Error; return; Error: throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } private static void BreakDownXsdTime(long val, out int hr, out int min, out int sec, out int ms) { if (val < 0) goto Error; val = val / 4; // trim indicator bits ms = (int)(val % 1000); val /= 1000; sec = (int)(val % 60); val /= 60; min = (int)(val % 60); hr = (int)(val / 60); if (0 > hr || hr > 23) goto Error; return; Error: throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } public static string XsdDateTimeToString(long val) { int yr; int mnth; int day; int hr; int min; int sec; int ms; BreakDownXsdDateTime(val, out yr, out mnth, out day, out hr, out min, out sec, out ms); StringBuilder sb = new StringBuilder(20); WriteDate(sb, yr, mnth, day); sb.Append('T'); WriteTime(sb, hr, min, sec, ms); sb.Append('Z'); return sb.ToString(); } public static DateTime XsdDateTimeToDateTime(long val) { int yr; int mnth; int day; int hr; int min; int sec; int ms; BreakDownXsdDateTime(val, out yr, out mnth, out day, out hr, out min, out sec, out ms); return new DateTime(yr, mnth, day, hr, min, sec, ms, DateTimeKind.Utc); } public static string XsdDateToString(long val) { int yr; int mnth; int day; int hr; int min; bool negTimeZ; BreakDownXsdDate(val, out yr, out mnth, out day, out negTimeZ, out hr, out min); StringBuilder sb = new StringBuilder(20); WriteDate(sb, yr, mnth, day); WriteTimeZone(sb, negTimeZ, hr, min); return sb.ToString(); } public static DateTime XsdDateToDateTime(long val) { int yr; int mnth; int day; int hr; int min; bool negTimeZ; BreakDownXsdDate(val, out yr, out mnth, out day, out negTimeZ, out hr, out min); DateTime d = new DateTime(yr, mnth, day, 0, 0, 0, DateTimeKind.Utc); // adjust for timezone int adj = (negTimeZ ? -1 : 1) * ((hr * 60) + min); return TimeZoneInfo.ConvertTime(d.AddMinutes(adj), TimeZoneInfo.Local); } public static string XsdTimeToString(long val) { int hr; int min; int sec; int ms; BreakDownXsdTime(val, out hr, out min, out sec, out ms); StringBuilder sb = new StringBuilder(16); WriteTime(sb, hr, min, sec, ms); sb.Append('Z'); return sb.ToString(); } public static DateTime XsdTimeToDateTime(long val) { int hr; int min; int sec; int ms; BreakDownXsdTime(val, out hr, out min, out sec, out ms); return new DateTime(1, 1, 1, hr, min, sec, ms, DateTimeKind.Utc); } public static string SqlDateTimeToString(int dateticks, uint timeticks) { DateTime dateTime = SqlDateTimeToDateTime(dateticks, timeticks); string format = (dateTime.Millisecond != 0) ? "yyyy/MM/dd\\THH:mm:ss.ffff" : "yyyy/MM/dd\\THH:mm:ss"; return dateTime.ToString(format, CultureInfo.InvariantCulture); } public static DateTime SqlDateTimeToDateTime(int dateticks, uint timeticks) { DateTime SQLBaseDate = new DateTime(1900, 1, 1); //long millisecond = (long)(((ulong)timeticks * 20 + (ulong)3) / (ulong)6); long millisecond = (long)(timeticks / s_SQLTicksPerMillisecond + 0.5); return SQLBaseDate.Add(new TimeSpan(dateticks * TimeSpan.TicksPerDay + millisecond * TimeSpan.TicksPerMillisecond)); } // Number of (100ns) ticks per time unit private const double s_SQLTicksPerMillisecond = 0.3; internal const int SQLTicksPerSecond = 300; internal const int SQLTicksPerMinute = SQLTicksPerSecond * 60; internal const int SQLTicksPerHour = SQLTicksPerMinute * 60; public static string SqlSmallDateTimeToString(short dateticks, ushort timeticks) { DateTime dateTime = SqlSmallDateTimeToDateTime(dateticks, timeticks); return dateTime.ToString("yyyy/MM/dd\\THH:mm:ss", CultureInfo.InvariantCulture); } public static DateTime SqlSmallDateTimeToDateTime(short dateticks, ushort timeticks) { return SqlDateTimeToDateTime((int)dateticks, (uint)(timeticks * SQLTicksPerMinute)); } // Conversions of the Katmai date & time types to DateTime public static DateTime XsdKatmaiDateToDateTime(byte[] data, int offset) { // Katmai SQL type "DATE" long dateTicks = GetKatmaiDateTicks(data, ref offset); DateTime dt = new DateTime(dateTicks); return dt; } public static DateTime XsdKatmaiDateTimeToDateTime(byte[] data, int offset) { // Katmai SQL type "DATETIME2" long timeTicks = GetKatmaiTimeTicks(data, ref offset); long dateTicks = GetKatmaiDateTicks(data, ref offset); DateTime dt = new DateTime(dateTicks + timeTicks); return dt; } public static DateTime XsdKatmaiTimeToDateTime(byte[] data, int offset) { // TIME without zone is stored as DATETIME2 return XsdKatmaiDateTimeToDateTime(data, offset); } public static DateTime XsdKatmaiDateOffsetToDateTime(byte[] data, int offset) { // read the timezoned value into DateTimeOffset and then convert to local time return XsdKatmaiDateOffsetToDateTimeOffset(data, offset).LocalDateTime; } public static DateTime XsdKatmaiDateTimeOffsetToDateTime(byte[] data, int offset) { // read the timezoned value into DateTimeOffset and then convert to local time return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset).LocalDateTime; } public static DateTime XsdKatmaiTimeOffsetToDateTime(byte[] data, int offset) { // read the timezoned value into DateTimeOffset and then convert to local time return XsdKatmaiTimeOffsetToDateTimeOffset(data, offset).LocalDateTime; } public static DateTimeOffset XsdKatmaiDateOffsetToDateTimeOffset(byte[] data, int offset) { // DATE with zone is stored as DATETIMEOFFSET return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset); } public static DateTimeOffset XsdKatmaiDateTimeOffsetToDateTimeOffset(byte[] data, int offset) { // Katmai SQL type "DATETIMEOFFSET" long timeTicks = GetKatmaiTimeTicks(data, ref offset); long dateTicks = GetKatmaiDateTicks(data, ref offset); long zoneTicks = GetKatmaiTimeZoneTicks(data, offset); // The DATETIMEOFFSET values are serialized in UTC, but DateTimeOffset takes adjusted time -> we need to add zoneTicks DateTimeOffset dto = new DateTimeOffset(dateTicks + timeTicks + zoneTicks, new TimeSpan(zoneTicks)); return dto; } public static DateTimeOffset XsdKatmaiTimeOffsetToDateTimeOffset(byte[] data, int offset) { // TIME with zone is stored as DATETIMEOFFSET return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset); } // Conversions of the Katmai date & time types to string public static string XsdKatmaiDateToString(byte[] data, int offset) { DateTime dt = XsdKatmaiDateToDateTime(data, offset); StringBuilder sb = new StringBuilder(10); WriteDate(sb, dt.Year, dt.Month, dt.Day); return sb.ToString(); } public static string XsdKatmaiDateTimeToString(byte[] data, int offset) { DateTime dt = XsdKatmaiDateTimeToDateTime(data, offset); StringBuilder sb = new StringBuilder(33); WriteDate(sb, dt.Year, dt.Month, dt.Day); sb.Append('T'); WriteTimeFullPrecision(sb, dt.Hour, dt.Minute, dt.Second, GetFractions(dt)); return sb.ToString(); } public static string XsdKatmaiTimeToString(byte[] data, int offset) { DateTime dt = XsdKatmaiTimeToDateTime(data, offset); StringBuilder sb = new StringBuilder(16); WriteTimeFullPrecision(sb, dt.Hour, dt.Minute, dt.Second, GetFractions(dt)); return sb.ToString(); } public static string XsdKatmaiDateOffsetToString(byte[] data, int offset) { DateTimeOffset dto = XsdKatmaiDateOffsetToDateTimeOffset(data, offset); StringBuilder sb = new StringBuilder(16); WriteDate(sb, dto.Year, dto.Month, dto.Day); WriteTimeZone(sb, dto.Offset); return sb.ToString(); } public static string XsdKatmaiDateTimeOffsetToString(byte[] data, int offset) { DateTimeOffset dto = XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset); StringBuilder sb = new StringBuilder(39); WriteDate(sb, dto.Year, dto.Month, dto.Day); sb.Append('T'); WriteTimeFullPrecision(sb, dto.Hour, dto.Minute, dto.Second, GetFractions(dto)); WriteTimeZone(sb, dto.Offset); return sb.ToString(); } public static string XsdKatmaiTimeOffsetToString(byte[] data, int offset) { DateTimeOffset dto = XsdKatmaiTimeOffsetToDateTimeOffset(data, offset); StringBuilder sb = new StringBuilder(22); WriteTimeFullPrecision(sb, dto.Hour, dto.Minute, dto.Second, GetFractions(dto)); WriteTimeZone(sb, dto.Offset); return sb.ToString(); } // Helper methods for the Katmai date & time types private static long GetKatmaiDateTicks(byte[] data, ref int pos) { int p = pos; pos = p + 3; return (data[p] | data[p + 1] << 8 | data[p + 2] << 16) * TimeSpan.TicksPerDay; } private static long GetKatmaiTimeTicks(byte[] data, ref int pos) { int p = pos; byte scale = data[p]; long timeTicks; p++; if (scale <= 2) { timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16); pos = p + 3; } else if (scale <= 4) { timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16); timeTicks |= ((long)data[p + 3] << 24); pos = p + 4; } else if (scale <= 7) { timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16); timeTicks |= ((long)data[p + 3] << 24) | ((long)data[p + 4] << 32); pos = p + 5; } else { throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null); } return timeTicks * KatmaiTimeScaleMultiplicator[scale]; } private static long GetKatmaiTimeZoneTicks(byte[] data, int pos) { return (short)(data[pos] | data[pos + 1] << 8) * TimeSpan.TicksPerMinute; } private static int GetFractions(DateTime dt) { return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks); } private static int GetFractions(DateTimeOffset dt) { return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks); } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfoOfT.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics; namespace System.Text.Json.Serialization.Metadata { /// <summary> /// Provides JSON serialization-related metadata about a type. /// </summary> /// <typeparam name="T">The generic definition of the type.</typeparam> [EditorBrowsable(EditorBrowsableState.Never)] public abstract class JsonTypeInfo<T> : JsonTypeInfo { private Action<Utf8JsonWriter, T>? _serialize; internal JsonTypeInfo(Type type, JsonSerializerOptions options) : base(type, options, dummy: false) { } internal JsonTypeInfo() { Debug.Assert(false, "This constructor should not be called."); } /// <summary> /// Serializes an instance of <typeparamref name="T"/> using /// <see cref="JsonSourceGenerationOptionsAttribute"/> values specified at design time. /// </summary> /// <remarks>The writer is not flushed after writing.</remarks> public Action<Utf8JsonWriter, T>? SerializeHandler { get { return _serialize; } private protected set { _serialize = value; HasSerialize = value != null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Diagnostics; namespace System.Text.Json.Serialization.Metadata { /// <summary> /// Provides JSON serialization-related metadata about a type. /// </summary> /// <typeparam name="T">The generic definition of the type.</typeparam> [EditorBrowsable(EditorBrowsableState.Never)] public abstract class JsonTypeInfo<T> : JsonTypeInfo { private Action<Utf8JsonWriter, T>? _serialize; internal JsonTypeInfo(Type type, JsonSerializerOptions options) : base(type, options, dummy: false) { } internal JsonTypeInfo() { Debug.Assert(false, "This constructor should not be called."); } /// <summary> /// Serializes an instance of <typeparamref name="T"/> using /// <see cref="JsonSourceGenerationOptionsAttribute"/> values specified at design time. /// </summary> /// <remarks>The writer is not flushed after writing.</remarks> public Action<Utf8JsonWriter, T>? SerializeHandler { get { return _serialize; } private protected set { _serialize = value; HasSerialize = value != null; } } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest190/Generated190.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated190 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct240`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<!T1,!T0> { .pack 0 .size 1 .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct240::Method7.1775<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<T1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,!T0>::Method7<[1]>() ldstr "MyStruct240::Method7.MI.1776<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod484() cil managed noinlining { ldstr "MyStruct240::ClassMethod484.1777()" ret } .method public hidebysig newslot instance string ClassMethod485<M0>() cil managed noinlining { ldstr "MyStruct240::ClassMethod485.1778<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod486<M0>() cil managed noinlining { ldstr "MyStruct240::ClassMethod486.1779<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated190 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.T.T<T0,T1,(valuetype MyStruct240`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.T.T<T0,T1,(valuetype MyStruct240`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.A.T<T1,(valuetype MyStruct240`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.A.T<T1,(valuetype MyStruct240`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.A.A<(valuetype MyStruct240`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.A.A<(valuetype MyStruct240`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.A.B<(valuetype MyStruct240`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.A.B<(valuetype MyStruct240`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.B.T<T1,(valuetype MyStruct240`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.B.T<T1,(valuetype MyStruct240`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.B.A<(valuetype MyStruct240`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.B.A<(valuetype MyStruct240`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.B.B<(valuetype MyStruct240`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.B.B<(valuetype MyStruct240`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_7 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_7 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.A<valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated190::MethodCallingTest() call void Generated190::ConstrainedCallsTest() call void Generated190::StructConstrainedInterfaceCallsTest() call void Generated190::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated190 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct240`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<!T1,!T0> { .pack 0 .size 1 .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct240::Method7.1775<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<T1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,!T0>::Method7<[1]>() ldstr "MyStruct240::Method7.MI.1776<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod484() cil managed noinlining { ldstr "MyStruct240::ClassMethod484.1777()" ret } .method public hidebysig newslot instance string ClassMethod485<M0>() cil managed noinlining { ldstr "MyStruct240::ClassMethod485.1778<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod486<M0>() cil managed noinlining { ldstr "MyStruct240::ClassMethod486.1779<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated190 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.T.T<T0,T1,(valuetype MyStruct240`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.T.T<T0,T1,(valuetype MyStruct240`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.A.T<T1,(valuetype MyStruct240`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.A.T<T1,(valuetype MyStruct240`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.A.A<(valuetype MyStruct240`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.A.A<(valuetype MyStruct240`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.A.B<(valuetype MyStruct240`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.A.B<(valuetype MyStruct240`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.B.T<T1,(valuetype MyStruct240`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.B.T<T1,(valuetype MyStruct240`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.B.A<(valuetype MyStruct240`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.B.A<(valuetype MyStruct240`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct240.B.B<(valuetype MyStruct240`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct240.B.B<(valuetype MyStruct240`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct240`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod484() ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod485<object>() ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod486<object>() ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type MyStruct240" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_7 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_7 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.B.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .try { ldloc V_8 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.IBase2.A.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.A<valuetype MyStruct240`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.A.B<valuetype MyStruct240`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.T<class BaseClass0,valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.A<valuetype MyStruct240`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.T<class BaseClass1,valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct240::Method7.MI.1776<System.Object>()#" call void Generated190::M.MyStruct240.B.B<valuetype MyStruct240`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct240`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct240`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct240`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct240`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct240`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.1775<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod484() calli default string(object) ldstr "MyStruct240::ClassMethod484.1777()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod485<object>() calli default string(object) ldstr "MyStruct240::ClassMethod485.1778<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ClassMethod486<object>() calli default string(object) ldstr "MyStruct240::ClassMethod486.1779<System.Object>()" ldstr "valuetype MyStruct240`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct240`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct240`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct240::Method7.MI.1776<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct240`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated190::MethodCallingTest() call void Generated190::ConstrainedCallsTest() call void Generated190::StructConstrainedInterfaceCallsTest() call void Generated190::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Methodical/tailcall/compat_r4_r8_il_d.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="compat_r4_r8.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="compat_r4_r8.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/mono/mono/tests/sgen-toggleref.cs
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using MonoTests.Helpers; public class Toggleref { public int __test; public string id; public List<object> link = new List<object> (); public const int DROP = 0; public const int STRONG = 1; public const int WEAK = 2; ~Toggleref () { } } public struct Helper { private class ObjectWrapper { public object Object; } private class IntPtrWrapper { public IntPtr Value; } [StructLayout(LayoutKind.Explicit)] private struct ObjectReinterpreter { [FieldOffset(0)] public ObjectWrapper AsObject; [FieldOffset(0)] public IntPtrWrapper AsIntPtr; } private static object mutualObject; private static ObjectReinterpreter reinterpreter; static Helper() { Helper.mutualObject = new object(); Helper.reinterpreter = new ObjectReinterpreter(); Helper.reinterpreter.AsObject = new ObjectWrapper(); } public static IntPtr ObjToPtr (object obj) { lock (Helper.mutualObject) { Helper.reinterpreter.AsObject.Object = obj; IntPtr address = Helper.reinterpreter.AsIntPtr.Value; Helper.reinterpreter.AsObject.Object = null; return address; } } } class Driver { static WeakReference<Toggleref> root, child; [DllImport ("__Internal", EntryPoint="mono_gc_toggleref_add")] static extern void mono_gc_toggleref_add (IntPtr ptr, bool strong_ref); static void Register (object obj) { mono_gc_toggleref_add (Helper.ObjToPtr (obj), true); } static Toggleref a, b; static void SetupLinks () { var r = new Toggleref () { id = "root" }; var c = new Toggleref () { id = "child" }; r.link.Add (c); r.__test = Toggleref.STRONG; c.__test = Toggleref.WEAK; Register (r); Register (c); root = new WeakReference<Toggleref> (r, false); child = new WeakReference<Toggleref> (c, false); } static int test_0_root_keeps_child () { Console.WriteLine ("test_0_root_keeps_child"); FinalizerHelpers.PerformNoPinAction (SetupLinks); GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b == null) return 1; Console.WriteLine ("a test {0}", a.__test); Console.WriteLine ("b test {0}", b.__test); //now we break the link and switch b to strong a.link.Clear (); b.__test = Toggleref.STRONG; a = b = null; GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b == null) return 2; Console.WriteLine ("a test {0}", a.__test); Console.WriteLine ("b test {0}", b.__test); return 0; } static void SetupLinks2 () { var r = new Toggleref () { id = "root" }; var c = new Toggleref () { id = "child" }; r.__test = Toggleref.STRONG; c.__test = Toggleref.WEAK; Register (r); Register (c); root = new WeakReference<Toggleref> (r, false); child = new WeakReference<Toggleref> (c, false); } static int test_0_child_goes_away () { Console.WriteLine ("test_0_child_goes_away"); FinalizerHelpers.PerformNoPinAction (SetupLinks2); GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b != null) return 1; Console.WriteLine ("a test {0}", a.__test); return 0; } static ConditionalWeakTable<Toggleref, object> cwt = new ConditionalWeakTable<Toggleref, object> (); static WeakReference<object> root_value, child_value; static object a_val, b_val; static void SetupLinks3 () { var r = new Toggleref () { id = "root" }; var c = new Toggleref () { id = "child" }; r.__test = Toggleref.STRONG; c.__test = Toggleref.WEAK; Register (r); Register (c); root = new WeakReference<Toggleref> (r, false); child = new WeakReference<Toggleref> (c, false); var root_val = new object (); var child_val = new object (); cwt.Add (r, root_val); cwt.Add (c, child_val); root_value = new WeakReference<object> (root_val, false); child_value = new WeakReference<object> (child_val, false); } static int test_0_CWT_keep_child_alive () { Console.WriteLine ("test_0_CWT_keep_child_alive"); FinalizerHelpers.PerformNoPinAction (SetupLinks3); GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b != null) return 1; Console.WriteLine ("a test {0}", a.__test); Console.WriteLine ("try get a_val {0}", root_value.TryGetTarget (out a_val)); Console.WriteLine ("try get v_val {0}", child_value.TryGetTarget (out b_val)); //the strong toggleref must keep the CWT value to remains alive if (a_val == null) return 2; //the weak toggleref should allow the CWT value to go away if (b_val != null) return 3; object res_value = null; bool res = cwt.TryGetValue (a, out res_value); Console.WriteLine ("CWT result {0} -> {1}", res, res_value == a_val); //the strong val is not on the CWT if (!res) return 4; //for some reason the value is not the right one if (res_value != a_val) return 5; return 0; } static int Main (string[] args) { return TestDriver.RunTests (typeof (Driver), args); } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using MonoTests.Helpers; public class Toggleref { public int __test; public string id; public List<object> link = new List<object> (); public const int DROP = 0; public const int STRONG = 1; public const int WEAK = 2; ~Toggleref () { } } public struct Helper { private class ObjectWrapper { public object Object; } private class IntPtrWrapper { public IntPtr Value; } [StructLayout(LayoutKind.Explicit)] private struct ObjectReinterpreter { [FieldOffset(0)] public ObjectWrapper AsObject; [FieldOffset(0)] public IntPtrWrapper AsIntPtr; } private static object mutualObject; private static ObjectReinterpreter reinterpreter; static Helper() { Helper.mutualObject = new object(); Helper.reinterpreter = new ObjectReinterpreter(); Helper.reinterpreter.AsObject = new ObjectWrapper(); } public static IntPtr ObjToPtr (object obj) { lock (Helper.mutualObject) { Helper.reinterpreter.AsObject.Object = obj; IntPtr address = Helper.reinterpreter.AsIntPtr.Value; Helper.reinterpreter.AsObject.Object = null; return address; } } } class Driver { static WeakReference<Toggleref> root, child; [DllImport ("__Internal", EntryPoint="mono_gc_toggleref_add")] static extern void mono_gc_toggleref_add (IntPtr ptr, bool strong_ref); static void Register (object obj) { mono_gc_toggleref_add (Helper.ObjToPtr (obj), true); } static Toggleref a, b; static void SetupLinks () { var r = new Toggleref () { id = "root" }; var c = new Toggleref () { id = "child" }; r.link.Add (c); r.__test = Toggleref.STRONG; c.__test = Toggleref.WEAK; Register (r); Register (c); root = new WeakReference<Toggleref> (r, false); child = new WeakReference<Toggleref> (c, false); } static int test_0_root_keeps_child () { Console.WriteLine ("test_0_root_keeps_child"); FinalizerHelpers.PerformNoPinAction (SetupLinks); GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b == null) return 1; Console.WriteLine ("a test {0}", a.__test); Console.WriteLine ("b test {0}", b.__test); //now we break the link and switch b to strong a.link.Clear (); b.__test = Toggleref.STRONG; a = b = null; GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b == null) return 2; Console.WriteLine ("a test {0}", a.__test); Console.WriteLine ("b test {0}", b.__test); return 0; } static void SetupLinks2 () { var r = new Toggleref () { id = "root" }; var c = new Toggleref () { id = "child" }; r.__test = Toggleref.STRONG; c.__test = Toggleref.WEAK; Register (r); Register (c); root = new WeakReference<Toggleref> (r, false); child = new WeakReference<Toggleref> (c, false); } static int test_0_child_goes_away () { Console.WriteLine ("test_0_child_goes_away"); FinalizerHelpers.PerformNoPinAction (SetupLinks2); GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b != null) return 1; Console.WriteLine ("a test {0}", a.__test); return 0; } static ConditionalWeakTable<Toggleref, object> cwt = new ConditionalWeakTable<Toggleref, object> (); static WeakReference<object> root_value, child_value; static object a_val, b_val; static void SetupLinks3 () { var r = new Toggleref () { id = "root" }; var c = new Toggleref () { id = "child" }; r.__test = Toggleref.STRONG; c.__test = Toggleref.WEAK; Register (r); Register (c); root = new WeakReference<Toggleref> (r, false); child = new WeakReference<Toggleref> (c, false); var root_val = new object (); var child_val = new object (); cwt.Add (r, root_val); cwt.Add (c, child_val); root_value = new WeakReference<object> (root_val, false); child_value = new WeakReference<object> (child_val, false); } static int test_0_CWT_keep_child_alive () { Console.WriteLine ("test_0_CWT_keep_child_alive"); FinalizerHelpers.PerformNoPinAction (SetupLinks3); GC.Collect (); GC.WaitForPendingFinalizers (); Console.WriteLine ("try get A {0}", root.TryGetTarget (out a)); Console.WriteLine ("try get B {0}", child.TryGetTarget (out b)); Console.WriteLine ("a is null {0}", a == null); Console.WriteLine ("b is null {0}", b == null); if (a == null || b != null) return 1; Console.WriteLine ("a test {0}", a.__test); Console.WriteLine ("try get a_val {0}", root_value.TryGetTarget (out a_val)); Console.WriteLine ("try get v_val {0}", child_value.TryGetTarget (out b_val)); //the strong toggleref must keep the CWT value to remains alive if (a_val == null) return 2; //the weak toggleref should allow the CWT value to go away if (b_val != null) return 3; object res_value = null; bool res = cwt.TryGetValue (a, out res_value); Console.WriteLine ("CWT result {0} -> {1}", res, res_value == a_val); //the strong val is not on the CWT if (!res) return 4; //for some reason the value is not the right one if (res_value != a_val) return 5; return 0; } static int Main (string[] args) { return TestDriver.RunTests (typeof (Driver), args); } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Methodical/explicit/coverage/body_safe_val.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; internal class TestApp { private static int test_0_0(int num, AA init, AA zero) { return init.q.val; } private static int test_0_1(int num, AA init, AA zero) { zero.q.val = num; return zero.q.val; } private static int test_0_2(int num, AA init, AA zero) { if (init.q.val != zero.q.val) return 100; else return zero.q.val; } private static int test_0_3(int num, AA init, AA zero) { return init.q.val < num + 1 ? 100 : -1; } private static int test_0_4(int num, AA init, AA zero) { return (init.q.val > zero.q.val ? 1 : 0) + 99; } private static int test_0_5(int num, AA init, AA zero) { return (init.q.val ^ zero.q.val) | num; } private static int test_0_6(int num, AA init, AA zero) { zero.q.val |= init.q.val; return zero.q.val & num; } private static int test_0_7(int num, AA init, AA zero) { return init.q.val >> zero.q.val; } private static int test_0_8(int num, AA init, AA zero) { return AA.a_init[init.q.val].q.val; } private static int test_0_9(int num, AA init, AA zero) { return AA.aa_init[num - 100, (init.q.val | 1) - 2, 1 + zero.q.val].q.val; } private static int test_0_10(int num, AA init, AA zero) { object bb = init.q.val; return (int)bb; } private static int test_0_11(int num, AA init, AA zero) { double dbl = init.q.val; return (int)dbl; } private static int test_0_12(int num, AA init, AA zero) { return AA.call_target(init.q).val; } private static int test_0_13(int num, AA init, AA zero) { return AA.call_target_ref(ref init.q).val; } private static int test_0_14(int num, AA init, AA zero) { return init.q.ret_code(); } private static int test_1_0(int num, ref AA r_init, ref AA r_zero) { return r_init.q.val; } private static int test_1_1(int num, ref AA r_init, ref AA r_zero) { r_zero.q.val = num; return r_zero.q.val; } private static int test_1_2(int num, ref AA r_init, ref AA r_zero) { if (r_init.q.val != r_zero.q.val) return 100; else return r_zero.q.val; } private static int test_1_3(int num, ref AA r_init, ref AA r_zero) { return r_init.q.val < num + 1 ? 100 : -1; } private static int test_1_4(int num, ref AA r_init, ref AA r_zero) { return (r_init.q.val > r_zero.q.val ? 1 : 0) + 99; } private static int test_1_5(int num, ref AA r_init, ref AA r_zero) { return (r_init.q.val ^ r_zero.q.val) | num; } private static int test_1_6(int num, ref AA r_init, ref AA r_zero) { r_zero.q.val |= r_init.q.val; return r_zero.q.val & num; } private static int test_1_7(int num, ref AA r_init, ref AA r_zero) { return r_init.q.val >> r_zero.q.val; } private static int test_1_8(int num, ref AA r_init, ref AA r_zero) { return AA.a_init[r_init.q.val].q.val; } private static int test_1_9(int num, ref AA r_init, ref AA r_zero) { return AA.aa_init[num - 100, (r_init.q.val | 1) - 2, 1 + r_zero.q.val].q.val; } private static int test_1_10(int num, ref AA r_init, ref AA r_zero) { object bb = r_init.q.val; return (int)bb; } private static int test_1_11(int num, ref AA r_init, ref AA r_zero) { double dbl = r_init.q.val; return (int)dbl; } private static int test_1_12(int num, ref AA r_init, ref AA r_zero) { return AA.call_target(r_init.q).val; } private static int test_1_13(int num, ref AA r_init, ref AA r_zero) { return AA.call_target_ref(ref r_init.q).val; } private static int test_1_14(int num, ref AA r_init, ref AA r_zero) { return r_init.q.ret_code(); } private static int test_2_0(int num) { return AA.a_init[num].q.val; } private static int test_2_1(int num) { AA.a_zero[num].q.val = num; return AA.a_zero[num].q.val; } private static int test_2_2(int num) { if (AA.a_init[num].q.val != AA.a_zero[num].q.val) return 100; else return AA.a_zero[num].q.val; } private static int test_2_3(int num) { return AA.a_init[num].q.val < num + 1 ? 100 : -1; } private static int test_2_4(int num) { return (AA.a_init[num].q.val > AA.a_zero[num].q.val ? 1 : 0) + 99; } private static int test_2_5(int num) { return (AA.a_init[num].q.val ^ AA.a_zero[num].q.val) | num; } private static int test_2_6(int num) { AA.a_zero[num].q.val |= AA.a_init[num].q.val; return AA.a_zero[num].q.val & num; } private static int test_2_7(int num) { return AA.a_init[num].q.val >> AA.a_zero[num].q.val; } private static int test_2_8(int num) { return AA.a_init[AA.a_init[num].q.val].q.val; } private static int test_2_9(int num) { return AA.aa_init[num - 100, (AA.a_init[num].q.val | 1) - 2, 1 + AA.a_zero[num].q.val].q.val; } private static int test_2_10(int num) { object bb = AA.a_init[num].q.val; return (int)bb; } private static int test_2_11(int num) { double dbl = AA.a_init[num].q.val; return (int)dbl; } private static int test_2_12(int num) { return AA.call_target(AA.a_init[num].q).val; } private static int test_2_13(int num) { return AA.call_target_ref(ref AA.a_init[num].q).val; } private static int test_2_14(int num) { return AA.a_init[num].q.ret_code(); } private static int test_3_0(int num) { return AA.aa_init[0, num - 1, num / 100].q.val; } private static int test_3_1(int num) { AA.aa_zero[0, num - 1, num / 100].q.val = num; return AA.aa_zero[0, num - 1, num / 100].q.val; } private static int test_3_2(int num) { if (AA.aa_init[0, num - 1, num / 100].q.val != AA.aa_zero[0, num - 1, num / 100].q.val) return 100; else return AA.aa_zero[0, num - 1, num / 100].q.val; } private static int test_3_3(int num) { return AA.aa_init[0, num - 1, num / 100].q.val < num + 1 ? 100 : -1; } private static int test_3_4(int num) { return (AA.aa_init[0, num - 1, num / 100].q.val > AA.aa_zero[0, num - 1, num / 100].q.val ? 1 : 0) + 99; } private static int test_3_5(int num) { return (AA.aa_init[0, num - 1, num / 100].q.val ^ AA.aa_zero[0, num - 1, num / 100].q.val) | num; } private static int test_3_6(int num) { AA.aa_zero[0, num - 1, num / 100].q.val |= AA.aa_init[0, num - 1, num / 100].q.val; return AA.aa_zero[0, num - 1, num / 100].q.val & num; } private static int test_3_7(int num) { return AA.aa_init[0, num - 1, num / 100].q.val >> AA.aa_zero[0, num - 1, num / 100].q.val; } private static int test_3_8(int num) { return AA.a_init[AA.aa_init[0, num - 1, num / 100].q.val].q.val; } private static int test_3_9(int num) { return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q.val | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q.val].q.val; } private static int test_3_10(int num) { object bb = AA.aa_init[0, num - 1, num / 100].q.val; return (int)bb; } private static int test_3_11(int num) { double dbl = AA.aa_init[0, num - 1, num / 100].q.val; return (int)dbl; } private static int test_3_12(int num) { return AA.call_target(AA.aa_init[0, num - 1, num / 100].q).val; } private static int test_3_13(int num) { return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q).val; } private static int test_3_14(int num) { return AA.aa_init[0, num - 1, num / 100].q.ret_code(); } private static int test_4_0(int num) { return BB.f_init.q.val; } private static int test_4_1(int num) { BB.f_zero.q.val = num; return BB.f_zero.q.val; } private static int test_4_2(int num) { if (BB.f_init.q.val != BB.f_zero.q.val) return 100; else return BB.f_zero.q.val; } private static int test_4_3(int num) { return BB.f_init.q.val < num + 1 ? 100 : -1; } private static int test_4_4(int num) { return (BB.f_init.q.val > BB.f_zero.q.val ? 1 : 0) + 99; } private static int test_4_5(int num) { return (BB.f_init.q.val ^ BB.f_zero.q.val) | num; } private static int test_4_6(int num) { BB.f_zero.q.val |= BB.f_init.q.val; return BB.f_zero.q.val & num; } private static int test_4_7(int num) { return BB.f_init.q.val >> BB.f_zero.q.val; } private static int test_4_8(int num) { return AA.a_init[BB.f_init.q.val].q.val; } private static int test_4_9(int num) { return AA.aa_init[num - 100, (BB.f_init.q.val | 1) - 2, 1 + BB.f_zero.q.val].q.val; } private static int test_4_10(int num) { object bb = BB.f_init.q.val; return (int)bb; } private static int test_4_11(int num) { double dbl = BB.f_init.q.val; return (int)dbl; } private static int test_4_12(int num) { return AA.call_target(BB.f_init.q).val; } private static int test_4_13(int num) { return AA.call_target_ref(ref BB.f_init.q).val; } private static int test_4_14(int num) { return BB.f_init.q.ret_code(); } private static int test_5_0(int num) { return ((AA)AA.b_init).q.val; } private static int test_6_0(int num, TypedReference tr_init) { return __refvalue(tr_init, AA).q.val; } internal static unsafe int RunAllTests() { AA.reset(); if (test_0_0(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_0() failed."); return 101; } AA.verify_all(); AA.reset(); if (test_0_1(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_1() failed."); return 102; } AA.verify_all(); AA.reset(); if (test_0_2(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_2() failed."); return 103; } AA.verify_all(); AA.reset(); if (test_0_3(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_3() failed."); return 104; } AA.verify_all(); AA.reset(); if (test_0_4(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_4() failed."); return 105; } AA.verify_all(); AA.reset(); if (test_0_5(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_5() failed."); return 106; } AA.verify_all(); AA.reset(); if (test_0_6(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_6() failed."); return 107; } AA.verify_all(); AA.reset(); if (test_0_7(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_7() failed."); return 108; } AA.verify_all(); AA.reset(); if (test_0_8(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_8() failed."); return 109; } AA.verify_all(); AA.reset(); if (test_0_9(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_9() failed."); return 110; } AA.verify_all(); AA.reset(); if (test_0_10(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_10() failed."); return 111; } AA.verify_all(); AA.reset(); if (test_0_11(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_11() failed."); return 112; } AA.verify_all(); AA.reset(); if (test_0_12(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_12() failed."); return 113; } AA.verify_all(); AA.reset(); if (test_0_13(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_13() failed."); return 114; } AA.verify_all(); AA.reset(); if (test_0_14(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_14() failed."); return 115; } AA.verify_all(); AA.reset(); if (test_1_0(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_0() failed."); return 116; } AA.verify_all(); AA.reset(); if (test_1_1(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_1() failed."); return 117; } AA.verify_all(); AA.reset(); if (test_1_2(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_2() failed."); return 118; } AA.verify_all(); AA.reset(); if (test_1_3(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_3() failed."); return 119; } AA.verify_all(); AA.reset(); if (test_1_4(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_4() failed."); return 120; } AA.verify_all(); AA.reset(); if (test_1_5(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_5() failed."); return 121; } AA.verify_all(); AA.reset(); if (test_1_6(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_6() failed."); return 122; } AA.verify_all(); AA.reset(); if (test_1_7(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_7() failed."); return 123; } AA.verify_all(); AA.reset(); if (test_1_8(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_8() failed."); return 124; } AA.verify_all(); AA.reset(); if (test_1_9(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_9() failed."); return 125; } AA.verify_all(); AA.reset(); if (test_1_10(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_10() failed."); return 126; } AA.verify_all(); AA.reset(); if (test_1_11(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_11() failed."); return 127; } AA.verify_all(); AA.reset(); if (test_1_12(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_12() failed."); return 128; } AA.verify_all(); AA.reset(); if (test_1_13(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_13() failed."); return 129; } AA.verify_all(); AA.reset(); if (test_1_14(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_14() failed."); return 130; } AA.verify_all(); AA.reset(); if (test_2_0(100) != 100) { Console.WriteLine("test_2_0() failed."); return 131; } AA.verify_all(); AA.reset(); if (test_2_1(100) != 100) { Console.WriteLine("test_2_1() failed."); return 132; } AA.verify_all(); AA.reset(); if (test_2_2(100) != 100) { Console.WriteLine("test_2_2() failed."); return 133; } AA.verify_all(); AA.reset(); if (test_2_3(100) != 100) { Console.WriteLine("test_2_3() failed."); return 134; } AA.verify_all(); AA.reset(); if (test_2_4(100) != 100) { Console.WriteLine("test_2_4() failed."); return 135; } AA.verify_all(); AA.reset(); if (test_2_5(100) != 100) { Console.WriteLine("test_2_5() failed."); return 136; } AA.verify_all(); AA.reset(); if (test_2_6(100) != 100) { Console.WriteLine("test_2_6() failed."); return 137; } AA.verify_all(); AA.reset(); if (test_2_7(100) != 100) { Console.WriteLine("test_2_7() failed."); return 138; } AA.verify_all(); AA.reset(); if (test_2_8(100) != 100) { Console.WriteLine("test_2_8() failed."); return 139; } AA.verify_all(); AA.reset(); if (test_2_9(100) != 100) { Console.WriteLine("test_2_9() failed."); return 140; } AA.verify_all(); AA.reset(); if (test_2_10(100) != 100) { Console.WriteLine("test_2_10() failed."); return 141; } AA.verify_all(); AA.reset(); if (test_2_11(100) != 100) { Console.WriteLine("test_2_11() failed."); return 142; } AA.verify_all(); AA.reset(); if (test_2_12(100) != 100) { Console.WriteLine("test_2_12() failed."); return 143; } AA.verify_all(); AA.reset(); if (test_2_13(100) != 100) { Console.WriteLine("test_2_13() failed."); return 144; } AA.verify_all(); AA.reset(); if (test_2_14(100) != 100) { Console.WriteLine("test_2_14() failed."); return 145; } AA.verify_all(); AA.reset(); if (test_3_0(100) != 100) { Console.WriteLine("test_3_0() failed."); return 146; } AA.verify_all(); AA.reset(); if (test_3_1(100) != 100) { Console.WriteLine("test_3_1() failed."); return 147; } AA.verify_all(); AA.reset(); if (test_3_2(100) != 100) { Console.WriteLine("test_3_2() failed."); return 148; } AA.verify_all(); AA.reset(); if (test_3_3(100) != 100) { Console.WriteLine("test_3_3() failed."); return 149; } AA.verify_all(); AA.reset(); if (test_3_4(100) != 100) { Console.WriteLine("test_3_4() failed."); return 150; } AA.verify_all(); AA.reset(); if (test_3_5(100) != 100) { Console.WriteLine("test_3_5() failed."); return 151; } AA.verify_all(); AA.reset(); if (test_3_6(100) != 100) { Console.WriteLine("test_3_6() failed."); return 152; } AA.verify_all(); AA.reset(); if (test_3_7(100) != 100) { Console.WriteLine("test_3_7() failed."); return 153; } AA.verify_all(); AA.reset(); if (test_3_8(100) != 100) { Console.WriteLine("test_3_8() failed."); return 154; } AA.verify_all(); AA.reset(); if (test_3_9(100) != 100) { Console.WriteLine("test_3_9() failed."); return 155; } AA.verify_all(); AA.reset(); if (test_3_10(100) != 100) { Console.WriteLine("test_3_10() failed."); return 156; } AA.verify_all(); AA.reset(); if (test_3_11(100) != 100) { Console.WriteLine("test_3_11() failed."); return 157; } AA.verify_all(); AA.reset(); if (test_3_12(100) != 100) { Console.WriteLine("test_3_12() failed."); return 158; } AA.verify_all(); AA.reset(); if (test_3_13(100) != 100) { Console.WriteLine("test_3_13() failed."); return 159; } AA.verify_all(); AA.reset(); if (test_3_14(100) != 100) { Console.WriteLine("test_3_14() failed."); return 160; } AA.verify_all(); AA.reset(); if (test_4_0(100) != 100) { Console.WriteLine("test_4_0() failed."); return 161; } AA.verify_all(); AA.reset(); if (test_4_1(100) != 100) { Console.WriteLine("test_4_1() failed."); return 162; } AA.verify_all(); AA.reset(); if (test_4_2(100) != 100) { Console.WriteLine("test_4_2() failed."); return 163; } AA.verify_all(); AA.reset(); if (test_4_3(100) != 100) { Console.WriteLine("test_4_3() failed."); return 164; } AA.verify_all(); AA.reset(); if (test_4_4(100) != 100) { Console.WriteLine("test_4_4() failed."); return 165; } AA.verify_all(); AA.reset(); if (test_4_5(100) != 100) { Console.WriteLine("test_4_5() failed."); return 166; } AA.verify_all(); AA.reset(); if (test_4_6(100) != 100) { Console.WriteLine("test_4_6() failed."); return 167; } AA.verify_all(); AA.reset(); if (test_4_7(100) != 100) { Console.WriteLine("test_4_7() failed."); return 168; } AA.verify_all(); AA.reset(); if (test_4_8(100) != 100) { Console.WriteLine("test_4_8() failed."); return 169; } AA.verify_all(); AA.reset(); if (test_4_9(100) != 100) { Console.WriteLine("test_4_9() failed."); return 170; } AA.verify_all(); AA.reset(); if (test_4_10(100) != 100) { Console.WriteLine("test_4_10() failed."); return 171; } AA.verify_all(); AA.reset(); if (test_4_11(100) != 100) { Console.WriteLine("test_4_11() failed."); return 172; } AA.verify_all(); AA.reset(); if (test_4_12(100) != 100) { Console.WriteLine("test_4_12() failed."); return 173; } AA.verify_all(); AA.reset(); if (test_4_13(100) != 100) { Console.WriteLine("test_4_13() failed."); return 174; } AA.verify_all(); AA.reset(); if (test_4_14(100) != 100) { Console.WriteLine("test_4_14() failed."); return 175; } AA.verify_all(); AA.reset(); if (test_5_0(100) != 100) { Console.WriteLine("test_5_0() failed."); return 176; } AA.verify_all(); AA.reset(); if (test_6_0(100, __makeref(AA._init)) != 100) { Console.WriteLine("test_6_0() failed."); return 177; } AA.verify_all(); Console.WriteLine("All tests passed."); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; internal class TestApp { private static int test_0_0(int num, AA init, AA zero) { return init.q.val; } private static int test_0_1(int num, AA init, AA zero) { zero.q.val = num; return zero.q.val; } private static int test_0_2(int num, AA init, AA zero) { if (init.q.val != zero.q.val) return 100; else return zero.q.val; } private static int test_0_3(int num, AA init, AA zero) { return init.q.val < num + 1 ? 100 : -1; } private static int test_0_4(int num, AA init, AA zero) { return (init.q.val > zero.q.val ? 1 : 0) + 99; } private static int test_0_5(int num, AA init, AA zero) { return (init.q.val ^ zero.q.val) | num; } private static int test_0_6(int num, AA init, AA zero) { zero.q.val |= init.q.val; return zero.q.val & num; } private static int test_0_7(int num, AA init, AA zero) { return init.q.val >> zero.q.val; } private static int test_0_8(int num, AA init, AA zero) { return AA.a_init[init.q.val].q.val; } private static int test_0_9(int num, AA init, AA zero) { return AA.aa_init[num - 100, (init.q.val | 1) - 2, 1 + zero.q.val].q.val; } private static int test_0_10(int num, AA init, AA zero) { object bb = init.q.val; return (int)bb; } private static int test_0_11(int num, AA init, AA zero) { double dbl = init.q.val; return (int)dbl; } private static int test_0_12(int num, AA init, AA zero) { return AA.call_target(init.q).val; } private static int test_0_13(int num, AA init, AA zero) { return AA.call_target_ref(ref init.q).val; } private static int test_0_14(int num, AA init, AA zero) { return init.q.ret_code(); } private static int test_1_0(int num, ref AA r_init, ref AA r_zero) { return r_init.q.val; } private static int test_1_1(int num, ref AA r_init, ref AA r_zero) { r_zero.q.val = num; return r_zero.q.val; } private static int test_1_2(int num, ref AA r_init, ref AA r_zero) { if (r_init.q.val != r_zero.q.val) return 100; else return r_zero.q.val; } private static int test_1_3(int num, ref AA r_init, ref AA r_zero) { return r_init.q.val < num + 1 ? 100 : -1; } private static int test_1_4(int num, ref AA r_init, ref AA r_zero) { return (r_init.q.val > r_zero.q.val ? 1 : 0) + 99; } private static int test_1_5(int num, ref AA r_init, ref AA r_zero) { return (r_init.q.val ^ r_zero.q.val) | num; } private static int test_1_6(int num, ref AA r_init, ref AA r_zero) { r_zero.q.val |= r_init.q.val; return r_zero.q.val & num; } private static int test_1_7(int num, ref AA r_init, ref AA r_zero) { return r_init.q.val >> r_zero.q.val; } private static int test_1_8(int num, ref AA r_init, ref AA r_zero) { return AA.a_init[r_init.q.val].q.val; } private static int test_1_9(int num, ref AA r_init, ref AA r_zero) { return AA.aa_init[num - 100, (r_init.q.val | 1) - 2, 1 + r_zero.q.val].q.val; } private static int test_1_10(int num, ref AA r_init, ref AA r_zero) { object bb = r_init.q.val; return (int)bb; } private static int test_1_11(int num, ref AA r_init, ref AA r_zero) { double dbl = r_init.q.val; return (int)dbl; } private static int test_1_12(int num, ref AA r_init, ref AA r_zero) { return AA.call_target(r_init.q).val; } private static int test_1_13(int num, ref AA r_init, ref AA r_zero) { return AA.call_target_ref(ref r_init.q).val; } private static int test_1_14(int num, ref AA r_init, ref AA r_zero) { return r_init.q.ret_code(); } private static int test_2_0(int num) { return AA.a_init[num].q.val; } private static int test_2_1(int num) { AA.a_zero[num].q.val = num; return AA.a_zero[num].q.val; } private static int test_2_2(int num) { if (AA.a_init[num].q.val != AA.a_zero[num].q.val) return 100; else return AA.a_zero[num].q.val; } private static int test_2_3(int num) { return AA.a_init[num].q.val < num + 1 ? 100 : -1; } private static int test_2_4(int num) { return (AA.a_init[num].q.val > AA.a_zero[num].q.val ? 1 : 0) + 99; } private static int test_2_5(int num) { return (AA.a_init[num].q.val ^ AA.a_zero[num].q.val) | num; } private static int test_2_6(int num) { AA.a_zero[num].q.val |= AA.a_init[num].q.val; return AA.a_zero[num].q.val & num; } private static int test_2_7(int num) { return AA.a_init[num].q.val >> AA.a_zero[num].q.val; } private static int test_2_8(int num) { return AA.a_init[AA.a_init[num].q.val].q.val; } private static int test_2_9(int num) { return AA.aa_init[num - 100, (AA.a_init[num].q.val | 1) - 2, 1 + AA.a_zero[num].q.val].q.val; } private static int test_2_10(int num) { object bb = AA.a_init[num].q.val; return (int)bb; } private static int test_2_11(int num) { double dbl = AA.a_init[num].q.val; return (int)dbl; } private static int test_2_12(int num) { return AA.call_target(AA.a_init[num].q).val; } private static int test_2_13(int num) { return AA.call_target_ref(ref AA.a_init[num].q).val; } private static int test_2_14(int num) { return AA.a_init[num].q.ret_code(); } private static int test_3_0(int num) { return AA.aa_init[0, num - 1, num / 100].q.val; } private static int test_3_1(int num) { AA.aa_zero[0, num - 1, num / 100].q.val = num; return AA.aa_zero[0, num - 1, num / 100].q.val; } private static int test_3_2(int num) { if (AA.aa_init[0, num - 1, num / 100].q.val != AA.aa_zero[0, num - 1, num / 100].q.val) return 100; else return AA.aa_zero[0, num - 1, num / 100].q.val; } private static int test_3_3(int num) { return AA.aa_init[0, num - 1, num / 100].q.val < num + 1 ? 100 : -1; } private static int test_3_4(int num) { return (AA.aa_init[0, num - 1, num / 100].q.val > AA.aa_zero[0, num - 1, num / 100].q.val ? 1 : 0) + 99; } private static int test_3_5(int num) { return (AA.aa_init[0, num - 1, num / 100].q.val ^ AA.aa_zero[0, num - 1, num / 100].q.val) | num; } private static int test_3_6(int num) { AA.aa_zero[0, num - 1, num / 100].q.val |= AA.aa_init[0, num - 1, num / 100].q.val; return AA.aa_zero[0, num - 1, num / 100].q.val & num; } private static int test_3_7(int num) { return AA.aa_init[0, num - 1, num / 100].q.val >> AA.aa_zero[0, num - 1, num / 100].q.val; } private static int test_3_8(int num) { return AA.a_init[AA.aa_init[0, num - 1, num / 100].q.val].q.val; } private static int test_3_9(int num) { return AA.aa_init[num - 100, (AA.aa_init[0, num - 1, num / 100].q.val | 1) - 2, 1 + AA.aa_zero[0, num - 1, num / 100].q.val].q.val; } private static int test_3_10(int num) { object bb = AA.aa_init[0, num - 1, num / 100].q.val; return (int)bb; } private static int test_3_11(int num) { double dbl = AA.aa_init[0, num - 1, num / 100].q.val; return (int)dbl; } private static int test_3_12(int num) { return AA.call_target(AA.aa_init[0, num - 1, num / 100].q).val; } private static int test_3_13(int num) { return AA.call_target_ref(ref AA.aa_init[0, num - 1, num / 100].q).val; } private static int test_3_14(int num) { return AA.aa_init[0, num - 1, num / 100].q.ret_code(); } private static int test_4_0(int num) { return BB.f_init.q.val; } private static int test_4_1(int num) { BB.f_zero.q.val = num; return BB.f_zero.q.val; } private static int test_4_2(int num) { if (BB.f_init.q.val != BB.f_zero.q.val) return 100; else return BB.f_zero.q.val; } private static int test_4_3(int num) { return BB.f_init.q.val < num + 1 ? 100 : -1; } private static int test_4_4(int num) { return (BB.f_init.q.val > BB.f_zero.q.val ? 1 : 0) + 99; } private static int test_4_5(int num) { return (BB.f_init.q.val ^ BB.f_zero.q.val) | num; } private static int test_4_6(int num) { BB.f_zero.q.val |= BB.f_init.q.val; return BB.f_zero.q.val & num; } private static int test_4_7(int num) { return BB.f_init.q.val >> BB.f_zero.q.val; } private static int test_4_8(int num) { return AA.a_init[BB.f_init.q.val].q.val; } private static int test_4_9(int num) { return AA.aa_init[num - 100, (BB.f_init.q.val | 1) - 2, 1 + BB.f_zero.q.val].q.val; } private static int test_4_10(int num) { object bb = BB.f_init.q.val; return (int)bb; } private static int test_4_11(int num) { double dbl = BB.f_init.q.val; return (int)dbl; } private static int test_4_12(int num) { return AA.call_target(BB.f_init.q).val; } private static int test_4_13(int num) { return AA.call_target_ref(ref BB.f_init.q).val; } private static int test_4_14(int num) { return BB.f_init.q.ret_code(); } private static int test_5_0(int num) { return ((AA)AA.b_init).q.val; } private static int test_6_0(int num, TypedReference tr_init) { return __refvalue(tr_init, AA).q.val; } internal static unsafe int RunAllTests() { AA.reset(); if (test_0_0(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_0() failed."); return 101; } AA.verify_all(); AA.reset(); if (test_0_1(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_1() failed."); return 102; } AA.verify_all(); AA.reset(); if (test_0_2(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_2() failed."); return 103; } AA.verify_all(); AA.reset(); if (test_0_3(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_3() failed."); return 104; } AA.verify_all(); AA.reset(); if (test_0_4(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_4() failed."); return 105; } AA.verify_all(); AA.reset(); if (test_0_5(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_5() failed."); return 106; } AA.verify_all(); AA.reset(); if (test_0_6(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_6() failed."); return 107; } AA.verify_all(); AA.reset(); if (test_0_7(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_7() failed."); return 108; } AA.verify_all(); AA.reset(); if (test_0_8(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_8() failed."); return 109; } AA.verify_all(); AA.reset(); if (test_0_9(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_9() failed."); return 110; } AA.verify_all(); AA.reset(); if (test_0_10(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_10() failed."); return 111; } AA.verify_all(); AA.reset(); if (test_0_11(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_11() failed."); return 112; } AA.verify_all(); AA.reset(); if (test_0_12(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_12() failed."); return 113; } AA.verify_all(); AA.reset(); if (test_0_13(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_13() failed."); return 114; } AA.verify_all(); AA.reset(); if (test_0_14(100, new AA(100), new AA(0)) != 100) { Console.WriteLine("test_0_14() failed."); return 115; } AA.verify_all(); AA.reset(); if (test_1_0(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_0() failed."); return 116; } AA.verify_all(); AA.reset(); if (test_1_1(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_1() failed."); return 117; } AA.verify_all(); AA.reset(); if (test_1_2(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_2() failed."); return 118; } AA.verify_all(); AA.reset(); if (test_1_3(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_3() failed."); return 119; } AA.verify_all(); AA.reset(); if (test_1_4(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_4() failed."); return 120; } AA.verify_all(); AA.reset(); if (test_1_5(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_5() failed."); return 121; } AA.verify_all(); AA.reset(); if (test_1_6(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_6() failed."); return 122; } AA.verify_all(); AA.reset(); if (test_1_7(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_7() failed."); return 123; } AA.verify_all(); AA.reset(); if (test_1_8(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_8() failed."); return 124; } AA.verify_all(); AA.reset(); if (test_1_9(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_9() failed."); return 125; } AA.verify_all(); AA.reset(); if (test_1_10(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_10() failed."); return 126; } AA.verify_all(); AA.reset(); if (test_1_11(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_11() failed."); return 127; } AA.verify_all(); AA.reset(); if (test_1_12(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_12() failed."); return 128; } AA.verify_all(); AA.reset(); if (test_1_13(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_13() failed."); return 129; } AA.verify_all(); AA.reset(); if (test_1_14(100, ref AA._init, ref AA._zero) != 100) { Console.WriteLine("test_1_14() failed."); return 130; } AA.verify_all(); AA.reset(); if (test_2_0(100) != 100) { Console.WriteLine("test_2_0() failed."); return 131; } AA.verify_all(); AA.reset(); if (test_2_1(100) != 100) { Console.WriteLine("test_2_1() failed."); return 132; } AA.verify_all(); AA.reset(); if (test_2_2(100) != 100) { Console.WriteLine("test_2_2() failed."); return 133; } AA.verify_all(); AA.reset(); if (test_2_3(100) != 100) { Console.WriteLine("test_2_3() failed."); return 134; } AA.verify_all(); AA.reset(); if (test_2_4(100) != 100) { Console.WriteLine("test_2_4() failed."); return 135; } AA.verify_all(); AA.reset(); if (test_2_5(100) != 100) { Console.WriteLine("test_2_5() failed."); return 136; } AA.verify_all(); AA.reset(); if (test_2_6(100) != 100) { Console.WriteLine("test_2_6() failed."); return 137; } AA.verify_all(); AA.reset(); if (test_2_7(100) != 100) { Console.WriteLine("test_2_7() failed."); return 138; } AA.verify_all(); AA.reset(); if (test_2_8(100) != 100) { Console.WriteLine("test_2_8() failed."); return 139; } AA.verify_all(); AA.reset(); if (test_2_9(100) != 100) { Console.WriteLine("test_2_9() failed."); return 140; } AA.verify_all(); AA.reset(); if (test_2_10(100) != 100) { Console.WriteLine("test_2_10() failed."); return 141; } AA.verify_all(); AA.reset(); if (test_2_11(100) != 100) { Console.WriteLine("test_2_11() failed."); return 142; } AA.verify_all(); AA.reset(); if (test_2_12(100) != 100) { Console.WriteLine("test_2_12() failed."); return 143; } AA.verify_all(); AA.reset(); if (test_2_13(100) != 100) { Console.WriteLine("test_2_13() failed."); return 144; } AA.verify_all(); AA.reset(); if (test_2_14(100) != 100) { Console.WriteLine("test_2_14() failed."); return 145; } AA.verify_all(); AA.reset(); if (test_3_0(100) != 100) { Console.WriteLine("test_3_0() failed."); return 146; } AA.verify_all(); AA.reset(); if (test_3_1(100) != 100) { Console.WriteLine("test_3_1() failed."); return 147; } AA.verify_all(); AA.reset(); if (test_3_2(100) != 100) { Console.WriteLine("test_3_2() failed."); return 148; } AA.verify_all(); AA.reset(); if (test_3_3(100) != 100) { Console.WriteLine("test_3_3() failed."); return 149; } AA.verify_all(); AA.reset(); if (test_3_4(100) != 100) { Console.WriteLine("test_3_4() failed."); return 150; } AA.verify_all(); AA.reset(); if (test_3_5(100) != 100) { Console.WriteLine("test_3_5() failed."); return 151; } AA.verify_all(); AA.reset(); if (test_3_6(100) != 100) { Console.WriteLine("test_3_6() failed."); return 152; } AA.verify_all(); AA.reset(); if (test_3_7(100) != 100) { Console.WriteLine("test_3_7() failed."); return 153; } AA.verify_all(); AA.reset(); if (test_3_8(100) != 100) { Console.WriteLine("test_3_8() failed."); return 154; } AA.verify_all(); AA.reset(); if (test_3_9(100) != 100) { Console.WriteLine("test_3_9() failed."); return 155; } AA.verify_all(); AA.reset(); if (test_3_10(100) != 100) { Console.WriteLine("test_3_10() failed."); return 156; } AA.verify_all(); AA.reset(); if (test_3_11(100) != 100) { Console.WriteLine("test_3_11() failed."); return 157; } AA.verify_all(); AA.reset(); if (test_3_12(100) != 100) { Console.WriteLine("test_3_12() failed."); return 158; } AA.verify_all(); AA.reset(); if (test_3_13(100) != 100) { Console.WriteLine("test_3_13() failed."); return 159; } AA.verify_all(); AA.reset(); if (test_3_14(100) != 100) { Console.WriteLine("test_3_14() failed."); return 160; } AA.verify_all(); AA.reset(); if (test_4_0(100) != 100) { Console.WriteLine("test_4_0() failed."); return 161; } AA.verify_all(); AA.reset(); if (test_4_1(100) != 100) { Console.WriteLine("test_4_1() failed."); return 162; } AA.verify_all(); AA.reset(); if (test_4_2(100) != 100) { Console.WriteLine("test_4_2() failed."); return 163; } AA.verify_all(); AA.reset(); if (test_4_3(100) != 100) { Console.WriteLine("test_4_3() failed."); return 164; } AA.verify_all(); AA.reset(); if (test_4_4(100) != 100) { Console.WriteLine("test_4_4() failed."); return 165; } AA.verify_all(); AA.reset(); if (test_4_5(100) != 100) { Console.WriteLine("test_4_5() failed."); return 166; } AA.verify_all(); AA.reset(); if (test_4_6(100) != 100) { Console.WriteLine("test_4_6() failed."); return 167; } AA.verify_all(); AA.reset(); if (test_4_7(100) != 100) { Console.WriteLine("test_4_7() failed."); return 168; } AA.verify_all(); AA.reset(); if (test_4_8(100) != 100) { Console.WriteLine("test_4_8() failed."); return 169; } AA.verify_all(); AA.reset(); if (test_4_9(100) != 100) { Console.WriteLine("test_4_9() failed."); return 170; } AA.verify_all(); AA.reset(); if (test_4_10(100) != 100) { Console.WriteLine("test_4_10() failed."); return 171; } AA.verify_all(); AA.reset(); if (test_4_11(100) != 100) { Console.WriteLine("test_4_11() failed."); return 172; } AA.verify_all(); AA.reset(); if (test_4_12(100) != 100) { Console.WriteLine("test_4_12() failed."); return 173; } AA.verify_all(); AA.reset(); if (test_4_13(100) != 100) { Console.WriteLine("test_4_13() failed."); return 174; } AA.verify_all(); AA.reset(); if (test_4_14(100) != 100) { Console.WriteLine("test_4_14() failed."); return 175; } AA.verify_all(); AA.reset(); if (test_5_0(100) != 100) { Console.WriteLine("test_5_0() failed."); return 176; } AA.verify_all(); AA.reset(); if (test_6_0(100, __makeref(AA._init)) != 100) { Console.WriteLine("test_6_0() failed."); return 177; } AA.verify_all(); Console.WriteLine("All tests passed."); return 100; } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Methodical/explicit/coverage/expl_double_1_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <DebugType>None</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="expl_double_1.cs" /> <Compile Include="body_double.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <DebugType>None</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="expl_double_1.cs" /> <Compile Include="body_double.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Globalization { // needs to be kept in sync with CalendarDataType in System.Globalization.Native internal enum CalendarDataType { Uninitialized = 0, NativeName = 1, MonthDay = 2, ShortDates = 3, LongDates = 4, YearMonths = 5, DayNames = 6, AbbrevDayNames = 7, MonthNames = 8, AbbrevMonthNames = 9, SuperShortDayNames = 10, MonthGenitiveNames = 11, AbbrevMonthGenitiveNames = 12, EraNames = 13, AbbrevEraNames = 14, } internal sealed partial class CalendarData { private bool IcuLoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { Debug.Assert(!GlobalizationMode.UseNls); bool result = true; // these can return null but are later replaced with String.Empty or other non-nullable value result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName!); result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay!); if (this.sMonthDay != null) { this.sMonthDay = NormalizeDatePattern(this.sMonthDay); } result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates!); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates!); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths!); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames!); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames!); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames!); string? leapHebrewMonthName = null; result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames!, ref leapHebrewMonthName); if (leapHebrewMonthName != null) { Debug.Assert(this.saMonthNames != null); // In Hebrew calendar, get the leap month name Adar II and override the non-leap month 7 Debug.Assert(calendarId == CalendarId.HEBREW && saMonthNames.Length == 13); saLeapYearMonthNames = (string[]) saMonthNames.Clone(); saLeapYearMonthNames[6] = leapHebrewMonthName; // The returned data from ICU has 6th month name as 'Adar I' and 7th month name as 'Adar' // We need to adjust that in the list used with non-leap year to have 6th month as 'Adar' and 7th month as 'Adar II' // note that when formatting non-leap year dates, 7th month shouldn't get used at all. saMonthNames[5] = saMonthNames[6]; saMonthNames[6] = leapHebrewMonthName; } result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames!, ref leapHebrewMonthName); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames!, ref leapHebrewMonthName); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames!, ref leapHebrewMonthName); result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames!); result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames!); return result; } internal static int IcuGetTwoDigitYearMax() { Debug.Assert(!GlobalizationMode.UseNls); // There is no user override for this value on Linux or in ICU. // So just return -1 to use the hard-coded defaults. return -1; } // Call native side to figure out which calendars are allowed internal static int IcuGetCalendars(string localeName, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); // NOTE: there are no 'user overrides' on Linux int count = Interop.Globalization.GetCalendars(localeName, calendars, calendars.Length); // ensure there is at least 1 calendar returned if (count == 0 && calendars.Length > 0) { calendars[0] = CalendarId.GREGORIAN; count = 1; } return count; } private static bool IcuSystemSupportsTaiwaneseCalendar() { Debug.Assert(!GlobalizationMode.UseNls); return true; } // PAL Layer ends here private static unsafe bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string? calendarString) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.CallStringMethod( static (buffer, locale, id, type) => { fixed (char* bufferPtr = buffer) { return Interop.Globalization.GetCalendarInfo(locale, id, type, bufferPtr, buffer.Length); } }, localeName, calendarId, dataType, out calendarString); } private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? datePatterns) { datePatterns = null; IcuEnumCalendarsData callbackContext = default; callbackContext.Results = new List<string>(); callbackContext.DisallowDuplicates = true; bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { List<string> datePatternsList = callbackContext.Results; for (int i = 0; i < datePatternsList.Count; i++) { datePatternsList[i] = NormalizeDatePattern(datePatternsList[i]); } if (dataType == CalendarDataType.ShortDates) FixDefaultShortDatePattern(datePatternsList); datePatterns = datePatternsList.ToArray(); } return result; } // FixDefaultShortDatePattern will convert the default short date pattern from using 'yy' to using 'yyyy' // And will ensure the original pattern still exist in the list. // doing that will have the short date pattern format the year as 4-digit number and not just 2-digit number. // Example: June 5, 2018 will be formatted to something like 6/5/2018 instead of 6/5/18 fro en-US culture. private static void FixDefaultShortDatePattern(List<string> shortDatePatterns) { if (shortDatePatterns.Count == 0) return; string s = shortDatePatterns[0]; // We are not expecting any pattern have length more than 100. // We have to do this check to prevent stack overflow as we allocate the buffer on the stack. if (s.Length > 100) return; Span<char> modifiedPattern = stackalloc char[s.Length + 2]; int index = 0; while (index < s.Length) { if (s[index] == '\'') { do { modifiedPattern[index] = s[index]; index++; } while (index < s.Length && s[index] != '\''); if (index >= s.Length) return; } else if (s[index] == 'y') { modifiedPattern[index] = 'y'; break; } modifiedPattern[index] = s[index]; index++; } if (index >= s.Length - 1 || s[index + 1] != 'y') { // not a 'yy' pattern return; } if (index + 2 < s.Length && s[index + 2] == 'y') { // we have 'yyy' then nothing to do return; } // we are sure now we have 'yy' pattern Debug.Assert(index + 3 < modifiedPattern.Length); modifiedPattern[index + 1] = 'y'; // second y modifiedPattern[index + 2] = 'y'; // third y modifiedPattern[index + 3] = 'y'; // fourth y index += 2; // Now, copy the rest of the pattern to the destination buffer while (index < s.Length) { modifiedPattern[index + 2] = s[index]; index++; } shortDatePatterns[0] = modifiedPattern.ToString(); for (int i = 1; i < shortDatePatterns.Count; i++) { if (shortDatePatterns[i] == shortDatePatterns[0]) { // Found match in the list to the new constructed pattern, then replace it with the original modified pattern shortDatePatterns[i] = s; return; } } // if we come here means the newly constructed pattern not found on the list, then add the original pattern shortDatePatterns.Add(s); } /// <summary> /// The ICU date format characters are not exactly the same as the .NET date format characters. /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern. /// </summary> /// <remarks> /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// </remarks> private static string NormalizeDatePattern(string input) { var destination = input.Length < 128 ? new ValueStringBuilder(stackalloc char[128]) : new ValueStringBuilder(input.Length); int index = 0; while (index < input.Length) { switch (input[index]) { case '\'': // single quotes escape characters, like 'de' in es-SP // so read verbatim until the next single quote destination.Append(input[index++]); while (index < input.Length) { char current = input[index++]; destination.Append(current); if (current == '\'') { break; } } break; case 'E': case 'e': case 'c': // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET // 'e' in ICU is the local day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET NormalizeDayOfWeek(input, ref destination, ref index); break; case 'L': case 'M': // 'L' in ICU is the stand-alone name of the month, // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns // 'M' in both ICU and .NET is the month, // but ICU supports 5 'M's, which is the super short month name int occurrences = CountOccurrences(input, input[index], ref index); if (occurrences > 4) { // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET occurrences = 3; } destination.Append('M', occurrences); break; case 'G': // 'G' in ICU is the era, which maps to 'g' in .NET CountOccurrences(input, 'G', ref index); // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they // have the same meaning destination.Append('g'); break; case 'y': // a single 'y' in ICU is the year with no padding or trimming. // a single 'y' in .NET is the year with 1 or 2 digits // so convert any single 'y' to 'yyyy' occurrences = CountOccurrences(input, 'y', ref index); if (occurrences == 1) { occurrences = 4; } destination.Append('y', occurrences); break; default: const string unsupportedDateFieldSymbols = "YuUrQqwWDFg"; Debug.Assert(!unsupportedDateFieldSymbols.Contains(input[index]), $"Encountered an unexpected date field symbol '{input[index]}' from ICU which has no known corresponding .NET equivalent."); destination.Append(input[index++]); break; } } return destination.ToString(); } private static void NormalizeDayOfWeek(string input, ref ValueStringBuilder destination, ref int index) { char dayChar = input[index]; int occurrences = CountOccurrences(input, dayChar, ref index); occurrences = Math.Max(occurrences, 3); if (occurrences > 4) { // 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET occurrences = 3; } destination.Append('d', occurrences); } private static int CountOccurrences(string input, char value, ref int index) { int startIndex = index; while (index < input.Length && input[index] == value) { index++; } return index - startIndex; } private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? monthNames, ref string? leapHebrewMonthName) { monthNames = null; IcuEnumCalendarsData callbackContext = default; callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { // the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an // extra empty string to fill the array. if (callbackContext.Results.Count == 12) { callbackContext.Results.Add(string.Empty); } if (callbackContext.Results.Count > 13) { Debug.Assert(calendarId == CalendarId.HEBREW && callbackContext.Results.Count == 14); if (calendarId == CalendarId.HEBREW) { leapHebrewMonthName = callbackContext.Results[13]; } callbackContext.Results.RemoveRange(13, callbackContext.Results.Count - 13); } monthNames = callbackContext.Results.ToArray(); } return result; } private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? eraNames) { bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames); // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames?.Length > 0) { string[] latestEraName = new string[] { eraNames![eraNames.Length - 1] }; eraNames = latestEraName; } return result; } internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? calendarData) { calendarData = null; IcuEnumCalendarsData callbackContext = default; callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { calendarData = callbackContext.Results.ToArray(); } return result; } private static unsafe bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, ref IcuEnumCalendarsData callbackContext) { return Interop.Globalization.EnumCalendarInfo(&EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)Unsafe.AsPointer(ref callbackContext)); } [UnmanagedCallersOnly] private static unsafe void EnumCalendarInfoCallback(char* calendarStringPtr, IntPtr context) { try { ReadOnlySpan<char> calendarStringSpan = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(calendarStringPtr); ref IcuEnumCalendarsData callbackContext = ref Unsafe.As<byte, IcuEnumCalendarsData>(ref *(byte*)context); if (callbackContext.DisallowDuplicates) { foreach (string existingResult in callbackContext.Results) { if (string.CompareOrdinal(calendarStringSpan, existingResult) == 0) { // the value is already in the results, so don't add it again return; } } } callbackContext.Results.Add(calendarStringSpan.ToString()); } catch (Exception e) { Debug.Fail(e.ToString()); // we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code. // If we don't ignore the exception here that can cause the runtime to fail fast. } } private struct IcuEnumCalendarsData { public List<string> Results; public bool DisallowDuplicates; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Globalization { // needs to be kept in sync with CalendarDataType in System.Globalization.Native internal enum CalendarDataType { Uninitialized = 0, NativeName = 1, MonthDay = 2, ShortDates = 3, LongDates = 4, YearMonths = 5, DayNames = 6, AbbrevDayNames = 7, MonthNames = 8, AbbrevMonthNames = 9, SuperShortDayNames = 10, MonthGenitiveNames = 11, AbbrevMonthGenitiveNames = 12, EraNames = 13, AbbrevEraNames = 14, } internal sealed partial class CalendarData { private bool IcuLoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { Debug.Assert(!GlobalizationMode.UseNls); bool result = true; // these can return null but are later replaced with String.Empty or other non-nullable value result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName!); result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay!); if (this.sMonthDay != null) { this.sMonthDay = NormalizeDatePattern(this.sMonthDay); } result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates!); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates!); result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths!); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames!); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames!); result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames!); string? leapHebrewMonthName = null; result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames!, ref leapHebrewMonthName); if (leapHebrewMonthName != null) { Debug.Assert(this.saMonthNames != null); // In Hebrew calendar, get the leap month name Adar II and override the non-leap month 7 Debug.Assert(calendarId == CalendarId.HEBREW && saMonthNames.Length == 13); saLeapYearMonthNames = (string[]) saMonthNames.Clone(); saLeapYearMonthNames[6] = leapHebrewMonthName; // The returned data from ICU has 6th month name as 'Adar I' and 7th month name as 'Adar' // We need to adjust that in the list used with non-leap year to have 6th month as 'Adar' and 7th month as 'Adar II' // note that when formatting non-leap year dates, 7th month shouldn't get used at all. saMonthNames[5] = saMonthNames[6]; saMonthNames[6] = leapHebrewMonthName; } result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames!, ref leapHebrewMonthName); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames!, ref leapHebrewMonthName); result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames!, ref leapHebrewMonthName); result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames!); result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames!); return result; } internal static int IcuGetTwoDigitYearMax() { Debug.Assert(!GlobalizationMode.UseNls); // There is no user override for this value on Linux or in ICU. // So just return -1 to use the hard-coded defaults. return -1; } // Call native side to figure out which calendars are allowed internal static int IcuGetCalendars(string localeName, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!GlobalizationMode.UseNls); // NOTE: there are no 'user overrides' on Linux int count = Interop.Globalization.GetCalendars(localeName, calendars, calendars.Length); // ensure there is at least 1 calendar returned if (count == 0 && calendars.Length > 0) { calendars[0] = CalendarId.GREGORIAN; count = 1; } return count; } private static bool IcuSystemSupportsTaiwaneseCalendar() { Debug.Assert(!GlobalizationMode.UseNls); return true; } // PAL Layer ends here private static unsafe bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string? calendarString) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.CallStringMethod( static (buffer, locale, id, type) => { fixed (char* bufferPtr = buffer) { return Interop.Globalization.GetCalendarInfo(locale, id, type, bufferPtr, buffer.Length); } }, localeName, calendarId, dataType, out calendarString); } private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? datePatterns) { datePatterns = null; IcuEnumCalendarsData callbackContext = default; callbackContext.Results = new List<string>(); callbackContext.DisallowDuplicates = true; bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { List<string> datePatternsList = callbackContext.Results; for (int i = 0; i < datePatternsList.Count; i++) { datePatternsList[i] = NormalizeDatePattern(datePatternsList[i]); } if (dataType == CalendarDataType.ShortDates) FixDefaultShortDatePattern(datePatternsList); datePatterns = datePatternsList.ToArray(); } return result; } // FixDefaultShortDatePattern will convert the default short date pattern from using 'yy' to using 'yyyy' // And will ensure the original pattern still exist in the list. // doing that will have the short date pattern format the year as 4-digit number and not just 2-digit number. // Example: June 5, 2018 will be formatted to something like 6/5/2018 instead of 6/5/18 fro en-US culture. private static void FixDefaultShortDatePattern(List<string> shortDatePatterns) { if (shortDatePatterns.Count == 0) return; string s = shortDatePatterns[0]; // We are not expecting any pattern have length more than 100. // We have to do this check to prevent stack overflow as we allocate the buffer on the stack. if (s.Length > 100) return; Span<char> modifiedPattern = stackalloc char[s.Length + 2]; int index = 0; while (index < s.Length) { if (s[index] == '\'') { do { modifiedPattern[index] = s[index]; index++; } while (index < s.Length && s[index] != '\''); if (index >= s.Length) return; } else if (s[index] == 'y') { modifiedPattern[index] = 'y'; break; } modifiedPattern[index] = s[index]; index++; } if (index >= s.Length - 1 || s[index + 1] != 'y') { // not a 'yy' pattern return; } if (index + 2 < s.Length && s[index + 2] == 'y') { // we have 'yyy' then nothing to do return; } // we are sure now we have 'yy' pattern Debug.Assert(index + 3 < modifiedPattern.Length); modifiedPattern[index + 1] = 'y'; // second y modifiedPattern[index + 2] = 'y'; // third y modifiedPattern[index + 3] = 'y'; // fourth y index += 2; // Now, copy the rest of the pattern to the destination buffer while (index < s.Length) { modifiedPattern[index + 2] = s[index]; index++; } shortDatePatterns[0] = modifiedPattern.ToString(); for (int i = 1; i < shortDatePatterns.Count; i++) { if (shortDatePatterns[i] == shortDatePatterns[0]) { // Found match in the list to the new constructed pattern, then replace it with the original modified pattern shortDatePatterns[i] = s; return; } } // if we come here means the newly constructed pattern not found on the list, then add the original pattern shortDatePatterns.Add(s); } /// <summary> /// The ICU date format characters are not exactly the same as the .NET date format characters. /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern. /// </summary> /// <remarks> /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// </remarks> private static string NormalizeDatePattern(string input) { var destination = input.Length < 128 ? new ValueStringBuilder(stackalloc char[128]) : new ValueStringBuilder(input.Length); int index = 0; while (index < input.Length) { switch (input[index]) { case '\'': // single quotes escape characters, like 'de' in es-SP // so read verbatim until the next single quote destination.Append(input[index++]); while (index < input.Length) { char current = input[index++]; destination.Append(current); if (current == '\'') { break; } } break; case 'E': case 'e': case 'c': // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET // 'e' in ICU is the local day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but // maps closest to 3 or 4 'd's in .NET NormalizeDayOfWeek(input, ref destination, ref index); break; case 'L': case 'M': // 'L' in ICU is the stand-alone name of the month, // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns // 'M' in both ICU and .NET is the month, // but ICU supports 5 'M's, which is the super short month name int occurrences = CountOccurrences(input, input[index], ref index); if (occurrences > 4) { // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET occurrences = 3; } destination.Append('M', occurrences); break; case 'G': // 'G' in ICU is the era, which maps to 'g' in .NET CountOccurrences(input, 'G', ref index); // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they // have the same meaning destination.Append('g'); break; case 'y': // a single 'y' in ICU is the year with no padding or trimming. // a single 'y' in .NET is the year with 1 or 2 digits // so convert any single 'y' to 'yyyy' occurrences = CountOccurrences(input, 'y', ref index); if (occurrences == 1) { occurrences = 4; } destination.Append('y', occurrences); break; default: const string unsupportedDateFieldSymbols = "YuUrQqwWDFg"; Debug.Assert(!unsupportedDateFieldSymbols.Contains(input[index]), $"Encountered an unexpected date field symbol '{input[index]}' from ICU which has no known corresponding .NET equivalent."); destination.Append(input[index++]); break; } } return destination.ToString(); } private static void NormalizeDayOfWeek(string input, ref ValueStringBuilder destination, ref int index) { char dayChar = input[index]; int occurrences = CountOccurrences(input, dayChar, ref index); occurrences = Math.Max(occurrences, 3); if (occurrences > 4) { // 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET occurrences = 3; } destination.Append('d', occurrences); } private static int CountOccurrences(string input, char value, ref int index) { int startIndex = index; while (index < input.Length && input[index] == value) { index++; } return index - startIndex; } private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? monthNames, ref string? leapHebrewMonthName) { monthNames = null; IcuEnumCalendarsData callbackContext = default; callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { // the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an // extra empty string to fill the array. if (callbackContext.Results.Count == 12) { callbackContext.Results.Add(string.Empty); } if (callbackContext.Results.Count > 13) { Debug.Assert(calendarId == CalendarId.HEBREW && callbackContext.Results.Count == 14); if (calendarId == CalendarId.HEBREW) { leapHebrewMonthName = callbackContext.Results[13]; } callbackContext.Results.RemoveRange(13, callbackContext.Results.Count - 13); } monthNames = callbackContext.Results.ToArray(); } return result; } private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? eraNames) { bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames); // .NET expects that only the Japanese calendars have more than 1 era. // So for other calendars, only return the latest era. if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames?.Length > 0) { string[] latestEraName = new string[] { eraNames![eraNames.Length - 1] }; eraNames = latestEraName; } return result; } internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[]? calendarData) { calendarData = null; IcuEnumCalendarsData callbackContext = default; callbackContext.Results = new List<string>(); bool result = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (result) { calendarData = callbackContext.Results.ToArray(); } return result; } private static unsafe bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, ref IcuEnumCalendarsData callbackContext) { return Interop.Globalization.EnumCalendarInfo(&EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)Unsafe.AsPointer(ref callbackContext)); } [UnmanagedCallersOnly] private static unsafe void EnumCalendarInfoCallback(char* calendarStringPtr, IntPtr context) { try { ReadOnlySpan<char> calendarStringSpan = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(calendarStringPtr); ref IcuEnumCalendarsData callbackContext = ref Unsafe.As<byte, IcuEnumCalendarsData>(ref *(byte*)context); if (callbackContext.DisallowDuplicates) { foreach (string existingResult in callbackContext.Results) { if (string.CompareOrdinal(calendarStringSpan, existingResult) == 0) { // the value is already in the results, so don't add it again return; } } } callbackContext.Results.Add(calendarStringSpan.ToString()); } catch (Exception e) { Debug.Fail(e.ToString()); // we ignore the managed exceptions here because EnumCalendarInfoCallback will get called from the native code. // If we don't ignore the exception here that can cause the runtime to fail fast. } } private struct IcuEnumCalendarsData { public List<string> Results; public bool DisallowDuplicates; } } }
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/libraries/System.Security.Cryptography.Primitives/ref/System.Security.Cryptography.Primitives.Forwards.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ // System.Runtime [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicException))] // System.Security.Cryptography [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.AsymmetricAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CipherMode))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicOperations))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicUnexpectedOperationException))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptoStream))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptoStreamMode))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HashAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HashAlgorithmName))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HMAC))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.ICryptoTransform))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.KeyedHashAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.KeySizes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.PaddingMode))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.PbeEncryptionAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.PbeParameters))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.SymmetricAlgorithm))]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ // System.Runtime [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicException))] // System.Security.Cryptography [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.AsymmetricAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CipherMode))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicOperations))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptographicUnexpectedOperationException))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptoStream))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.CryptoStreamMode))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HashAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HashAlgorithmName))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.HMAC))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.ICryptoTransform))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.KeyedHashAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.KeySizes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.PaddingMode))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.PbeEncryptionAlgorithm))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.PbeParameters))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Security.Cryptography.SymmetricAlgorithm))]
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/CodeGenBringUpTests/DblArea_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="DblArea.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="DblArea.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b56068/b56068.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).il" /> </ItemGroup> </Project>
-1
dotnet/runtime
65,973
[hot_reload] various post-Preview 1 fixes
A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
lambdageek
2022-02-28T20:29:18Z
2022-03-01T21:17:38Z
002647fce853a359a826461c06f5f530e2bb939e
2a00ad862b4d43521297ab4f1d4946fd1e718b90
[hot_reload] various post-Preview 1 fixes. A collection of changes building on top of what is in .NET 7 Preview 1 and #65865: 1. In cases where we tell the interpreter to generate sequence points, but where the hot reload deltas don't include PDBs (basicallyi `dotnet watch`) treat added methods as having zero sequence points. This is a follow-up to #65865 which actually makes it possible to add static lambdas. 2. Allow custom attribute deletions. In the case of nullability attributes, we get deletions (modifications that set the Parent to row 0) even if we don't declare a `ChangeCustomAttribute` capability. We intend to support custom attribute deletions in .NET 7, so this is fine. 3. Fix an off by one error where the last modified method in a delta was considered a method addition. Contributes to #51126
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/LoadVector64.Int16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void LoadVector64_Int16() { var test = new LoadUnaryOpTest__LoadVector64_Int16(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_Load(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class LoadUnaryOpTest__LoadVector64_Int16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadVector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadVector64( (Int16*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector64), new Type[] { typeof(Int16*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Int16*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector64<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector64)}<Int16>(Vector64<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void LoadVector64_Int16() { var test = new LoadUnaryOpTest__LoadVector64_Int16(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_Load(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class LoadUnaryOpTest__LoadVector64_Int16 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadVector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadVector64( (Int16*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector64), new Type[] { typeof(Int16*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Int16*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector64<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector64)}<Int16>(Vector64<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1